# @ifloom/audio (https://ifloom.dev/docs/api/audio) Generated from the source of `@ifloom/audio` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. - Functions: [`startAudio`](#startaudio) - Types: [`AudioLike`](#audiolike), [`AudioOptions`](#audiooptions), [`AudioPlayer`](#audioplayer) ## AudioLike [#audiolike] Type. Explained in [The audio player](https://ifloom.dev/docs/reference/browser/audio-player#audiolike). The part of an `HTMLAudioElement` that the audio player uses. Tests pass a fake through `AudioOptions.createAudio`. ```ts shape import type { AudioLike } from '@ifloom/audio' type AudioLike = { play: () => void | Promise pause: () => void volume: number loop: boolean currentTime: number readonly ended: boolean onended: ((event: Event) => void) | null src: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `play` | `() => void \| Promise` | | | Starts playing. The browser may refuse, by throwing or by rejecting the promise it returns. | | `pause` | `() => void` | | | Pauses playing. | | `volume` | `number` | | | The element's volume, from 0 to 1. | | `loop` | `boolean` | | | True when the element starts again from the beginning as it ends. | | `currentTime` | `number` | | | The element's position in the file, in seconds. | | `ended` | `boolean` | | | True once the element has played to its end. | | `onended` | `((event: Event) => void) \| null` | | | The handler the element calls when it plays to its end. | | `src` | `string` | | | The element's file. | ## AudioOptions [#audiooptions] Type. Explained in [The audio player](https://ifloom.dev/docs/reference/browser/audio-player#audiooptions). Settings for `startAudio`. Each is optional. ```ts shape import type { AudioOptions } from '@ifloom/audio' type AudioOptions = { createAudio?: (src: string) => AudioLike log?: (message: string) => void root?: EventTarget } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `createAudio` | `(src: string) =>` [`AudioLike`](#audiolike) | yes | | The function that makes the element for a file. `new Audio(src)` if left out. | | `log` | `(message: string) => void` | yes | | A function that receives a line for each decision the player makes, for debugging, such as `console.debug`. | | `root` | `EventTarget` | yes | | The element whose first `pointerdown` or `keydown` unlocks sound. `document` if left out. | ## AudioPlayer [#audioplayer] Type. Explained in [The audio player](https://ifloom.dev/docs/reference/browser/audio-player#audioplayer). The audio player `startAudio` returns, a function that stops it with two methods on it. Calling it stops following the runner and the page's clicks and key presses, and pauses every sound. ```ts shape import type { AudioPlayer } from '@ifloom/audio' type AudioPlayer = (() => void) & { unlock(): void; play(src: string, channel?: string, volume?: number): void } ``` ## startAudio [#startaudio] Function. Explained in [The audio player](https://ifloom.dev/docs/reference/browser/audio-player#startaudio). Starts playing a runner's `view.audio` in the browser, and returns the `AudioPlayer` that stops it. Nothing plays until the player first clicks or presses a key, or until `unlock()`. Background channels crossfade when their file changes, and step through playlists. Each cue key plays once, and the player counts the cues already in the view when it starts as heard, so loading a save replays nothing. Volumes and muting follow the game's settings in the runner's snapshot. ```ts shape import { startAudio } from '@ifloom/audio' function startAudio(runner: Runner, options?: AudioOptions): AudioPlayer ``` Uses: [`Runner`](https://ifloom.dev/docs/api/engine#runner), [`AudioOptions`](#audiooptions), [`AudioPlayer`](#audioplayer). # @ifloom/browser (https://ifloom.dev/docs/api/browser) Generated from the source of `@ifloom/browser` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. - Functions: [`browserRunner`](#browserrunner), [`dialogOpen`](#dialogopen), [`ignoredKey`](#ignoredkey), [`indexedDbDriver`](#indexeddbdriver), [`localStorageDriver`](#localstoragedriver), [`minigameInput`](#minigameinput), [`nextSlot`](#nextslot), [`numberedChoices`](#numberedchoices), [`startClock`](#startclock), [`startKeys`](#startkeys), [`startMinigameKeys`](#startminigamekeys), [`startRevealSkip`](#startrevealskip) - Types: [`ClockOptions`](#clockoptions), [`IndexedDbLike`](#indexeddblike), [`KeysOptions`](#keysoptions), [`StorageLike`](#storagelike) ## browserRunner [#browserrunner] Function. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#browserrunner). Returns a runner set up for a browser, with saves and a profile in `localStorage`. Each runner option you pass replaces that option's default whole. The defaults are a new game with a random seed, undo 50 steps deep and an autosave each turn. It reads the profile before it starts, so the new game has the player's play settings and `settings()` has their UI settings from the first frame. Pass `start` to begin from another state. The React UI's `mountGame` and the templates use it. ```ts shape import { browserRunner } from '@ifloom/browser' function browserRunner(game: Game, options?: RunnerOptions & { start?: GameState }): Promise ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`RunnerOptions`](https://ifloom.dev/docs/api/engine#runneroptions), [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Runner`](https://ifloom.dev/docs/api/engine#runner). ## ClockOptions [#clockoptions] Type. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#clockoptions). Settings for `startClock`. Each is optional. ```ts shape import type { ClockOptions } from '@ifloom/browser' type ClockOptions = { every?: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `every` | `number` | yes | | The clock's interval between ticks while a timer or a minigame counts down, in milliseconds. 100 if left out. | ## dialogOpen [#dialogopen] Function. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#dialogopen). Returns true while the page shows a dialog, an open `` or an element with the `dialog` or `alertdialog` role. Shortcuts stand aside while it's open, so the dialog's own keys and Escape reach it. ```ts shape import { dialogOpen } from '@ifloom/browser' function dialogOpen(): boolean ``` ## ignoredKey [#ignoredkey] Function. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#ignoredkey). Returns true for a key press that shortcuts should leave alone. That is a key typed into a field, a key held with Ctrl, Alt, Meta or Shift, or one another handler has already prevented. ```ts shape import { ignoredKey } from '@ifloom/browser' function ignoredKey(event: KeyboardEvent): boolean ``` ## indexedDbDriver [#indexeddbdriver] Function. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#indexeddbdriver). Returns a save driver that keeps its strings in IndexedDB, which holds far more than `localStorage`. Use it for long games, long backlogs and mods. It opens one database, `ifloom` unless `database` names another, with one store of strings by key, `saves` unless `store` names another. It creates both on first use. Tests pass their own `indexedDB`. ```ts shape import { indexedDbDriver } from '@ifloom/browser' function indexedDbDriver(options?: { database?: string; store?: string; indexedDB?: IndexedDbLike }): SaveDriver ``` Uses: [`IndexedDbLike`](#indexeddblike), [`SaveDriver`](https://ifloom.dev/docs/api/engine#savedriver). ## IndexedDbLike [#indexeddblike] Type. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#indexeddblike). The part of the `indexedDB` API that `indexedDbDriver` uses. The browser's `indexedDB` fits it. ```ts fragment type IndexedDbLike = { open: (name: string, version?: number | undefined) => OpenRequest } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `open` | `(name: string, version?: number \| undefined) => OpenRequest` | | | Opens a database by name at a version, and returns the request that settles with it. | ## KeysOptions [#keysoptions] Type. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#keysoptions). Settings for `startKeys`. Each is optional, and the number keys and a minigame's keys are on if left out. ```ts shape import type { KeysOptions } from '@ifloom/browser' type KeysOptions = { choices?: boolean | ((key: number) => boolean) escape?: () => boolean | void map?: Record minigame?: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `choices` | `boolean \| ((key: number) => boolean)` | yes | | The number keys' handling. By default keys 1 to 9 choose the choices on screen, in `numberedChoices` order, and a disabled one does nothing. `false` turns them off. A function chooses in their place. It gets the key's number and returns true when it handled the key, such as a UI that clicks the button it rendered with that number. | | `escape` | `() => boolean \| void` | yes | | The function Escape calls, such as one that opens the game's menu. Escape does nothing if left out. Return `false` when it did nothing, such as with no menu on screen, and the key goes on to the page untouched. | | `map` | `Record` | yes | | The game's own keys, each mapped by `KeyboardEvent.key` (`'m'`, `'F2'`, `' '`) to the command it sends. They come before the built-in keys, so mapping `'1'` or `'Escape'` replaces that key. | | `minigame` | `boolean` | yes | | True to start `startMinigameKeys` too, so the keyboard sends a minigame's inputs. On unless false. | ## localStorageDriver [#localstoragedriver] Function. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#localstoragedriver). Returns a save driver that keeps its strings in `localStorage`, or in the storage you pass. Every browser has it, but it holds about 5MB per origin. In Chromium every page opened from disk shares one origin, and so one 5MB store. Tests pass a storage of their own. ```ts shape import { localStorageDriver } from '@ifloom/browser' function localStorageDriver(storage?: StorageLike): SaveDriver ``` Uses: [`StorageLike`](#storagelike), [`SaveDriver`](https://ifloom.dev/docs/api/engine#savedriver). ## minigameInput [#minigameinput] Function. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#minigameinput). Returns the id of the minigame input that a key presses, by `KeyboardEvent.key`, or `undefined` for none. It returns the id even when the input does nothing now. It reads the minigame's own `keys` first. Without them, the arrow keys and space press the inputs `up`, `down`, `left`, `right` and `space`, and an input with a one-letter id is pressed by that letter. One-letter keys match either case. ```ts shape import { minigameInput } from '@ifloom/browser' function minigameInput(minigame: MinigameView, key: string): string | undefined ``` Uses: [`MinigameView`](https://ifloom.dev/docs/api/engine#minigameview). ## nextSlot [#nextslot] Function. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#nextslot). Returns the slot for a new save, one more than the highest numbered slot in a `saves.list()` listing, as a string. It returns `'1'` when there's none. It skips slots with other names, such as `'auto'`. A save that can't be read still counts, so a new save never writes over it. ```ts shape import { nextSlot } from '@ifloom/browser' function nextSlot(listing: readonly SaveListing[]): string ``` Uses: [`SaveListing`](https://ifloom.dev/docs/api/engine#savelisting). ## numberedChoices [#numberedchoices] Function. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#numberedchoices). Returns the choices the number keys choose, in order. They're the open scene's choices, else the room's actions, and key 1 is the first. ```ts shape import { numberedChoices } from '@ifloom/browser' function numberedChoices(view: View): RenderedChoice[] ``` Uses: [`View`](https://ifloom.dev/docs/api/engine#view), [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice). ## startClock [#startclock] Function. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#startclock). Starts the clock that runs down the game's timers, and returns a function that stops it. The engine keeps no clock, so start one per runner. While a timer in `view.timers` or the running minigame's timer counts down and the page is visible, the clock sends a `tick` command with the real time since the last one, every 100 ms by default. It drops the time the page spends hidden, so a timer waits for the player. It sends the time up to the moment the page hides, then starts afresh when the page shows again. A timer that the last command started, or a minigame state it entered, counts from that command rather than from the last tick. ```ts shape import { startClock } from '@ifloom/browser' function startClock(runner: Runner, options?: ClockOptions): () => void ``` Uses: [`Runner`](https://ifloom.dev/docs/api/engine#runner), [`ClockOptions`](#clockoptions). ## startKeys [#startkeys] Function. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#startkeys). Starts the game's keyboard shortcuts, and returns a function that stops them. They cover the game's own keys, Escape, the number keys for the choices on screen and a minigame's inputs. They leave alone a key typed into a field, a key held with a modifier and any key while a dialog is open. ```ts shape import { startKeys } from '@ifloom/browser' function startKeys(runner: Runner, options?: KeysOptions): () => void ``` Uses: [`Runner`](https://ifloom.dev/docs/api/engine#runner), [`KeysOptions`](#keysoptions). ## startMinigameKeys [#startminigamekeys] Function. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#startminigamekeys). Starts sending the running minigame's inputs from the keyboard, and returns a function that stops it. It maps keys with `minigameInput` and listens before other shortcuts, so a minigame's keys win. A key that maps to an input never does anything else, such as scrolling the page, even while that input does nothing. ```ts shape import { startMinigameKeys } from '@ifloom/browser' function startMinigameKeys(runner: Runner): () => void ``` Uses: [`Runner`](https://ifloom.dev/docs/api/engine#runner). ## startRevealSkip [#startrevealskip] Function. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#startrevealskip). Starts calling `skip` on each key press, and returns a function that stops it. Run it while a UI reveals a scene in steps, and stop it once the scene shows in full. It listens before other shortcuts and stops the key there, so a number key can't choose a choice the player can't see yet. It leaves alone a key typed into a field and a key held with a modifier. ```ts shape import { startRevealSkip } from '@ifloom/browser' function startRevealSkip(skip: () => void): () => void ``` ## StorageLike [#storagelike] Type. Explained in [Browser helpers](https://ifloom.dev/docs/reference/browser#storagelike). The part of the Web Storage API that `localStorageDriver` uses. `localStorage` and `sessionStorage` both fit it. ```ts shape import type { StorageLike } from '@ifloom/browser' type StorageLike = { getItem: (key: string) => string | null setItem: (key: string, value: string) => void removeItem: (key: string) => void key: (index: number) => string | null readonly length: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `getItem` | `(key: string) => string \| null` | | | Returns the string stored under a key, or `null` when there's none. | | `setItem` | `(key: string, value: string) => void` | | | Stores a string under a key, replacing any already there. | | `removeItem` | `(key: string) => void` | | | Removes the string stored under a key. | | `key` | `(index: number) => string \| null` | | | Returns the key at an index, or `null` past the end. The driver lists keys with it. | | `length` | `number` | | | The number of keys in the storage. | # @ifloom/cli/game (https://ifloom.dev/docs/api/cli-game) Generated from the source of `@ifloom/cli/game` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. - Functions: [`defineGame`](#definegame), [`explorer`](#explorer), [`probe`](#probe-1) - Types: [`BuildOptions`](#buildoptions), [`GameModule`](#gamemodule), [`GameModuleDef`](#gamemoduledef), [`Policy`](#policy), [`Probe`](#probe), [`ProbeStep`](#probestep) ## BuildOptions [#buildoptions] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#gamemoduledef-buildoptions-and-gamemodule). The options a game module's `build` receives. They name the packs to load over the content, such as the locked content a player's codes opened. ```ts shape import type { BuildOptions } from '@ifloom/cli/game' type BuildOptions = { unlocked: Pack[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `unlocked` | [`Pack[]`](https://ifloom.dev/docs/api/engine#pack) | | | The packs to pass to `loadGame` as `{ packs }`. `ifloom check` passes the game's `src/unlocks/` packs, and it's empty otherwise. | ## defineGame [#definegame] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#definegame). Returns the game module for a definition, the default export of `src/game.ts`. It throws when `build` is missing. `ifloom check`, `playtest`, `snapshot`, `words` and `build` read the game module, and the page builds the game from it with `game.build()`. export default defineGame({ build: ({ unlocked }) => loadGame(content, { id: 'my-story', title: 'My Story' }, { packs: unlocked }), }) ```ts shape import { defineGame } from '@ifloom/cli/game' function defineGame(def: GameModuleDef): GameModule ``` Uses: [`GameModuleDef`](https://ifloom.dev/docs/api/cli#gamemoduledef), [`GameModule`](https://ifloom.dev/docs/api/cli#gamemodule). ## explorer [#explorer] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#explorer). Returns a policy that explores the game as a curious player would, rather than following a route through the story. It never chooses a choice or action that carries a warning. In a scene it chooses a choice it hasn't chosen yet. Otherwise, at the calendar's bedtime it goes to bed, walking home if it must. Failing that it talks to someone and does something, each once a turn, leaving an action that ends the turn till last. Then it walks to the nearest location it hasn't visited this turn, waits for a running timer with a `tick`, and at last ends the turn. ```ts shape import { explorer } from '@ifloom/cli/game' function explorer(): Policy ``` Uses: [`Policy`](https://ifloom.dev/docs/api/cli#policy). ## GameModule [#gamemodule] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#gamemoduledef-buildoptions-and-gamemodule). The game module `defineGame` returns, the default export of `src/game.ts`. Its `build` takes its options as optional, so a page calls `game.build()`. ```ts shape import type { GameModule } from '@ifloom/cli/game' type GameModule = { start?: (game: Game) => GameState probes?: (game: Game) => Probe[] policy?: Policy build: (options?: Partial) => { game: Game; problems: Problem[] } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `start` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | yes | | The function that returns the state `ifloom playtest` starts from, and `ifloom snapshot` when there are no probes. `startingState(game)` if left out. | | `probes` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) =>` [`Probe[]`](https://ifloom.dev/docs/api/engine#probe) | yes | | The function that returns the states `ifloom snapshot` renders every scene and location in, each made with `probe`. The start only if left out. | | `policy` | [`Policy`](https://ifloom.dev/docs/api/cli#policy) | yes | | The policy that chooses each command `ifloom playtest` sends. The CLI's `explorer()` if left out. | | `build` | `(options?: Partial<`[`BuildOptions`](https://ifloom.dev/docs/api/cli#buildoptions)`>) => { game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`; problems:` [`Problem[]`](https://ifloom.dev/docs/api/engine#problem) `}` | | | Builds the game with the definition's `build`, and returns the game and the loader's problems. `unlocked` is empty unless given. | ## GameModuleDef [#gamemoduledef] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#gamemoduledef-buildoptions-and-gamemodule). The definition a game passes to `defineGame`. Only `build` is required. ```ts shape import type { GameModuleDef } from '@ifloom/cli/game' type GameModuleDef = { build: (options: BuildOptions) => { game: Game; problems: Problem[] } start?: (game: Game) => GameState probes?: (game: Game) => Probe[] policy?: Policy } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `build` | `(options:` [`BuildOptions`](https://ifloom.dev/docs/api/cli#buildoptions)`) => { game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`; problems:` [`Problem[]`](https://ifloom.dev/docs/api/engine#problem) `}` | | | The function that builds the game. It returns what `loadGame` returns, the `game` and its `problems`. | | `start` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | yes | | The function that returns the state `ifloom playtest` starts from, and `ifloom snapshot` when there are no probes. `startingState(game)` if left out. | | `probes` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) =>` [`Probe[]`](https://ifloom.dev/docs/api/engine#probe) | yes | | The function that returns the states `ifloom snapshot` renders every scene and location in, each made with `probe`. The start only if left out. | | `policy` | [`Policy`](https://ifloom.dev/docs/api/cli#policy) | yes | | The policy that chooses each command `ifloom playtest` sends. The CLI's `explorer()` if left out. | ## Policy [#policy] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#policy). A function that chooses the next command for `playtest` from the view, the state and the game. It returns null to stop the run. ```ts shape import type { Policy } from '@ifloom/cli/game' type Policy = (screen: View, state: GameState, game: Game) => CommandRef | null ``` Uses: [`View`](https://ifloom.dev/docs/api/engine#view), [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref). ## Probe [#probe] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#probe-1). A state the content checker renders every scene against, named for the problems it finds. Make one with `probe`, by playing. ```ts shape import type { Probe } from '@ifloom/cli/game' type Probe = { name: string state: GameState } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | | | The probe's name, which the problems it finds carry, such as `'evening, after the café'`. | | `state` | [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | | | The state to render every scene against. | ## probe [#probe-1] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#probe). Returns a probe made by playing each step in order, from the game's starting state or from `from`. It throws when the game refuses a command, with the reason. `from` is another probe or a state. An effect step is any effect content can write, a plugin's included, so a probe never writes the state directly. A `{ play }` step sends the command with everything that follows a command. const morning = probe('first-morning', game, [{ play: { type: 'choose', id: 'unpack' } }, { play: calendar.sleep() }]) probe('a-week-in', game, [{ turn: { by: 6 } }, { 'calendar/set': { period: 'afternoon' } }], morning) ```ts shape import { probe } from '@ifloom/cli/game' function probe(name: string, game: Game, steps: readonly ProbeStep[], from?: Probe | GameState): Probe ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`ProbeStep`](https://ifloom.dev/docs/api/cli#probestep), [`Probe`](https://ifloom.dev/docs/api/engine#probe), [`GameState`](https://ifloom.dev/docs/api/engine#gamestate). ## ProbeStep [#probestep] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#probestep). One step of a probe, either an effect or `{ play: command }`. The probe applies an effect as content's effects apply, and sends a command as the player would. ```ts shape import type { ProbeStep } from '@ifloom/cli/game' type ProbeStep = Effect | { play: CommandRef } ``` Uses: [`Effect`](https://ifloom.dev/docs/api/engine#effect), [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref). # @ifloom/cli/vite (https://ifloom.dev/docs/api/cli-vite) Generated from the source of `@ifloom/cli/vite` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. - Functions: [`ifloom`](#ifloom) - Types: [`IfloomViteOptions`](#ifloomviteoptions) ## ifloom [#ifloom] Function. Returns the Vite config every IFLoom game builds with, which writes one HTML file with relative paths. It names no UI framework, so a game adds its framework's Vite plugin in `vite.plugins`. The preset's plugins come after the game's. Inside the IFLoom checkout it reads the `@ifloom` packages' source, and it encrypts a game's `src/unlocks/` packs into the page. ```ts fragment function ifloom(options?: IfloomViteOptions): UserConfig ``` Uses: [`IfloomViteOptions`](#ifloomviteoptions). ## IfloomViteOptions [#ifloomviteoptions] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#ifloomviteoptions). Settings for `ifloom()`, the Vite preset. Each is optional. ```ts fragment type IfloomViteOptions = { singleFile?: boolean vite?: UserConfig | undefined } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `singleFile` | `boolean` | yes | | True to put the JS and CSS inside the one HTML file, rather than beside it. True if left out. | | `vite` | `UserConfig \| undefined` | yes | | The game's own Vite config, which the preset builds on. The preset keeps `base` at `'./'` and adds its plugins after the game's `plugins`, where the game's framework plugin goes. | # @ifloom/cli (https://ifloom.dev/docs/api/cli) Generated from the source of `@ifloom/cli` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. - Functions: [`buildFiles`](#buildfiles), [`checkBuild`](#checkbuild), [`checkFiles`](#checkfiles), [`checkGame`](#checkgame), [`defineGame`](#definegame), [`explorer`](#explorer), [`gameFrom`](#gamefrom), [`inlineAssets`](#inlineassets), [`metricsText`](#metricstext), [`newGame`](#newgame), [`playtest`](#playtest-1), [`probe`](#probe-1), [`screenText`](#screentext), [`snapshot`](#snapshot) - Constants: [`TEMPLATES`](#templates), [`THEMES`](#themes) - Types: [`BuildOptions`](#buildoptions), [`GameModule`](#gamemodule), [`GameModuleDef`](#gamemoduledef), [`NewGameOptions`](#newgameoptions), [`Playtest`](#playtest), [`PlaytestOptions`](#playtestoptions), [`Policy`](#policy), [`Probe`](#probe), [`ProbeStep`](#probestep), [`TemplateName`](#templatename), [`ThemeName`](#themename), [`TurnMetrics`](#turnmetrics) ## buildFiles [#buildfiles] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#buildfiles). Returns every file in a built folder with its size in bytes, largest first. `at` names a subfolder to list instead. ```ts shape import { buildFiles } from '@ifloom/cli' function buildFiles(dir: string, at?: string): { file: string; bytes: number }[] ``` ## BuildOptions [#buildoptions] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#gamemoduledef-buildoptions-and-gamemodule). The options a game module's `build` receives. They name the packs to load over the content, such as the locked content a player's codes opened. ```ts shape import type { BuildOptions } from '@ifloom/cli' type BuildOptions = { unlocked: Pack[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `unlocked` | [`Pack[]`](https://ifloom.dev/docs/api/engine#pack) | | | The packs to pass to `loadGame` as `{ packs }`. `ifloom check` passes the game's `src/unlocks/` packs, and it's empty otherwise. | ## checkBuild [#checkbuild] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#checkbuild). Returns a line for each reason a built folder won't open from disk, or an empty list when it will. Its `index.html` must load files only from beside it, with no module script. Given the files the game names (`checkGame(game).files`), it also reports each one that isn't in the folder, or in the page after `--inline-assets`. It doesn't look for `fetch` in the built file, since a bundled library can name it without calling it. The engine's and the UI's contract tests check their source never fetches at runtime instead. ```ts shape import { checkBuild } from '@ifloom/cli' function checkBuild(dir: string, files?: readonly FileRef[]): string[] ``` Uses: [`FileRef`](https://ifloom.dev/docs/api/engine#fileref). ## checkFiles [#checkfiles] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#checkfiles). Returns a line for each file in `files` that isn't in `dir`, as `: no file /`. An empty list means every file is there. The files are the content checker's (`checkGame(game).files`), with their paths as the page requests them, so `dir` is `public/` before a build and `dist/` after one. Paths in `inlined` are inside the page after `--inline-assets`, and count as there. ```ts shape import { checkFiles } from '@ifloom/cli' function checkFiles(files: readonly FileRef[], dir: string, inlined?: ReadonlySet): string[] ``` Uses: [`FileRef`](https://ifloom.dev/docs/api/engine#fileref). ## checkGame [#checkgame] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#checkgame). Returns a line for each problem with a game module's game, the loader's problems first. Given the game's public folder, it adds each sound, picture and video file that isn't in it. ```ts shape import { checkGame } from '@ifloom/cli' function checkGame(module: Record, publicDir?: string): string[] ``` ## defineGame [#definegame] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#definegame). Returns the game module for a definition, the default export of `src/game.ts`. It throws when `build` is missing. `ifloom check`, `playtest`, `snapshot`, `words` and `build` read the game module, and the page builds the game from it with `game.build()`. export default defineGame({ build: ({ unlocked }) => loadGame(content, { id: 'my-story', title: 'My Story' }, { packs: unlocked }), }) ```ts shape import { defineGame } from '@ifloom/cli' function defineGame(def: GameModuleDef): GameModule ``` Uses: [`GameModuleDef`](#gamemoduledef), [`GameModule`](#gamemodule). ## explorer [#explorer] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#explorer). Returns a policy that explores the game as a curious player would, rather than following a route through the story. It never chooses a choice or action that carries a warning. In a scene it chooses a choice it hasn't chosen yet. Otherwise, at the calendar's bedtime it goes to bed, walking home if it must. Failing that it talks to someone and does something, each once a turn, leaving an action that ends the turn till last. Then it walks to the nearest location it hasn't visited this turn, waits for a running timer with a `tick`, and at last ends the turn. ```ts shape import { explorer } from '@ifloom/cli' function explorer(): Policy ``` Uses: [`Policy`](#policy). ## gameFrom [#gamefrom] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#gamefrom). Returns the game a game module builds, with its problems and warnings as sentences and the files its content names. It throws when the module's default export isn't made with `defineGame`. The problems are the loader's and the warnings the content checker's, each worded by `describeProblem`. `unlocked` packs go to the module's `build` as `{ unlocked }`. ```ts shape import { gameFrom } from '@ifloom/cli' function gameFrom(module: Record, unlocked?: Pack[]): { game: Game; problems: string[]; warnings: string[]; files: FileRef[] } ``` Uses: [`Pack`](https://ifloom.dev/docs/api/engine#pack), [`Game`](https://ifloom.dev/docs/api/engine#game), [`FileRef`](https://ifloom.dev/docs/api/engine#fileref). ## GameModule [#gamemodule] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#gamemoduledef-buildoptions-and-gamemodule). The game module `defineGame` returns, the default export of `src/game.ts`. Its `build` takes its options as optional, so a page calls `game.build()`. ```ts shape import type { GameModule } from '@ifloom/cli' type GameModule = { start?: (game: Game) => GameState probes?: (game: Game) => Probe[] policy?: Policy build: (options?: Partial) => { game: Game; problems: Problem[] } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `start` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | yes | | The function that returns the state `ifloom playtest` starts from, and `ifloom snapshot` when there are no probes. `startingState(game)` if left out. | | `probes` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) =>` [`Probe[]`](https://ifloom.dev/docs/api/engine#probe) | yes | | The function that returns the states `ifloom snapshot` renders every scene and location in, each made with `probe`. The start only if left out. | | `policy` | [`Policy`](#policy) | yes | | The policy that chooses each command `ifloom playtest` sends. The CLI's `explorer()` if left out. | | `build` | `(options?: Partial<`[`BuildOptions`](#buildoptions)`>) => { game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`; problems:` [`Problem[]`](https://ifloom.dev/docs/api/engine#problem) `}` | | | Builds the game with the definition's `build`, and returns the game and the loader's problems. `unlocked` is empty unless given. | ## GameModuleDef [#gamemoduledef] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#gamemoduledef-buildoptions-and-gamemodule). The definition a game passes to `defineGame`. Only `build` is required. ```ts shape import type { GameModuleDef } from '@ifloom/cli' type GameModuleDef = { build: (options: BuildOptions) => { game: Game; problems: Problem[] } start?: (game: Game) => GameState probes?: (game: Game) => Probe[] policy?: Policy } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `build` | `(options:` [`BuildOptions`](#buildoptions)`) => { game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`; problems:` [`Problem[]`](https://ifloom.dev/docs/api/engine#problem) `}` | | | The function that builds the game. It returns what `loadGame` returns, the `game` and its `problems`. | | `start` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | yes | | The function that returns the state `ifloom playtest` starts from, and `ifloom snapshot` when there are no probes. `startingState(game)` if left out. | | `probes` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) =>` [`Probe[]`](https://ifloom.dev/docs/api/engine#probe) | yes | | The function that returns the states `ifloom snapshot` renders every scene and location in, each made with `probe`. The start only if left out. | | `policy` | [`Policy`](#policy) | yes | | The policy that chooses each command `ifloom playtest` sends. The CLI's `explorer()` if left out. | ## inlineAssets [#inlineassets] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#inlineassets). Moves every file in a built folder's `art/` into its `index.html` as data URLs, except videos, and returns the counts. It suits a small game, and a large one is better left as a folder. Each file goes in under its path, and the React UI's `assetUrl` looks a path up there first. The engine's `mediaType` says which files are videos, and those stay in `art/`, as sound in `audio/` does. The result gives the number of files moved in, the page's size in bytes and the number of videos left beside it. `folder` names another folder than `art`. ```ts shape import { inlineAssets } from '@ifloom/cli' function inlineAssets(dir: string, folder?: string): { files: number; bytes: number; videos: number } ``` ## metricsText [#metricstext] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#metricstext). Returns a playtest's turn numbers as a tab-separated table, with a header row and one row a turn. ```ts shape import { metricsText } from '@ifloom/cli' function metricsText(turns: TurnMetrics[]): string ``` Uses: [`TurnMetrics`](#turnmetrics). ## newGame [#newgame] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#newgame). Makes a new game from a template, and returns its folder, the files written there and the theme it chose. It installs nothing. It throws when the name can't be a package name, the template or theme doesn't exist, or the folder isn't empty. ```ts shape import { newGame } from '@ifloom/cli' function newGame(options: NewGameOptions): { dir: string; files: string[]; theme: ThemeName | null } ``` Uses: [`NewGameOptions`](#newgameoptions), [`ThemeName`](#themename). ## NewGameOptions [#newgameoptions] Type. Settings for `newGame`. Only `name` is required. ```ts shape import type { NewGameOptions } from '@ifloom/cli' type NewGameOptions = { name: string template?: TemplateName into?: string theme?: ThemeName | 'none' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | | | The game's package name, such as `my-story`, which is also its folder's name. For the `plugin` template it's the plugin's package name, such as `ifloom-plugin-weather`. The plugin's id is the name without `ifloom-plugin-` or `plugin-` in front, so `weather`. | | `template` | [`TemplateName`](#templatename) | yes | | The template the game starts from. `react` if left out. | | `into` | `string` | yes | | The folder to make the game in. `games/` in the IFLoom checkout if left out, else `` in the current folder. | | `theme` | [`ThemeName`](#themename) `\| 'none'` | yes | | The React UI theme preset the game starts with. A `react` or `next` game gets one at random if left out, and a copied example keeps its own. `'none'` leaves the preset out, for the React UI's plain look. The `vanilla`, `vue` and `svelte` templates have no React UI and ignore it. | ## Playtest [#playtest] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#playtest-and-playtest). The result of a `playtest` run, with its transcript, each turn's numbers and the refusals. ```ts shape import type { Playtest } from '@ifloom/cli' type Playtest = { transcript: string turns: TurnMetrics[] refusals: { turn: number; command: Command; reason: string }[] state: GameState } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `transcript` | `string` | | | The run's transcript as plain text, with each screen and the command sent from it. | | `turns` | [`TurnMetrics[]`](#turnmetrics) | | | Each turn's numbers, in order. | | `refusals` | `{ turn: number; command:` [`Command`](https://ifloom.dev/docs/api/engine#command)`; reason: string }[]` | | | The policy's commands that the game refused, each with its turn and reason. Each one is a bug in the policy or the game. | | `state` | [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | | | The state the run ended on. | ## playtest [#playtest-1] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#playtest-and-playtest). Returns the result of playing from `start` with `policy`, the explorer by default. It stops when `turns` or `steps` run out, the policy returns null, the game restarts or a screen keeps repeating. The transcript writes each notice once, under the screen it first shows on. ```ts shape import { playtest } from '@ifloom/cli' function playtest(game: Game, start: GameState, policy?: Policy, options?: PlaytestOptions): Playtest ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Policy`](#policy), [`PlaytestOptions`](#playtestoptions), [`Playtest`](#playtest). ## PlaytestOptions [#playtestoptions] Type. Settings for `playtest`. Each is optional. ```ts shape import type { PlaytestOptions } from '@ifloom/cli' type PlaytestOptions = { turns?: number steps?: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `turns` | `number` | yes | | The number of turns the run plays before it stops. 7 if left out. | | `steps` | `number` | yes | | The most commands the run sends, whatever the turn, so a policy that goes round in circles still stops. 2000 if left out. | ## Policy [#policy] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#policy). A function that chooses the next command for `playtest` from the view, the state and the game. It returns null to stop the run. ```ts shape import type { Policy } from '@ifloom/cli' type Policy = (screen: View, state: GameState, game: Game) => CommandRef | null ``` Uses: [`View`](https://ifloom.dev/docs/api/engine#view), [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref). ## Probe [#probe] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#probe-1). A state the content checker renders every scene against, named for the problems it finds. Make one with `probe`, by playing. ```ts shape import type { Probe } from '@ifloom/cli' type Probe = { name: string state: GameState } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | | | The probe's name, which the problems it finds carry, such as `'evening, after the café'`. | | `state` | [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | | | The state to render every scene against. | ## probe [#probe-1] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#probe). Returns a probe made by playing each step in order, from the game's starting state or from `from`. It throws when the game refuses a command, with the reason. `from` is another probe or a state. An effect step is any effect content can write, a plugin's included, so a probe never writes the state directly. A `{ play }` step sends the command with everything that follows a command. const morning = probe('first-morning', game, [{ play: { type: 'choose', id: 'unpack' } }, { play: calendar.sleep() }]) probe('a-week-in', game, [{ turn: { by: 6 } }, { 'calendar/set': { period: 'afternoon' } }], morning) ```ts shape import { probe } from '@ifloom/cli' function probe(name: string, game: Game, steps: readonly ProbeStep[], from?: Probe | GameState): Probe ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`ProbeStep`](#probestep), [`Probe`](https://ifloom.dev/docs/api/engine#probe), [`GameState`](https://ifloom.dev/docs/api/engine#gamestate). ## ProbeStep [#probestep] Type. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#probestep). One step of a probe, either an effect or `{ play: command }`. The probe applies an effect as content's effects apply, and sends a command as the player would. ```ts shape import type { ProbeStep } from '@ifloom/cli' type ProbeStep = Effect | { play: CommandRef } ``` Uses: [`Effect`](https://ifloom.dev/docs/api/engine#effect), [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref). ## screenText [#screentext] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#screentext). Returns a view as plain text, as `ifloom playtest` writes it. The text has the turn, the time, the body, each choice and action with its price or reason, and the inputs. ```ts shape import { screenText } from '@ifloom/cli' function screenText(screen: View): string ``` Uses: [`View`](https://ifloom.dev/docs/api/engine#view). ## snapshot [#snapshot] Function. Explained in [The CLI](https://ifloom.dev/docs/reference/cli#snapshot). Returns every scene and every location rendered as text in every probe state. It's what `ifloom snapshot` writes. The text comes from the engine's `view`, so it reads as the screen does. Each scene shows its body and its choices, and a choice that a lock or a plugin's guard refuses shows as disabled, with its reason. Locations come from the places plugin's `places/all` query, and a game without it has none. Compared with the last run's file, the diff names the scene and the probe that read differently. ```ts shape import { snapshot } from '@ifloom/cli' function snapshot(game: Game, probes: Probe[]): string ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`Probe`](https://ifloom.dev/docs/api/engine#probe). ## TemplateName [#templatename] Type. The name of a template in `TEMPLATES`. ```ts shape import type { TemplateName } from '@ifloom/cli' type TemplateName = (typeof TEMPLATES)[number] ``` ## TEMPLATES [#templates] Const. The templates `ifloom new` can start a game from. `novel`, `cafe` and `town` copy the examples, and `plugin` makes a plugin package. ```ts shape import { TEMPLATES } from '@ifloom/cli' const TEMPLATES: readonly ['react', 'vanilla', 'vue', 'svelte', 'next', 'novel', 'cafe', 'town', 'plugin'] ``` ## ThemeName [#themename] Type. The name of a theme preset in `THEMES`. ```ts shape import type { ThemeName } from '@ifloom/cli' type ThemeName = (typeof THEMES)[number] ``` ## THEMES [#themes] Const. The names of the React UI's theme presets, each a stylesheet at `@ifloom/react/themes/.css`. ```ts shape import { THEMES } from '@ifloom/cli' const THEMES: readonly ['paper', 'terminal', 'studio', 'storybook'] ``` ## TurnMetrics [#turnmetrics] Type. One turn's numbers in a playtest, taken as the turn ended. They hold the player's stats and the number of entities of each listed kind. ```ts shape import type { TurnMetrics } from '@ifloom/cli' type TurnMetrics = { turn: number stats: Record scenes: string[] refused: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `turn` | `number` | | | The turn's number, counting from 1. | | `stats` | `Record` | | | The player's stats and, by kind id, the number of entities of each listed kind, as the turn ended. | | `scenes` | `string[]` | | | The ids of the scenes the turn opened, in order. | | `refused` | `number` | | | The number of the policy's commands the game refused during the turn. | # @ifloom/engine/plugin (https://ifloom.dev/docs/api/engine-plugin) Generated from the source of `@ifloom/engine/plugin` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. - Functions: [`actionReferences`](#actionreferences), [`anyOf`](#anyof), [`bindCurrent`](#bindcurrent), [`defineCalls`](#definecalls), [`defineData`](#definedata), [`definePlugin`](#defineplugin), [`defineRules`](#definerules), [`defineTraitKind`](#definetraitkind), [`entityUi`](#entityui), [`everyEntity`](#everyentity), [`hasEntity`](#hasentity), [`list`](#list), [`lockedOut`](#lockedout), [`lockOn`](#lockon), [`panelOf`](#panelof), [`parseBeats`](#parsebeats), [`pictureView`](#pictureview), [`priceView`](#priceview), [`renderAction`](#renderaction), [`setTraitState`](#settraitstate), [`speakerOf`](#speakerof), [`styledBeats`](#styledbeats), [`traitState`](#traitstate) - Constants: [`arg`](#arg-1) - Types: [`AnyCalls`](#anycalls), [`Arg`](#arg), [`ArgIn`](#argin), [`ArgOut`](#argout), [`ArgShape`](#argshape), [`ArgsIn`](#argsin), [`ArgsOut`](#argsout), [`Asked`](#asked), [`CallArgs`](#callargs), [`CallForm`](#callform), [`CallIn`](#callin), [`CallShapes`](#callshapes), [`CallTable`](#calltable), [`CallWriter`](#callwriter), [`CheckTools`](#checktools), [`CommandsOf`](#commandsof), [`CommandStep`](#commandstep), [`ConditionsOf`](#conditionsof), [`ContentReferences`](#contentreferences), [`ContentStep`](#contentstep), [`ContentTools`](#contenttools), [`DataList`](#datalist), [`DefinedPlugin`](#definedplugin), [`EffectsOf`](#effectsof), [`ListSpec`](#listspec), [`Lock`](#lock), [`LockTarget`](#locktarget), [`Macro`](#macro), [`PackContext`](#packcontext), [`Plugin`](#plugin), [`PluginArgs`](#pluginargs), [`PluginCalls`](#plugincalls), [`PluginCommand`](#plugincommand), [`PluginContext`](#plugincontext), [`PluginData`](#plugindata), [`PluginDef`](#plugindef), [`PluginEntry`](#pluginentry), [`PluginProblem`](#pluginproblem), [`PluginReferences`](#pluginreferences), [`PluginSlice`](#pluginslice), [`QueryAnswer`](#queryanswer), [`QueryArgs`](#queryargs), [`RawCall`](#rawcall), [`RawCommand`](#rawcommand), [`Receiver`](#receiver), [`Reference`](#reference), [`Refusal`](#refusal), [`RoomScene`](#roomscene), [`RulesDef`](#rulesdef), [`SpeakerFinder`](#speakerfinder), [`StatModifier`](#statmodifier), [`TraitDef`](#traitdef), [`TraitEntityDef`](#traitentitydef), [`TraitKind`](#traitkind), [`TraitKindSpec`](#traitkindspec), [`TraitTools`](#traittools), [`TurnContext`](#turncontext), [`WrittenAs`](#writtenas) ## actionReferences [#actionreferences] Function. Explained in [Actions](https://ifloom.dev/docs/reference/actions#actionreferences). Returns the references an action makes, for the content checker. They cover its words, conditions, effects, command and hints. A plugin whose content holds actions (a location's, an app's) passes these to its `references`. ```ts shape import { actionReferences } from '@ifloom/engine/plugin' function actionReferences(action: ActionDef): Reference[] ``` Uses: [`ActionDef`](https://ifloom.dev/docs/api/engine#actiondef), [`Reference`](#reference). ## AnyCalls [#anycalls] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#plugincalls-and-anycalls). Any plugin's `PluginCalls`, with each call's full name and arguments, by table. ```ts shape import type { AnyCalls } from '@ifloom/engine/plugin' type AnyCalls = { readonly id: string readonly conditions: Readonly> readonly effects: Readonly> readonly commands: Readonly> } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The plugin's id. | | `conditions` | `Readonly>` | | | The plugin's conditions, by name. | | `effects` | `Readonly>` | | | The plugin's effects, by name. | | `commands` | `Readonly>` | | | The plugin's commands, by name. | ## anyOf [#anyof] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#anyof). Returns a stand-in reference for any entity of a kind, for checking content written with `'$'` before it runs. ```ts shape import { anyOf } from '@ifloom/engine/plugin' function anyOf(kind: string): EntityRef ``` Uses: [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref). ## Arg [#arg] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#arg). One argument of a plugin's call, made with `arg`. `In` is the type content writes, and `Out` the type the implementation gets, read from whatever content wrote. It also says whether content may leave it out, how the checker describes the right shape, and what a value names. ```ts shape import type { Arg } from '@ifloom/engine/plugin' type Arg = { readonly kind: string readonly isOptional: Optional readonly words?: WordPart read: (value: unknown) => Out fits: (value: unknown) => boolean refs: (value: Out, game: Game) => readonly Reference[] optional: { (): Arg; (fallback: F): Arg; } naming: (refs: (value: Exclude, game: Game) => readonly Reference[]) => Arg rule: (problem: (value: Exclude) => string | undefined) => Arg readonly _in?: In } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `kind` | `string` | | | The shape a value must have, in the checker's words, such as `'text'` or `'a number'`. | | `isOptional` | `Optional` | | | True when content may leave the argument out. | | `words` | [`WordPart`](https://ifloom.dev/docs/api/engine#wordpart) | yes | | The argument's word shape, set when its value is words a player reads that a translation can replace. | | `read` | `(value: unknown) => Out` | | | Returns the value the implementation gets for content's value, whatever content wrote. | | `fits` | `(value: unknown) => boolean` | | | Returns true when content's value has the right shape. The checker asks it only of a value content wrote. | | `refs` | `(value: Out, game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => readonly` [`Reference[]`](#reference) | | | Returns the references a value makes for the checker, such as a location, an entry or a `{ problem }`. | | `optional` | `{ ():` [`Arg`](#arg)`; (fallback: F):` [`Arg`](#arg)`; }` | | | Returns the same argument, which content may leave out. The implementation then gets `undefined`, or `fallback` when one is given. | | `naming` | `(refs: (value: Exclude, game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => readonly` [`Reference[]`](#reference)`) =>` [`Arg`](#arg)` [...]`, or the registries built from the calls refer to themselves. | | `rule` | `(problem: (value: Exclude) => string \| undefined) =>` [`Arg`](#arg)` (n >= 1 ? undefined : 'count must be 1 or more'))`. | | `_in` | `In` | yes | | The type content writes, for type inference only. It is never set. | ## arg [#arg-1] Const. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#arg-1). The makers of the `Arg`s a call can take, for `defineCalls`. Each reads content's value into the value the implementation gets, whatever content wrote, and the checker reports a value of the wrong shape. A missing text reads as `''`, and a single value as a list of one. `.optional()` lets content leave an argument out, `.optional(1)` with the value the implementation then gets. `.naming(fn)` adds the references a value makes, as in `arg.string().naming((id) => [{ scene: id }])`. ```ts shape import { arg } from '@ifloom/engine/plugin' const arg: { string: () => Arg words: () => Arg number: () => Arg boolean: () => Arg strings: () => Arg numbers: () => Arg entity: (trait?: string | undefined) => Arg<`${string}:${string}`, `${string}:${string}`, false> someone: () => Arg kv: () => Arg amount: () => Arg range: () => Arg entry: (list: DataList) => Arg entries: (list: DataList) => Arg bounds: { gte: Arg; gt: Arg; lte: Arg; lt: Arg; } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `string` | `() =>` [`Arg`](#arg)`` | | | Returns a text argument, such as `'cafe'`. It reads as `''` when missing. | | `words` | `() =>` [`Arg`](#arg)`` | | | Returns a text argument of words a player reads, such as a post's text, which a translation can replace. | | `number` | `() =>` [`Arg`](#arg)`` | | | Returns a number argument, such as `2`. It reads as `0` when missing or not a number. | | `boolean` | `() =>` [`Arg`](#arg)`` | | | Returns a true or false argument. It reads as false unless content wrote `true`. | | `strings` | `() =>` [`Arg`](#arg)`` | | | Returns an argument of one text or a list, `'cafe'` or `['cafe', 'park']`, which the implementation gets as a list. | | `numbers` | `() =>` [`Arg`](#arg)`` | | | Returns an argument of one number or a list, which the implementation gets as a list. | | `entity` | `(trait?: string \| undefined) =>` [`Arg`](#arg)`<'${string}:${string}', '${string}:${string}', false>` | | | Returns an entity reference argument, such as `'food:bun'`. The checker must find the entity, carrying `trait` when one is given. | | `someone` | `() =>` [`Arg`](#arg)`<`[`Someone`](https://ifloom.dev/docs/api/engine#someone)`,` [`Someone`](https://ifloom.dev/docs/api/engine#someone)`, false>` | | | Returns an argument naming someone, `'player'`, `'you'` or a unique entity. The checker must find them. | | `kv` | `() =>` [`Arg`](#arg)`<`[`KvValue`](https://ifloom.dev/docs/api/engine#kvvalue)`,` [`KvValue`](https://ifloom.dev/docs/api/engine#kvvalue)`, false>` | | | Returns a kv value argument, true or false, a number or text. | | `amount` | `() =>` [`Arg`](#arg)`<`[`Amount`](https://ifloom.dev/docs/api/engine#amount)`,` [`Amount`](https://ifloom.dev/docs/api/engine#amount)`, false>` | | | Returns an `Amount` argument, worked out when the implementation reads it with `amountOf`. The checker resolves the references it makes. | | `range` | `() =>` [`Arg`](#arg)`<`[`Range`](https://ifloom.dev/docs/api/engine#range)`,` [`Range`](https://ifloom.dev/docs/api/engine#range)`, false>` | | | Returns a range argument, such as `stacks: { gte: 2 }`. Its bounds are amounts, and the checker resolves the references they make. | | `entry` | `(list:` [`DataList`](#datalist)`) =>` [`Arg`](#arg)`` | | | Returns an argument naming an entry of one of the plugin's data lists by id, as in `arg.entry(DATA.jobs)`. The checker reports an id the list doesn't have. | | `entries` | `(list:` [`DataList`](#datalist)`) =>` [`Arg`](#arg)`` | | | Returns an argument naming one entry of a data list or several, which the implementation gets as a list. The checker reports each as `entry` does. | | `bounds` | `{ gte:` [`Arg`](#arg)`<`[`Amount`](https://ifloom.dev/docs/api/engine#amount)`,` [`Amount`](https://ifloom.dev/docs/api/engine#amount) `\| undefined, true>; gt:` [`Arg`](#arg)`<`[`Amount`](https://ifloom.dev/docs/api/engine#amount)`,` [`Amount`](https://ifloom.dev/docs/api/engine#amount) `\| undefined, true>;…` | | | The optional `gte`, `gt`, `lte` and `lt` arguments of a range, as the call's own arguments (`{ job: 'cafe', gte: 3 }`). Spread them into a shape, as in `{ job: arg.entry(DATA.jobs), ...arg.bounds }`. The core checks a call's bounds itself. | ## ArgIn [#argin] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#argin-argout-argsin-and-argsout). The type content writes for an `Arg`. ```ts shape import type { ArgIn } from '@ifloom/engine/plugin' type ArgIn = A extends Arg ? In : never ``` Uses: [`Arg`](#arg). ## ArgOut [#argout] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#argin-argout-argsin-and-argsout). The type the implementation gets for an `Arg`. ```ts shape import type { ArgOut } from '@ifloom/engine/plugin' type ArgOut = A extends Arg ? Out : never ``` Uses: [`Arg`](#arg). ## ArgShape [#argshape] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#callshapes-and-argshape). The arguments one call takes, by name. It is `{}` for a call with none, which content writes as `true`. ```ts shape import type { ArgShape } from '@ifloom/engine/plugin' type ArgShape = { [key: string]: Arg } ``` ## ArgsIn [#argsin] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#argin-argout-argsin-and-argsout). The arguments content writes for a call of an `ArgShape`, as an object. ```ts fragment type ArgsIn = { [K in keyof ({ [K in RequiredKeys]: ArgIn; } & { [K in OptionalKeys]?: ArgIn; })]: ({ [K in RequiredKeys]: ArgIn; } & { [K in OptionalKeys]?: ArgIn; })[K]; } ``` Uses: [`ArgIn`](#argin). ## ArgsOut [#argsout] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#argin-argout-argsin-and-argsout). The arguments the implementation of a call of an `ArgShape` gets, every one read. ```ts shape import type { ArgsOut } from '@ifloom/engine/plugin' type ArgsOut = { [key: string]: { [K in keyof S]: ArgOut; }[string] } ``` ## Asked [#asked] Type. Explained in [Plugin API](https://ifloom.dev/docs/reference/plugin-api#asked-and-refusal). The question a plugin's `guard` gets, a command with the effects it would apply. ```ts shape import type { Asked } from '@ifloom/engine/plugin' type Asked = { command: Command effects: readonly Effect[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `command` | [`Command`](https://ifloom.dev/docs/api/engine#command) | | | The command the guard is asked about. | | `effects` | `readonly` [`Effect[]`](https://ifloom.dev/docs/api/engine#effect) | | | The effects the command would apply. | ## bindCurrent [#bindcurrent] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#bindcurrent). Returns a condition or effects with `ref` in place of each `'$'`. A nested `each`'s effects and a nested `count`'s `where` keep their own `'$'`. It replaces `'$'` in every `of`, `entity` and `like`, in a `remove`, `you`, `receive`, `release` or `owned`'s target, in a `receive`'s `to` and a `release`'s `from`, and anywhere in a call's arguments or a `create`'s `with` (`{ 'cast/met': { character: '$' } }`). ```ts shape import { bindCurrent } from '@ifloom/engine/plugin' function bindCurrent(value: T, ref: EntityRef): T ``` Uses: [`Condition`](https://ifloom.dev/docs/api/engine#condition), [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref), [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref). ## CallArgs [#callargs] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#callargs). The arguments the implementation of each call in a table gets, by name. ```ts fragment type CallArgs = { [K in keyof ShapesOf]: ShapesOf[K] extends ArgShape ? { [K in keyof { [K in keyof ShapesOf[K]]: ArgOut[K][K]>; }]: { [K in keyof ShapesOf[K]]: ArgOut[K][K]>; }[K]; } : never; } ``` Uses: [`ArgShape`](#argshape), [`ArgOut`](#argout). ## CallForm [#callform] Type. Explained in [Plugin migrations](https://ifloom.dev/docs/reference/plugin-migrations#callform). The form a plugin call is written in, `short`, `long` or `command`. See `ContentTools.calls`. ```ts shape import type { CallForm } from '@ifloom/engine/plugin' type CallForm = 'short' | 'long' | 'command' ``` ## CallIn [#callin] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#callin). A call in the short form, type-checked against registry `R` when its name is declared there and loose otherwise. ```ts shape import type { CallIn } from '@ifloom/engine/plugin' type CallIn = | { [K in keyof R & `${string}/${string}`]: { [P in K]: R[K]; }; }[keyof R & `${string}/${string}`] | PluginCall & { [K in (keyof R & `${string}/${string}`) | 'achievements/earned' | 'calendar/period' | 'calendar/weekday' | 'calendar/weekend' | 'calendar/day' | 'calendar/curfew' | 'cast/at' | 'cast/here' | 'cast/met' | 'devices/open' | 'feed/appeared' | 'feed/posted' | 'feed/likes' | 'jobs/hired' | 'jobs/fired' | 'jobs/worked' | 'jobs/shifts' | 'messages/since' | 'messages/read' | 'messages/arrived' | 'messages/replied' | 'places/within' | 'places/at' | 'places/away' | 'quests/active' | 'quests/done' | 'quests/reached' | 'shop/open' | 'shop/outside' | 'shop/inStock' | 'statuses/active' | 'unlocks/has' | 'unlocks/cheated' | 'wardrobe/wearing' | 'achievements/grant' | 'calendar/pass' | 'calendar/set' | 'feed/post' | 'feed/react' | 'generators/generate' | 'inventory/set' | 'inventory/move' | 'jobs/hire' | 'jobs/fire' | 'messages/draw' | 'messages/due' | 'places/move' | 'places/put' | 'quests/start' | 'statuses/apply' | 'statuses/remove' | 'wardrobe/remove' | 'wardrobe/add' | 'wardrobe/store' | 'wardrobe/takeOut' | 'calendar/sleep' | 'cast/call' | 'cast/talk' | 'debug/kv' | 'debug/turn' | 'debug/stat' | 'debug/scene' | 'debug/go' | 'debug/held' | 'debug/time' | 'devices/home' | 'devices/close' | 'feed/seen' | 'inventory/use' | 'inventory/drop' | 'inventory/give' | 'jobs/apply' | 'jobs/work' | 'jobs/quit' | 'messages/reply' | 'places/go' | 'places/pickUp' | 'quests/seen' | 'quests/track' | 'shop/buy' | 'shop/sell' | 'unlocks/cheat' | 'unlocks/record' | 'wardrobe/wear' | 'wardrobe/takeOff']?: undefined; } ``` Uses: [`PluginCall`](https://ifloom.dev/docs/api/engine#plugincall). ## CallShapes [#callshapes] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#callshapes-and-argshape). The arguments a plugin's calls take, by table and name, as `defineCalls` is given them. ```ts shape import type { CallShapes } from '@ifloom/engine/plugin' type CallShapes = { conditions?: Readonly> effects?: Readonly> commands?: Readonly> } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `conditions` | `Readonly>` | yes | | The arguments of each of the plugin's conditions, by name. | | `effects` | `Readonly>` | yes | | The arguments of each of the plugin's effects, by name. | | `commands` | `Readonly>` | yes | | The arguments of each of the plugin's commands, by name. | ## CallTable [#calltable] Type. Explained in [A plugin's content checks](https://ifloom.dev/docs/reference/plugin-checks#pluginreferences-calltable-and-contentreferences). The name of a plugin's table of calls, `conditions`, `effects` or `commands`. ```ts shape import type { CallTable } from '@ifloom/engine/plugin' type CallTable = 'conditions' | 'effects' | 'commands' ``` ## CallWriter [#callwriter] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#callwriter). A function that writes one call in the short form from its arguments, such as `{ 'places/at': { location } }`. ```ts fragment type CallWriter = ([RequiredKeys] extends [never] ? (args?: { [K in keyof ({ [K in RequiredKeys]: ArgIn; } & { [K in OptionalKeys]?: ArgIn; })]: ({ [K in RequiredKeys]: ArgIn; } & { [K in OptionalKeys]?: ArgIn; })[K]; } | undefined) => { [N in Name]: WrittenAs; } : (args: { [K in keyof ({ [K in RequiredKeys]: ArgIn; } & { [K in OptionalKeys]?: ArgIn; })]: ({ [K in RequiredKeys]: ArgIn; } & { [K in OptionalKeys]?: ArgIn; })[K]; }) => { [N in Name]: WrittenAs; }) & { readonly call: Name; readonly args: S; read(args: unknown): { [K in keyof { [K in keyof S]: ArgOut; }]: { [K in keyof S]: ArgOut; }[K]; }; } ``` Uses: [`ArgIn`](#argin), [`WrittenAs`](#writtenas), [`ArgOut`](#argout). ## CheckTools [#checktools] Type. Explained in [A plugin's content checks](https://ifloom.dev/docs/reference/plugin-checks#checktools). The tools the content checker gives a plugin's `check`. ```ts shape import type { CheckTools } from '@ifloom/engine/plugin' type CheckTools = { problems: (refs: readonly Reference[]) => string[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `problems` | `(refs: readonly` [`Reference[]`](#reference)`) => string[]` | | | Returns the checker's words for each reference in a list that names something the game doesn't have. | ## CommandsOf [#commandsof] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#conditionsof-effectsof-and-commandsof). The arguments a plugin's commands take, by full name, for its `CommandRegistry`. Use it as `ConditionsOf` is used. ```ts fragment type CommandsOf = C extends PluginCalls ? { [K in keyof Table & string as `${Id}/${K}`]: Table[K] extends ArgShape ? WrittenAs[K]> : never; } : never ``` Uses: [`PluginCalls`](#plugincalls), [`CallShapes`](#callshapes), [`ArgShape`](#argshape), [`WrittenAs`](#writtenas). ## CommandStep [#commandstep] Type. Explained in [Plugin migrations](https://ifloom.dev/docs/reference/plugin-migrations#commandstep). A step of a plugin's `commandMigrations`, which returns a log's command reshaped from one command version to the next. It gets every command, so it returns the ones that aren't its own unchanged. ```ts shape import type { CommandStep } from '@ifloom/engine/plugin' type CommandStep = (command: RawCommand) => RawCommand ``` Uses: [`RawCommand`](#rawcommand). ## ConditionsOf [#conditionsof] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#conditionsof-effectsof-and-commandsof). The arguments a plugin's conditions take, by full name, for its `ConditionRegistry`. Extend the registry from it. ```ts fragment declare module '@ifloom/engine' { interface ConditionRegistry extends ConditionsOf {} } ``` ```ts fragment type ConditionsOf = C extends PluginCalls ? { [K in keyof Table & string as `${Id}/${K}`]: Table[K] extends ArgShape ? WrittenAs[K]> : never; } : never ``` Uses: [`PluginCalls`](#plugincalls), [`CallShapes`](#callshapes), [`ArgShape`](#argshape), [`WrittenAs`](#writtenas). ## ContentReferences [#contentreferences] Type. Explained in [A plugin's content checks](https://ifloom.dev/docs/reference/plugin-checks#pluginreferences-calltable-and-contentreferences). The references one entry of a plugin's content makes. ```ts shape import type { ContentReferences } from '@ifloom/engine/plugin' type ContentReferences = { list: string id: string refs: readonly Reference[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `list` | `string` | | | The name of the plugin's list the entry is in. | | `id` | `string` | | | The entry's id. | | `refs` | `readonly` [`Reference[]`](#reference) | | | The references the entry makes. | ## ContentStep [#contentstep] Type. Explained in [Plugin migrations](https://ifloom.dev/docs/reference/plugin-migrations#contentstep). A step of a plugin's `contentMigrations`, which returns the whole pack reshaped from one content version to the next. It returns a new pack and never changes the one it was given. A step changes only the plugin's own `data`, calls, strings and traits as a rule. ```ts shape import type { ContentStep } from '@ifloom/engine/plugin' type ContentStep = (pack: RawPack, tools: ContentTools) => RawPack ``` Uses: [`RawPack`](https://ifloom.dev/docs/api/engine#rawpack), [`ContentTools`](#contenttools). ## ContentTools [#contenttools] Type. Explained in [Plugin migrations](https://ifloom.dev/docs/reference/plugin-migrations#contenttools). The tools a plugin's content step gets beside the pack, which rewrite a pack without walking it by hand. Each returns a new pack. `objects` and `calls` leave words and code (`prose`, `strings`, `variants`, `custom`) unchanged, and `words` rewrites only those words. ```ts shape import type { ContentTools } from '@ifloom/engine/plugin' type ContentTools = { objects: (pack: RawPack, rewrite: (value: Record) => Record) => RawPack calls: (pack: RawPack, rewrite: (call: RawCall) => { name: string; with: unknown }) => RawPack words: (pack: RawPack, rewrite: (text: string, key: string) => string) => RawPack wordKeys: (pack: RawPack, rename: (key: string) => string) => RawPack entries: (pack: RawPack, list: string, rewrite: (entry: Record) => Record) => RawPack prose: (key: string) => string | undefined } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `objects` | `(pack:` [`RawPack`](https://ifloom.dev/docs/api/engine#rawpack)`, rewrite: (value: Record) => Record) =>…` | | | Returns the pack with every object in its content rewritten by `rewrite`, from the innermost out. | | `calls` | `(pack:` [`RawPack`](https://ifloom.dev/docs/api/engine#rawpack)`, rewrite: (call:` [`RawCall`](#rawcall)`) => { name: string; with: unknown }) =>` [`RawPack`](https://ifloom.dev/docs/api/engine#rawpack) | | | Returns the pack with every call to a condition, effect or command by name rewritten by `rewrite`. A call returned with the same name and arguments stays as it was. The forms are `short` (`{ 'places/at': { location } }`, any key with a `/`, so check the name), `long` (`{ custom: 'places/at', with }` or `{ kind: 'custom', name, with }`) and `command` (`{ type: 'custom', name, with }`). A value (`{ value, with }`) is not a call, so reach it with `objects`. | | `words` | `(pack:` [`RawPack`](https://ifloom.dev/docs/api/engine#rawpack)`, rewrite: (text: string, key: string) => string) =>` [`RawPack`](https://ifloom.dev/docs/api/engine#rawpack) | | | Returns the pack with every line of its `prose` and `strings` rewritten by `rewrite`, which gets each line's key. | | `wordKeys` | `(pack:` [`RawPack`](https://ifloom.dev/docs/api/engine#rawpack)`, rename: (key: string) => string) =>` [`RawPack`](https://ifloom.dev/docs/api/engine#rawpack) | | | Returns the pack with every key of its words table (`quests/quests.settle.title`) renamed by `rename`, keeping the words. A step that renames a field uses it. | | `entries` | `(pack:` [`RawPack`](https://ifloom.dev/docs/api/engine#rawpack)`, list: string, rewrite: (entry: Record) => Record/` (`'quests/quests'` is `data.quests.quests`), and a pack without it comes back unchanged. | | `prose` | `(key: string) => string \| undefined` | | | Returns a prose key's line, the pack's own or else the game's under it, or undefined when neither has it. A step that turns a prose key into words in place uses it. | ## DataList [#datalist] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#datalist). One of a plugin's data lists as `defineData` declares it, kept at `data..`, with its noun, its words and its lookups. ```ts shape import type { DataList } from '@ifloom/engine/plugin' type DataList = { readonly plugin: string readonly list: string readonly noun: string readonly words?: WordShape all: (game: Game) => T[] get: (game: Game, id: unknown) => T | undefined ref: (id: string) => Reference content: (game: Game, refs: (entry: T) => readonly Reference[]) => ContentReferences[] problem: (id: string, what: string) => PluginProblem } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `plugin` | `string` | | | The id of the plugin whose data the list is. | | `list` | `string` | | | The list's name in the plugin's data, such as `'jobs'` for `data.jobs.jobs`. | | `noun` | `string` | | | The noun a problem calls one entry by. | | `words` | [`WordShape`](https://ifloom.dev/docs/api/engine#wordshape) | yes | | The fields of an entry that are words a player reads. | | `all` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => T[]` | | | Returns the game's entries in order. An entry that isn't an object with an id is left out. | | `get` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`, id: unknown) => T \| undefined` | | | Returns one entry by id, or undefined when the game has none. The id may be anything content wrote. | | `ref` | `(id: string) =>` [`Reference`](#reference) | | | Returns the reference to one entry by id, which the checker reports as `unknown job "cafe"` when the game has none. | | `content` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`, refs: (entry: T) => readonly` [`Reference[]`](#reference)`) =>` [`ContentReferences[]`](#contentreferences) | | | Returns the references each entry makes, for `references.content`, each reported at ` `. | | `problem` | `(id: string, what: string) =>` [`PluginProblem`](#pluginproblem) | | | Returns a problem with one entry, for `check`, reported at ` `. | ## defineCalls [#definecalls] Function. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#definecalls). Returns the `PluginCalls` declaration of a plugin's conditions, effects and commands, each by name with its arguments built from `arg`. A plugin calls it once, and its helpers, the content checker and its registries read that one declaration. ```ts fragment const CALLS = defineCalls('places', { conditions: { at: { location: arg.strings() } }, commands: { go: { id: arg.string() } }, }) ``` Give it to `definePlugin` as `calls`, so each implementation gets its arguments typed and read. Build the helpers from its writers (`CALLS.conditions.at({ location })`), and extend the registries from it (`ConditionsOf`), so content is checked against the same declaration. The content checker reports an argument content left out, one of the wrong shape and one the call doesn't take, and resolves the references each makes. ```ts shape import { defineCalls } from '@ifloom/engine/plugin' function defineCalls(id: Id, shapes: D): PluginCalls ``` Uses: [`CallShapes`](#callshapes), [`PluginCalls`](#plugincalls). ## defineData [#definedata] Function. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#definedata-and-list). Returns the `PluginData` declaration of a plugin's data lists, each by name with its entry's type, its noun and its word fields. A plugin calls it once, and its lookups, the content checker and the words table read that one declaration. ```ts fragment const DATA = defineData('jobs', { jobs: list({ noun: 'job', words: { name: true } }) }) DATA.jobs.all(game) // JobDef[] DATA.jobs.get(game, 'cafe') // JobDef | undefined arg.entry(DATA.jobs) // an argument naming a job, checked ``` Give it to `definePlugin` as `data`, so the loader reaches each list's words for a translation. ```ts shape import { defineData } from '@ifloom/engine/plugin' function defineData>>>(plugin: string, lists: L): PluginData ``` Uses: [`ListSpec`](#listspec), [`PluginData`](#plugindata). ## DefinedPlugin [#definedplugin] Type. Explained in [Plugin API](https://ifloom.dev/docs/reference/plugin-api#definedplugin). A plugin returned by `definePlugin`, with typed `read` and `write` for its own state. ```ts shape import type { DefinedPlugin } from '@ifloom/engine/plugin' type DefinedPlugin = { id: string version: number start?: ((game: Game) => S) migrations?: Record unknown> contentVersion?: number contentMigrations?: Record commandVersion?: number commandMigrations?: Record calls?: AnyCalls data?: PluginData conditions?: Record) => boolean> effects?: Record) => GameState> macros?: Record> commands?: Record> strings?: Record queries?: Record) => unknown> cooperates?: string[] statModifiers?: ((state: GameState, context: PluginContext) => readonly StatModifier[] | undefined) values?: Record) => string | number> onTurn?: ((state: GameState, context: TurnContext) => GameState) onTurnDone?: ((state: GameState, context: TurnContext) => GameState) onStat?: ((before: GameState, after: GameState, stat: string, by: number, context: PluginContext) => GameState) onCommand?: ((before: GameState, after: GameState, context: PluginContext) => GameState) guard?: ((state: GameState, asked: Asked, context: PluginContext) => Refusal | undefined) price?: ((state: GameState, effects: readonly Effect[], context: PluginContext) => string[] | undefined) label?: ((state: GameState, context: PluginContext) => string | undefined) saveName?: ((state: GameState, context: PluginContext) => string | undefined) scene?: ((state: GameState, context: PluginContext) => RoomScene | undefined) actions?: ((state: GameState, context: PluginContext) => readonly ButtonDef[] | undefined) action?: ((state: GameState, id: string, context: PluginContext) => ButtonDef | undefined) content?: Content traits?: readonly TraitDef[] audio?: ((state: GameState, context: PluginContext) => Record | undefined) view?: ((state: GameState, context: PluginContext) => V) profile?: ((state: GameState, previous: GameState, stored: unknown, context: PluginContext) => unknown) references?: PluginReferences check?: (game: Game, tools: CheckTools) => PluginProblem[] receiver?: Receiver carry?: ((fresh: GameState, from: GameState, context: PluginContext) => GameState) read: (state: GameState, game: Game) => S write: (state: GameState, next: S) => GameState } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The plugin's id, the prefix on everything it adds. It holds letters, digits and `-`. | | `version` | `number` | | | The version of the plugin's state's shape. Bump it when the shape changes, and add the step that carries the previous version forward to `migrations`. | | `start` | `((game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => S)` | yes | | Returns the plugin's state in a new game. A plugin with no state leaves it out. | | `migrations` | `Record unknown>` | yes | | The plugin's state migrations, one step per version, keyed by the version each upgrades from. A save whose state has no route forward is refused. Each step gets the plugin's old state and the same `MigrationTools` a game's migration gets, and returns the plugin's new state. | | `contentVersion` | `number` | yes | | The version of the shape of the content and packs written for the plugin, its `data`, calls' arguments, strings and traits. 1 if left out. Bump it when that shape changes, and add the step that carries a pack of the previous version forward to `contentMigrations`. Packs record the version they were written for in `plugins`. | | `contentMigrations` | `Record` | yes | | The plugin's content migrations, one step per content version, keyed by the version each upgrades from. A version with no step changed nothing a pack holds. `upgradePack` runs them on every pack the game loads, mods included, after the engine's own steps for the same schema. See `ContentStep` and `ContentTools`. | | `commandVersion` | `number` | yes | | The version of the plugin's commands' arguments, which command logs record. 1 if left out. Bump it when a command is renamed or its arguments change, and add the step to `commandMigrations`, so an old log still replays. | | `commandMigrations` | `Record` | yes | | The plugin's command migrations, one step per command version, keyed by the version each upgrades from. `replay` runs an older log's commands through them. See `CommandStep`. | | `calls` | [`AnyCalls`](#anycalls) | yes | | The declaration of the plugin's conditions, effects and commands, each with the arguments it takes, from `defineCalls`. Every declared call needs an implementation, and every implementation a declaration. The implementations get their arguments read by it. The content checker reports a call that leaves an argument out, gets one wrong or names something the game lacks, and a translation reaches the words in a call's arguments. | | `data` | [`PluginData`](#plugindata) | yes | | The declaration of the lists in the plugin's `data`, each with its entry's noun and its fields a player reads, from `defineData`. A translation's `words` table reaches those fields by `/..`, such as `quests/quests.coffee.name`. | | `conditions` | `Record) => boolean>` | yes | | The plugin's conditions content can test, by name without the prefix. | | `effects` | `Record) =>…` | yes | | The plugin's effects content can apply, by name without the prefix. Each takes the state the effects before it left and returns the next one, so two in one list compose. Prices and guards can't see what an effect does until it runs. An effect that only stands for other effects belongs in `macros` instead. | | `macros` | `Record>` | yes | | The plugin's macros, effects that stand for other effects, by name without the prefix. A name is an effect's or a macro's, never both. Content calls one as any effect. It returns the effects it stands for, worked out from the state, so a button's price and the guards see what it would do. See `Macro`. | | `commands` | `Record>` | yes | | The plugin's commands a choice or action can send, by name without the prefix. | | `strings` | `Record` | yes | | The plugin's strings, the lines a player reads, by name without the prefix, in English. A game overrides one as `strings['/']`, and the plugin reads them with `stringOf(game, '/')`. | | `queries` | `Record) => unknown>` | yes | | The plugin's queries, answers other plugins ask for by name without importing it, such as `context.query('calendar/whenNext', { when })`. A query answers what a condition's yes or no can't, such as a location, a time or a list. | | `cooperates` | `string[]` | yes | | The ids of the plugins this one works with when the game has them. Content may name their calls in a game without them, where the condition is false and the effect does nothing. The content checker lets those calls pass. | | `statModifiers` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => readonly` [`StatModifier[]`](#statmodifier) `\| undefined)` | yes | | Returns the changes to what the player's stats read now, worked out from the plugin's state, such as a timed boost. It must not read stats itself, or it reads itself. Nothing is written into the state. Every reading of the stat (conditions, derived stats, costs, the view) sees the changed value, and `stat` effects still write the kept value underneath. | | `values` | `Record) => string…` | yes | | The plugin's values, words and numbers content reads by name with arguments, as a condition is asked. Prose prints one as `{{id/name channel=texts}}`, and an `Amount` reads one as `{ value: 'id/name', with }`. | | `onTurn` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`TurnContext`](#turncontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`)` | yes | | The hook run at the end of a turn, once the counter has moved on and `resets` are back. It returns the next state, and the hooks run in order, the game's first. `context.before` is the state as the turn ended, and a `turn` effect applied through `context.apply` does nothing. | | `onTurnDone` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`TurnContext`](#turncontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`)` | yes | | The hook run once every `onTurn` has run, so it sees their changes, such as the calendar's new day. It returns the next state and runs in the same order and context as `onTurn`. | | `onStat` | `((before:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, after:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, stat: string, by: number, context:` [`PluginContext`](#plugincontext)`<…` | yes | | The hook run when a `stat` effect changes one of the player's stats. `before` is the state before it, `after` the state with it, and `by` how far it moved. Return `before` to undo the change, `after` to keep it, or `after` with more changes. The hooks run in order, the game's first, each seeing what the one before returned. | | `onCommand` | `((before:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, after:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`)` | yes | | The hook run after every command that took, with the state before and the state after. It returns the next state, and its context is the state after. | | `guard` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, asked:` [`Asked`](#asked)`, context:` [`PluginContext`](#plugincontext)`) =>` [`Refusal`](#refusal) `\| undefined)` | yes | | Returns a `Refusal` for a command, given the effects it would apply, or undefined to let it through. The engine asks it after the locks, of every command but the ones that ignore locks. | | `price` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, effects: readonly` [`Effect[]`](https://ifloom.dev/docs/api/engine#effect)`, context:` [`PluginContext`](#plugincontext)`) => string[] \|…` | yes | | Returns the plugin's words for what a button costs that the engine can't say, such as `['until evening']`. The engine asks it with the effects the button would apply. | | `label` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => string \| undefined)` | yes | | Returns a few words on the time or place in the game for a header or a save, such as "Day 3 · Wednesday morning". | | `saveName` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => string \| undefined)` | yes | | Returns the name a save is listed under, such as the name the player typed. It is kept as `SaveMeta.playerName` and shown for `@you`'s lines. The first that answers names it, the game's first. With none, saves have no player name. | | `scene` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) =>` [`RoomScene`](#roomscene) `\| undefined)` | yes | | Returns the `RoomScene` the screen shows while no scene is open, such as a location's description or a dashboard's heading. The first plugin that answers fills it. With none, the room shows the game's title and its actions. | | `actions` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => readonly` [`ButtonDef[]`](https://ifloom.dev/docs/api/engine#buttondef) `\| undefined)` | yes | | Returns the actions offered while no scene is open, such as a location's things to do. The view lists them before the game's own `actions`, rendered the same way. | | `action` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, id: string, context:` [`PluginContext`](#plugincontext)`) =>` [`ButtonDef`](https://ifloom.dev/docs/api/engine#buttondef) `\| undefined)` | yes | | Returns one of the plugin's actions that isn't among its `actions` now, by id without the prefix, such as an app's. Undefined when there is none. `{ type: 'action', id: '/' }` runs it, as for an action with a cost or effects. Without this provider, the engine looks the id up among the plugin's `actions`. | | `content` | [`Content`](https://ifloom.dev/docs/api/engine#content) | yes | | The content the plugin brings, merged first, under the game's content and packs, which can replace anything in it by id. It holds the plugin's kinds of entity, such as the cast's `character`, unlisted in the view unless the kind sets `listed`. A game that redeclares a kind keeps the fields it leaves out. It can also hold scenes, prose, actions or `data`. | | `traits` | `readonly` [`TraitDef`](#traitdef)`[]` | yes | | The traits the plugin gives meaning to, each id the plugin's id, `/` and a name. A trait is data only, and the plugin's code decides what it does. Content writes them on a kind, an entity or content's `traits` table, and the plugin reads them with `traitOf` or `declaredTrait`. | | `audio` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => Record \|…` | yes | | Returns the tracks the plugin plays on background channels, by channel, such as a location's ambience. Null silences a channel, and the first plugin that names a channel wins it. A plugin's track is below an open scene's and an `audio` effect's, and above the game's default. A channel left out is the next plugin's, then the default's. | | `view` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => V)` | yes | | Returns the plugin's view, which a UI reads at `view.plugins[id]`. Declare its type `V` in `ViewRegistry` under the plugin's id, and every view types `view.plugins[id]` as `V`. | | `profile` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, previous:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, stored: unknown, context:` [`PluginContext`](#plugincontext)`) =>…` | yes | | Returns the value the plugin keeps in the player's profile, which outlives saves and new games, such as earned achievements. Return undefined to leave the stored value. The runner asks it after every command that took, with the state after, the state before and the value the plugin's profile namespace (its id) holds now. Only a runner with a `profile` asks, and `apply` never does. | | `references` | [`PluginReferences`](#pluginreferences) | yes | | The references the plugin's calls and content make, which the content checker resolves as it resolves the engine's own. See `PluginReferences`. | | `check` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`, tools:` [`CheckTools`](#checktools)`) =>` [`PluginProblem[]`](#pluginproblem) | yes | | Returns the problems the plugin's own rules find that a reference can't express, such as two entries with one id or an exit to nowhere. The content checker runs it after the references. `tools` words problems with anything else the plugin names as the checker does. | | `receiver` | [`Receiver`](#receiver)`` | yes | | The plugin's answers to the `receive` and `release` effects and the `owned` condition, for a plugin that keeps things. An inventory or a wardrobe declares one. See `Receiver`. | | `carry` | `((fresh:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, from:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`)` | yes | | Returns a New Game+'s state with what the plugin carries from the game before laid over it, such as the things the player kept. The plugin starts fresh if left out. `fresh` is the new game's state so far, and `context.get(from)` reads the old game's slice. `context.set` writes the new one, and the plugin may copy an entity made in play with `writeEntity`. | | `read` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => S` | | | Returns the plugin's state in a game state, or its starting state if the save has none yet. | | `write` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, next: S) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | | | Returns the game state with the plugin's state replaced. | ## definePlugin [#defineplugin] Function. Explained in [Plugin API](https://ifloom.dev/docs/reference/plugin-api#defineplugin). Returns a plugin with `read` and `write` for its own state, for code outside it such as tests. It throws when a declared call has no implementation or an implemented one has no declaration. Name the types, `definePlugin`, so the view's type is kept and each call's implementation gets its arguments as `CALLS` (`defineCalls`) declares them. The plugin's view is typed by its `ViewRegistry` entry. ```ts shape import { definePlugin } from '@ifloom/engine/plugin' function definePlugin(def: PluginDef): DefinedPlugin ``` Uses: [`AnyCalls`](#anycalls), [`PluginDef`](#plugindef), [`DefinedPlugin`](#definedplugin). ## defineRules [#definerules] Function. Explained in [Calls by name](https://ifloom.dev/docs/reference/custom#definerules). Returns the game's rules as written, with each condition, effect, macro and command handed its arguments as the rules' `calls` declare them. It throws when a declared call has no implementation or an implemented one has no declaration. Declare the calls with `defineCalls('game', …)` and name its type, `defineRules`. The content checker then checks every `game/` call content writes against the declaration, as it checks a plugin's. ```ts shape import { defineRules } from '@ifloom/engine/plugin' function defineRules(def: RulesDef): GameRules ``` Uses: [`AnyCalls`](#anycalls), [`RulesDef`](#rulesdef), [`GameRules`](https://ifloom.dev/docs/api/engine#gamerules). ## defineTraitKind [#definetraitkind] Function. Explained in [A plugin's view, scene and actions](https://ifloom.dev/docs/reference/plugin-views#definetraitkind). Returns the `TraitKind` of a kind of entity a plugin's trait makes. Declare each such kind once, with this. ```ts fragment const PLACES = defineTraitKind({ kind: 'location', trait: 'places/location', fields: { exits: true, body: true, … } }) PLACES.ref('park') // 'location:park' PLACES.get(state, game, 'park') // its Place, or undefined PLACES.define({ id: 'park', name: 'Riverside Park', exits: [], body: [] }) const CALLS = defineCalls('places', { effects: { move: { location: PLACES.arg() } } }) ``` The plugin still declares the kind itself in its `content.kinds`, with its label and whether it's listed. ```ts shape import { defineTraitKind } from '@ifloom/engine/plugin' function defineTraitKind(spec: TraitKindSpec): TraitKind ``` Uses: [`TraitKindSpec`](#traitkindspec), [`TraitKind`](#traitkind). ## EffectsOf [#effectsof] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#conditionsof-effectsof-and-commandsof). The arguments a plugin's effects take, by full name, for its `EffectRegistry`. Use it as `ConditionsOf` is used. ```ts fragment type EffectsOf = C extends PluginCalls ? { [K in keyof Table & string as `${Id}/${K}`]: Table[K] extends ArgShape ? WrittenAs[K]> : never; } : never ``` Uses: [`PluginCalls`](#plugincalls), [`CallShapes`](#callshapes), [`ArgShape`](#argshape), [`WrittenAs`](#writtenas). ## entityUi [#entityui] Function. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#entityui). Returns an entity's ui hints, its kind's with its `like`'s and then its definition's laid over them field by field. Returns undefined when none has any. ```ts shape import { entityUi } from '@ifloom/engine/plugin' function entityUi(state: GameState, game: Game, ref: string): Ui | undefined ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`Ui`](https://ifloom.dev/docs/api/engine#ui), [`EntityUi`](https://ifloom.dev/docs/api/engine#entityui). ## everyEntity [#everyentity] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#everyentity-and-hasentity). Returns every entity in the game, as references. Declared ones not removed come first in content order, then those made in play, kind by kind in the order each kind first had one. ```ts shape import { everyEntity } from '@ifloom/engine/plugin' function everyEntity(state: GameState, game: Game | undefined): EntityRef[] ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref). ## hasEntity [#hasentity] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#everyentity-and-hasentity). Returns true when an entity is in the game. A declared entity is in until it is removed, and one made in play is in while the save keeps its record. ```ts shape import { hasEntity } from '@ifloom/engine/plugin' function hasEntity(state: GameState, game: Game | undefined, ref: string): boolean ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game). ## list [#list] Function. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#definedata-and-list). Returns the `ListSpec` of one of a plugin's data lists, for `defineData`, with the entry's type, its noun and its words. ```ts shape import { list } from '@ifloom/engine/plugin' function list(spec: { noun: string; words?: WordShape }): ListSpec ``` Uses: [`WordShape`](https://ifloom.dev/docs/api/engine#wordshape), [`ListSpec`](#listspec). ## ListSpec [#listspec] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#listspec). One list of a plugin's data as `list` declares it, such as `list({ noun: 'job', words: { name: true } })`. The type argument is an entry's type. ```ts shape import type { ListSpec } from '@ifloom/engine/plugin' type ListSpec = { noun: string words?: WordShape readonly _entry?: T } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `noun` | `string` | | | The noun a problem calls one entry by, as in `unknown job "cafe"`. | | `words` | [`WordShape`](https://ifloom.dev/docs/api/engine#wordshape) | yes | | The fields of an entry that are words a player reads, for a translation's `words` table. See `WordShape`. | | `_entry` | `T` | yes | | An entry's type, for type inference only. It is never set. | ## Lock [#lock] Type. Explained in [Locks](https://ifloom.dev/docs/reference/locks#lock). A lock the game declares in `locks`, which stops some commands while its `when` holds. The engine refuses the command with `reason`, and the view greys out its button with the same line. A game's stretches are locks, such as an intro that keeps you at one location or a first morning that only lets you get to work. The reducer and the view read the same first lock that matches, so they can't disagree. ```ts shape import type { Lock } from '@ifloom/engine/plugin' type Lock = { id?: string when: Condition deny: readonly LockTarget[] except?: readonly LockTarget[] effect?: string hide?: boolean reason: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | yes | | The lock's id, so a later pack can replace it. A lock with no id is always added. | | `when` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | | | The lock's condition. The lock is on while it holds. | | `deny` | `readonly` [`LockTarget[]`](#locktarget) | | | The commands the lock stops, by type. `'*'` stops every command not in `except`. A plugin's commands can be named one by one (`'quests/track'`) or all at once (`'quests/*'`), and `'custom'` stops every plugin command. | | `except` | `readonly` [`LockTarget[]`](#locktarget) | yes | | The commands the lock lets through all the same, named as in `deny`. | | `effect` | `string` | yes | | The effect a command must apply for the lock to stop it, named by its key. That's the engine's key (`'turn'`) or a plugin's name (`'calendar/pass'`), checked against `effectsOf`. | | `hide` | `boolean` | yes | | The lock's hide mark, true to leave the buttons it stops off the screen rather than greyed out. It covers the room's buttons, the places plugin's exits included, and never a command that ignores locks. | | `reason` | `string` | | | The lock's reason, the line both the refusal and the greyed-out button show. | ## lockedOut [#lockedout] Function. Explained in [Locks](https://ifloom.dev/docs/reference/locks#lockedout). Returns true while a lock that stops everything is on. Until it lifts, the player moves only through its scenes, with no exits, characters or actions in the room. ```ts shape import { lockedOut } from '@ifloom/engine/plugin' function lockedOut(state: GameState, game: Game): boolean ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game). ## lockOn [#lockon] Function. Explained in [Locks](https://ifloom.dev/docs/reference/locks#lockon). Returns the first lock that stops this command now, or undefined when none does. ```ts shape import { lockOn } from '@ifloom/engine/plugin' function lockOn(state: GameState, game: Game, command: Command): Lock | undefined ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`Command`](https://ifloom.dev/docs/api/engine#command), [`Lock`](#lock). ## LockTarget [#locktarget] Type. Explained in [Locks](https://ifloom.dev/docs/reference/locks#locktarget). A name a lock's `deny` and `except` take. It's a command type, `'*'`, a plugin command (`'quests/track'`) or a whole plugin (`'quests/*'`). ```ts shape import type { LockTarget } from '@ifloom/engine/plugin' type LockTarget = Command['type'] | '*' | `${string}/${string}` ``` Uses: [`Command`](https://ifloom.dev/docs/api/engine#command). ## Macro [#macro] Type. Explained in [Calls by name](https://ifloom.dev/docs/reference/custom#macro). An effect that stands for other effects, in a plugin's or the game's `macros`. It returns those effects from the state, so prices, locks and guards see them before it runs. Content calls it as any effect, `{ 'game/payRent': {} }`. It can return any effect content can write, another macro included. ```ts shape import type { Macro } from '@ifloom/engine/plugin' type Macro = (state: GameState, args: A, context: PluginContext) => EffectRef[] ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`PluginContext`](#plugincontext), [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref). ## PackContext [#packcontext] Type. Explained in [Content and packs](https://ifloom.dev/docs/reference/content#packcontext). The parts of the game under a pack that an upgrade step may read beside the pack. `loadGame` passes it, and a step without it reads only the pack. ```ts shape import type { PackContext } from '@ifloom/engine/plugin' type PackContext = { prose?: Readonly> } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `prose` | `Readonly>` | yes | | The prose keys' lines under the pack, from the content and earlier packs. | ## panelOf [#panelof] Function. Explained in [Panels](https://ifloom.dev/docs/reference/panels#panelof). Returns the panel open over the story, as in `view.panel`. It is the one the `panel` effect opened, else the open scene's own, else null. A plugin's view uses it to show what its own panel holds, filtered by the panel's `with`, as the jobs plugin lists the jobs on the open board. ```ts shape import { panelOf } from '@ifloom/engine/plugin' function panelOf(state: GameState, game: Game): OpenPanel | null ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`OpenPanel`](https://ifloom.dev/docs/api/engine#openpanel). ## parseBeats [#parsebeats] Function. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#parsebeats). Returns a body's beats, in order. `find` names the speaker of a line under `@id`, and without it `@you` and `@player` are the player's. ```ts shape import { parseBeats } from '@ifloom/engine/plugin' function parseBeats(body: string, find?: SpeakerFinder): SceneBeat[] ``` Uses: [`SpeakerFinder`](#speakerfinder), [`SceneBeat`](https://ifloom.dev/docs/api/engine#scenebeat). ## pictureView [#pictureview] Function. Explained in [The view](https://ifloom.dev/docs/reference/view#pictureview). Returns the `PictureView` of a picture, with its layers whose `when` holds and their hotspots, or null without a picture. A plugin calls it to render a picture of its own. Each layer's file can be a pool's pick, kept per owner and layer as `picture:`. A hotspot tied to a layer that isn't shown is left out. A `choice` hotspot takes that choice's command and availability from `choices`, the scene's rendered choices, and is left out when the choice is not on offer. A `command` hotspot is rendered as any action is. A plugin's `view` passes its context's `picks`, so the reducer records the layers' picks. ```ts shape import { pictureView } from '@ifloom/engine/plugin' function pictureView(state: GameState, game: Game, picture: PictureDef | undefined, owner: string, choices?: readonly RenderedChoice[] | null, picks?: Record): PictureView | null ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`PictureDef`](https://ifloom.dev/docs/api/engine#picturedef), [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice), [`PictureView`](https://ifloom.dev/docs/api/engine#pictureview). ## Plugin [#plugin] Type. Explained in [Plugin API](https://ifloom.dev/docs/reference/plugin-api#plugin). A system added to the engine, with its own state and the conditions, effects, commands, hooks and view that work on it. A game lists its plugins in `plugins` and never loads one later. Its members follow one naming rule. A hook runs at an event, returns the next state and is named `on` and the event (`onTurn`, `onCommand`). A provider answers a question, never changes the state and is named by the noun it gives (`guard`, `price`, `label`, `scene`, `actions`, `audio`, `statModifiers`, `view`, `profile`). Tables of named functions (`conditions`, `effects`, `commands`, `queries`, `values`) are plural nouns, and nothing is nested. Content calls a plugin by name with its id in front, as in `{ 'quests/done': { quest: 'bakery' } }`, the same way it calls the game's own code (`{ 'game/tired': true }`). A plugin's helpers write those calls for authors working in code. ```ts shape import type { Plugin } from '@ifloom/engine/plugin' type Plugin = { id: string version: number start?: (game: Game) => S migrations?: Record unknown> contentVersion?: number contentMigrations?: Record commandVersion?: number commandMigrations?: Record calls?: AnyCalls data?: PluginData conditions?: Record) => boolean> effects?: Record) => GameState> macros?: Record> commands?: Record> strings?: Record queries?: Record) => unknown> cooperates?: string[] statModifiers?: ((state: GameState, context: PluginContext) => readonly StatModifier[] | undefined) values?: Record) => string | number> onTurn?: (state: GameState, context: TurnContext) => GameState onTurnDone?: (state: GameState, context: TurnContext) => GameState onStat?: (before: GameState, after: GameState, stat: string, by: number, context: PluginContext) => GameState onCommand?: (before: GameState, after: GameState, context: PluginContext) => GameState guard?: ((state: GameState, asked: Asked, context: PluginContext) => Refusal | undefined) price?: ((state: GameState, effects: readonly Effect[], context: PluginContext) => string[] | undefined) label?: ((state: GameState, context: PluginContext) => string | undefined) saveName?: ((state: GameState, context: PluginContext) => string | undefined) scene?: ((state: GameState, context: PluginContext) => RoomScene | undefined) actions?: ((state: GameState, context: PluginContext) => readonly ButtonDef[] | undefined) action?: ((state: GameState, id: string, context: PluginContext) => ButtonDef | undefined) content?: Content traits?: readonly TraitDef[] audio?: ((state: GameState, context: PluginContext) => Record | undefined) view?: (state: GameState, context: PluginContext) => V profile?: (state: GameState, previous: GameState, stored: unknown, context: PluginContext) => unknown references?: PluginReferences check?: (game: Game, tools: CheckTools) => PluginProblem[] receiver?: Receiver carry?: (fresh: GameState, from: GameState, context: PluginContext) => GameState } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The plugin's id, the prefix on everything it adds. It holds letters, digits and `-`. | | `version` | `number` | | | The version of the plugin's state's shape. Bump it when the shape changes, and add the step that carries the previous version forward to `migrations`. | | `start` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => S` | yes | | Returns the plugin's state in a new game. A plugin with no state leaves it out. | | `migrations` | `Record unknown>` | yes | | The plugin's state migrations, one step per version, keyed by the version each upgrades from. A save whose state has no route forward is refused. Each step gets the plugin's old state and the same `MigrationTools` a game's migration gets, and returns the plugin's new state. | | `contentVersion` | `number` | yes | | The version of the shape of the content and packs written for the plugin, its `data`, calls' arguments, strings and traits. 1 if left out. Bump it when that shape changes, and add the step that carries a pack of the previous version forward to `contentMigrations`. Packs record the version they were written for in `plugins`. | | `contentMigrations` | `Record` | yes | | The plugin's content migrations, one step per content version, keyed by the version each upgrades from. A version with no step changed nothing a pack holds. `upgradePack` runs them on every pack the game loads, mods included, after the engine's own steps for the same schema. See `ContentStep` and `ContentTools`. | | `commandVersion` | `number` | yes | | The version of the plugin's commands' arguments, which command logs record. 1 if left out. Bump it when a command is renamed or its arguments change, and add the step to `commandMigrations`, so an old log still replays. | | `commandMigrations` | `Record` | yes | | The plugin's command migrations, one step per command version, keyed by the version each upgrades from. `replay` runs an older log's commands through them. See `CommandStep`. | | `calls` | [`AnyCalls`](#anycalls) | yes | | The declaration of the plugin's conditions, effects and commands, each with the arguments it takes, from `defineCalls`. Every declared call needs an implementation, and every implementation a declaration. The implementations get their arguments read by it. The content checker reports a call that leaves an argument out, gets one wrong or names something the game lacks, and a translation reaches the words in a call's arguments. | | `data` | [`PluginData`](#plugindata) | yes | | The declaration of the lists in the plugin's `data`, each with its entry's noun and its fields a player reads, from `defineData`. A translation's `words` table reaches those fields by `/..`, such as `quests/quests.coffee.name`. | | `conditions` | `Record) => boolean>` | yes | | The plugin's conditions content can test, by name without the prefix. | | `effects` | `Record) =>…` | yes | | The plugin's effects content can apply, by name without the prefix. Each takes the state the effects before it left and returns the next one, so two in one list compose. Prices and guards can't see what an effect does until it runs. An effect that only stands for other effects belongs in `macros` instead. | | `macros` | `Record>` | yes | | The plugin's macros, effects that stand for other effects, by name without the prefix. A name is an effect's or a macro's, never both. Content calls one as any effect. It returns the effects it stands for, worked out from the state, so a button's price and the guards see what it would do. See `Macro`. | | `commands` | `Record>` | yes | | The plugin's commands a choice or action can send, by name without the prefix. | | `strings` | `Record` | yes | | The plugin's strings, the lines a player reads, by name without the prefix, in English. A game overrides one as `strings['/']`, and the plugin reads them with `stringOf(game, '/')`. | | `queries` | `Record) => unknown>` | yes | | The plugin's queries, answers other plugins ask for by name without importing it, such as `context.query('calendar/whenNext', { when })`. A query answers what a condition's yes or no can't, such as a location, a time or a list. | | `cooperates` | `string[]` | yes | | The ids of the plugins this one works with when the game has them. Content may name their calls in a game without them, where the condition is false and the effect does nothing. The content checker lets those calls pass. | | `statModifiers` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => readonly` [`StatModifier[]`](#statmodifier) `\| undefined)` | yes | | Returns the changes to what the player's stats read now, worked out from the plugin's state, such as a timed boost. It must not read stats itself, or it reads itself. Nothing is written into the state. Every reading of the stat (conditions, derived stats, costs, the view) sees the changed value, and `stat` effects still write the kept value underneath. | | `values` | `Record) => string…` | yes | | The plugin's values, words and numbers content reads by name with arguments, as a condition is asked. Prose prints one as `{{id/name channel=texts}}`, and an `Amount` reads one as `{ value: 'id/name', with }`. | | `onTurn` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`TurnContext`](#turncontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | yes | | The hook run at the end of a turn, once the counter has moved on and `resets` are back. It returns the next state, and the hooks run in order, the game's first. `context.before` is the state as the turn ended, and a `turn` effect applied through `context.apply` does nothing. | | `onTurnDone` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`TurnContext`](#turncontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | yes | | The hook run once every `onTurn` has run, so it sees their changes, such as the calendar's new day. It returns the next state and runs in the same order and context as `onTurn`. | | `onStat` | `(before:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, after:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, stat: string, by: number, context:` [`PluginContext`](#plugincontext)`…` | yes | | The hook run when a `stat` effect changes one of the player's stats. `before` is the state before it, `after` the state with it, and `by` how far it moved. Return `before` to undo the change, `after` to keep it, or `after` with more changes. The hooks run in order, the game's first, each seeing what the one before returned. | | `onCommand` | `(before:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, after:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | yes | | The hook run after every command that took, with the state before and the state after. It returns the next state, and its context is the state after. | | `guard` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, asked:` [`Asked`](#asked)`, context:` [`PluginContext`](#plugincontext)`) =>` [`Refusal`](#refusal) `\| undefined)` | yes | | Returns a `Refusal` for a command, given the effects it would apply, or undefined to let it through. The engine asks it after the locks, of every command but the ones that ignore locks. | | `price` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, effects: readonly` [`Effect[]`](https://ifloom.dev/docs/api/engine#effect)`, context:` [`PluginContext`](#plugincontext)`) => string[] \|…` | yes | | Returns the plugin's words for what a button costs that the engine can't say, such as `['until evening']`. The engine asks it with the effects the button would apply. | | `label` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => string \| undefined)` | yes | | Returns a few words on the time or place in the game for a header or a save, such as "Day 3 · Wednesday morning". | | `saveName` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => string \| undefined)` | yes | | Returns the name a save is listed under, such as the name the player typed. It is kept as `SaveMeta.playerName` and shown for `@you`'s lines. The first that answers names it, the game's first. With none, saves have no player name. | | `scene` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) =>` [`RoomScene`](#roomscene) `\| undefined)` | yes | | Returns the `RoomScene` the screen shows while no scene is open, such as a location's description or a dashboard's heading. The first plugin that answers fills it. With none, the room shows the game's title and its actions. | | `actions` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => readonly` [`ButtonDef[]`](https://ifloom.dev/docs/api/engine#buttondef) `\| undefined)` | yes | | Returns the actions offered while no scene is open, such as a location's things to do. The view lists them before the game's own `actions`, rendered the same way. | | `action` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, id: string, context:` [`PluginContext`](#plugincontext)`) =>` [`ButtonDef`](https://ifloom.dev/docs/api/engine#buttondef) `\| undefined)` | yes | | Returns one of the plugin's actions that isn't among its `actions` now, by id without the prefix, such as an app's. Undefined when there is none. `{ type: 'action', id: '/' }` runs it, as for an action with a cost or effects. Without this provider, the engine looks the id up among the plugin's `actions`. | | `content` | [`Content`](https://ifloom.dev/docs/api/engine#content) | yes | | The content the plugin brings, merged first, under the game's content and packs, which can replace anything in it by id. It holds the plugin's kinds of entity, such as the cast's `character`, unlisted in the view unless the kind sets `listed`. A game that redeclares a kind keeps the fields it leaves out. It can also hold scenes, prose, actions or `data`. | | `traits` | `readonly` [`TraitDef`](#traitdef)`[]` | yes | | The traits the plugin gives meaning to, each id the plugin's id, `/` and a name. A trait is data only, and the plugin's code decides what it does. Content writes them on a kind, an entity or content's `traits` table, and the plugin reads them with `traitOf` or `declaredTrait`. | | `audio` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => Record \|…` | yes | | Returns the tracks the plugin plays on background channels, by channel, such as a location's ambience. Null silences a channel, and the first plugin that names a channel wins it. A plugin's track is below an open scene's and an `audio` effect's, and above the game's default. A channel left out is the next plugin's, then the default's. | | `view` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => V` | yes | | Returns the plugin's view, which a UI reads at `view.plugins[id]`. Declare its type `V` in `ViewRegistry` under the plugin's id, and every view types `view.plugins[id]` as `V`. | | `profile` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, previous:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, stored: unknown, context:` [`PluginContext`](#plugincontext)`) =>…` | yes | | Returns the value the plugin keeps in the player's profile, which outlives saves and new games, such as earned achievements. Return undefined to leave the stored value. The runner asks it after every command that took, with the state after, the state before and the value the plugin's profile namespace (its id) holds now. Only a runner with a `profile` asks, and `apply` never does. | | `references` | [`PluginReferences`](#pluginreferences) | yes | | The references the plugin's calls and content make, which the content checker resolves as it resolves the engine's own. See `PluginReferences`. | | `check` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`, tools:` [`CheckTools`](#checktools)`) =>` [`PluginProblem[]`](#pluginproblem) | yes | | Returns the problems the plugin's own rules find that a reference can't express, such as two entries with one id or an exit to nowhere. The content checker runs it after the references. `tools` words problems with anything else the plugin names as the checker does. | | `receiver` | [`Receiver`](#receiver)`` | yes | | The plugin's answers to the `receive` and `release` effects and the `owned` condition, for a plugin that keeps things. An inventory or a wardrobe declares one. See `Receiver`. | | `carry` | `(fresh:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, from:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | yes | | Returns a New Game+'s state with what the plugin carries from the game before laid over it, such as the things the player kept. The plugin starts fresh if left out. `fresh` is the new game's state so far, and `context.get(from)` reads the old game's slice. `context.set` writes the new one, and the plugin may copy an entity made in play with `writeEntity`. | ## PluginArgs [#pluginargs] Type. Explained in [Plugin API](https://ifloom.dev/docs/reference/plugin-api#pluginargs). The arguments content passes to a plugin's condition, effect or command, as an object. ```ts shape import type { PluginArgs } from '@ifloom/engine/plugin' type PluginArgs = { [key: string]: unknown } ``` ## PluginCalls [#plugincalls] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#plugincalls-and-anycalls). A plugin's calls as `defineCalls` declares them, with a `CallWriter` for each, by table, such as `calls.conditions.at({ location })`. Give it to `definePlugin` as `calls`, and derive the registries from it. ```ts fragment type PluginCalls = { readonly id: Id readonly conditions: Writers> readonly effects: Writers> readonly commands: Writers> } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `Id` | | | The plugin's id. | | `conditions` | `Writers>` | | | The writers of the plugin's conditions, by name. | | `effects` | `Writers>` | | | The writers of the plugin's effects, by name. | | `commands` | `Writers>` | | | The writers of the plugin's commands, by name. | ## PluginCommand [#plugincommand] Type. Explained in [Plugin API](https://ifloom.dev/docs/reference/plugin-api#plugincommand). A command a plugin declares in its `commands`, with its refusal, its run and what it would apply. ```ts shape import type { PluginCommand } from '@ifloom/engine/plugin' type PluginCommand = { ignoresLocks?: boolean whyNot?: ((state: GameState, args: A, context: PluginContext) => string | undefined) run: (state: GameState, args: A, context: PluginContext) => GameState effectsOf?: (state: GameState, args: A, context: PluginContext) => Effect[] spends?: ((state: GameState, args: A, context: PluginContext) => Record | undefined) } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `ignoresLocks` | `boolean` | yes | | The setting that runs the command even while a lock would stop it. Use it for tools outside the story, such as a debugger, never for something the player does in it. | | `whyNot` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, args: A, context:` [`PluginContext`](#plugincontext)`) => string \| undefined)` | yes | | Returns the reason the command can't run now, in the player's words, or undefined if it can. | | `run` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, args: A, context:` [`PluginContext`](#plugincontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | | | Returns the state after the command. The engine calls it only when `whyNot` gave no reason. | | `effectsOf` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, args: A, context:` [`PluginContext`](#plugincontext)`) =>` [`Effect[]`](https://ifloom.dev/docs/api/engine#effect) | yes | | Returns the effects running the command would apply, for guards, prices and locks to see. None if left out. | | `spends` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, args: A, context:` [`PluginContext`](#plugincontext)`) => Record \|…` | yes | | Returns the stats the command spends, by id, for its button's price, as an action's `cost.stats` gives them, such as `{ coins: 4 }`. None if left out. Only the price shows it. `run` does the spending, and `whyNot` refuses when there isn't enough. | ## PluginContext [#plugincontext] Type. Explained in [Plugin API](https://ifloom.dev/docs/reference/plugin-api#plugincontext). The context every plugin function gets besides the game state. It adds the plugin's own state, typed, to the `CustomContext` a game's own functions get. `get` reads the plugin's state from a later game state, and `set` returns the game state with it replaced. ```ts shape import type { PluginContext } from '@ifloom/engine/plugin' type PluginContext = { game: Game query: Query value: (name: string, args?: PluginArgs) => string | number | undefined roll: (max: number, name: string) => number slice: S get: (on?: GameState) => S set: (next: S, on?: GameState) => GameState apply: (effects: readonly EffectRef[], on?: GameState) => GameState picks?: Record beats: (blocks: readonly Block[], id: string) => SceneBeat[] profile?: unknown } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `game` | [`Game`](https://ifloom.dev/docs/api/engine#game) | | | The context's loaded game. | | `query` | [`Query`](https://ifloom.dev/docs/api/engine#query) | | | The context's query function, which asks a plugin or the game by full name (`query('loyalty/stampsLeft')`). | | `value` | `(name: string, args?:` [`PluginArgs`](#pluginargs)`) => string \| number \| undefined` | | | The context's value function, which returns a value by full name, a plugin's (`messages/unread`) or the game's, asked with `args`. It returns undefined when no plugin or game has that value. | | `roll` | `(max: number, name: string) => number` | | | The context's roll function, which returns a whole number from 0 to `max - 1`, drawn from the save's seed, the turn and `name`. The same save and turn always draw the same number. | | `slice` | `S` | | | The plugin's state in the game state the function was given, the same as `get()`. | | `get` | `(on?:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`) => S` | | | Returns the plugin's state in the game state the function was given, or in `on`. Its starting state (`start`) when the save has none yet. Pass `on` from a function that has already changed the game state, such as by applying effects, to read the plugin's state as it is now. It is the read that matches `set`. | | `set` | `(next: S, on?:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | | | Returns the game state with the plugin's state replaced, on the state the function was given or on `on`. Pass `on` from a function that has already changed other parts of the game state. | | `apply` | `(effects: readonly` [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref)`, on?:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | | | Returns the state after a list of effects, applied to the state the function was given or to `on`. Any effect works, a custom one or another plugin's included. A plugin's effect ends a turn with `apply([{ turn: true }])`. | | `picks` | `Record` | yes | | The record of the pool picks a `view` makes, for the reducer to keep. It is set only in `view`. Pass it to `pictureView` so a picture's pick stays the same on every visit. `beats` records its own. | | `beats` | `(blocks: readonly` [`Block[]`](https://ifloom.dev/docs/api/engine#block)`, id: string) =>` [`SceneBeat[]`](https://ifloom.dev/docs/api/engine#scenebeat) | | | Returns blocks rendered as beats, the way a scene's body is, for a message's words, a post's or an app's. Only the blocks whose `when` holds are rendered. Words are filled in for this save, variants and pools drawn under `id` so a block's pick stays the same on every visit, spoken lines given their speakers, and bold, italics and UI pieces made spans. Inline actions and tooltips stay as plain words, since only a scene offers choices. In `view`, the reducer records the pool picks it makes. | | `profile` | `unknown` | yes | | The value the plugin's own profile namespace (its id) held when the runner last read or wrote it. It is set only in `view`, when a runner with a profile builds the view. It is frozen, so read it and never change it. It is undefined in a view built by `view(state, game)` alone and while nothing is stored. Conditions, effects, commands and hooks never see it, so a replay always plays the same. | ## PluginData [#plugindata] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#plugindata). A plugin's `DataList`s as `defineData` declares them, by name. Give them to `definePlugin` as `data`. ```ts fragment type PluginData>> = Readonly>>> = { readonly [K in keyof L & string]: DataList>; } ``` Uses: [`DataList`](#datalist). ## PluginDef [#plugindef] Type. Explained in [Plugin API](https://ifloom.dev/docs/reference/plugin-api#plugindef). The plugin `definePlugin` takes. When it declares its `calls`, its conditions, effects, macros and commands must be exactly the declared ones, each given its arguments typed. A declared effect is implemented in `effects` or `macros`. ```ts fragment type PluginDef = { view?: ((state: GameState, context: PluginContext) => V) references?: PluginReferences traits?: readonly TraitDef[] actions?: ((state: GameState, context: PluginContext) => readonly ButtonDef[] | undefined) audio?: ((state: GameState, context: PluginContext) => Record | undefined) scene?: ((state: GameState, context: PluginContext) => RoomScene | undefined) receiver?: Receiver action?: ((state: GameState, id: string, context: PluginContext) => ButtonDef | undefined) id: string label?: ((state: GameState, context: PluginContext) => string | undefined) start?: ((game: Game) => S) version: number data?: PluginData content?: Content values?: Record) => string | number> strings?: Record migrations?: Record unknown> cooperates?: string[] contentVersion?: number contentMigrations?: Record commandVersion?: number commandMigrations?: Record carry?: ((fresh: GameState, from: GameState, context: PluginContext) => GameState) queries?: Record) => unknown> statModifiers?: ((state: GameState, context: PluginContext) => readonly StatModifier[] | undefined) onTurn?: ((state: GameState, context: TurnContext) => GameState) onTurnDone?: ((state: GameState, context: TurnContext) => GameState) onStat?: ((before: GameState, after: GameState, stat: string, by: number, context: PluginContext) => GameState) onCommand?: ((before: GameState, after: GameState, context: PluginContext) => GameState) guard?: ((state: GameState, asked: Asked, context: PluginContext) => Refusal | undefined) price?: ((state: GameState, effects: readonly Effect[], context: PluginContext) => string[] | undefined) saveName?: ((state: GameState, context: PluginContext) => string | undefined) profile?: ((state: GameState, previous: GameState, stored: unknown, context: PluginContext) => unknown) check?: (game: Game, tools: CheckTools) => PluginProblem[] conditions?: Record) => boolean> | Implemented effects?: Record) => GameState> | Partial> commands?: Record> | { [K in keyof CallArgs]: PluginCommand[K]>; } macros?: Record> | { [K in keyof CallArgs]?: Macro[K]>; } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `view` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => V)` | yes | | Returns the plugin's view, which a UI reads at `view.plugins[id]`. Declare its type `V` in `ViewRegistry` under the plugin's id, and every view types `view.plugins[id]` as `V`. | | `references` | [`PluginReferences`](#pluginreferences) | yes | | The references the plugin's calls and content make, which the content checker resolves as it resolves the engine's own. See `PluginReferences`. | | `traits` | `readonly` [`TraitDef`](#traitdef)`[]` | yes | | The traits the plugin gives meaning to, each id the plugin's id, `/` and a name. A trait is data only, and the plugin's code decides what it does. Content writes them on a kind, an entity or content's `traits` table, and the plugin reads them with `traitOf` or `declaredTrait`. | | `actions` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => readonly` [`ButtonDef[]`](https://ifloom.dev/docs/api/engine#buttondef) `\| undefined)` | yes | | Returns the actions offered while no scene is open, such as a location's things to do. The view lists them before the game's own `actions`, rendered the same way. | | `audio` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => Record \|…` | yes | | Returns the tracks the plugin plays on background channels, by channel, such as a location's ambience. Null silences a channel, and the first plugin that names a channel wins it. A plugin's track is below an open scene's and an `audio` effect's, and above the game's default. A channel left out is the next plugin's, then the default's. | | `scene` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) =>` [`RoomScene`](#roomscene) `\| undefined)` | yes | | Returns the `RoomScene` the screen shows while no scene is open, such as a location's description or a dashboard's heading. The first plugin that answers fills it. With none, the room shows the game's title and its actions. | | `receiver` | [`Receiver`](#receiver)`` | yes | | The plugin's answers to the `receive` and `release` effects and the `owned` condition, for a plugin that keeps things. An inventory or a wardrobe declares one. See `Receiver`. | | `action` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, id: string, context:` [`PluginContext`](#plugincontext)`) =>` [`ButtonDef`](https://ifloom.dev/docs/api/engine#buttondef) `\| undefined)` | yes | | Returns one of the plugin's actions that isn't among its `actions` now, by id without the prefix, such as an app's. Undefined when there is none. `{ type: 'action', id: '/' }` runs it, as for an action with a cost or effects. Without this provider, the engine looks the id up among the plugin's `actions`. | | `id` | `string` | | | The plugin's id, the prefix on everything it adds. It holds letters, digits and `-`. | | `label` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => string \| undefined)` | yes | | Returns a few words on the time or place in the game for a header or a save, such as "Day 3 · Wednesday morning". | | `start` | `((game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => S)` | yes | | Returns the plugin's state in a new game. A plugin with no state leaves it out. | | `version` | `number` | | | The version of the plugin's state's shape. Bump it when the shape changes, and add the step that carries the previous version forward to `migrations`. | | `data` | [`PluginData`](#plugindata) | yes | | The declaration of the lists in the plugin's `data`, each with its entry's noun and its fields a player reads, from `defineData`. A translation's `words` table reaches those fields by `/..`, such as `quests/quests.coffee.name`. | | `content` | [`Content`](https://ifloom.dev/docs/api/engine#content) | yes | | The content the plugin brings, merged first, under the game's content and packs, which can replace anything in it by id. It holds the plugin's kinds of entity, such as the cast's `character`, unlisted in the view unless the kind sets `listed`. A game that redeclares a kind keeps the fields it leaves out. It can also hold scenes, prose, actions or `data`. | | `values` | `Record) => string…` | yes | | The plugin's values, words and numbers content reads by name with arguments, as a condition is asked. Prose prints one as `{{id/name channel=texts}}`, and an `Amount` reads one as `{ value: 'id/name', with }`. | | `strings` | `Record` | yes | | The plugin's strings, the lines a player reads, by name without the prefix, in English. A game overrides one as `strings['/']`, and the plugin reads them with `stringOf(game, '/')`. | | `migrations` | `Record unknown>` | yes | | The plugin's state migrations, one step per version, keyed by the version each upgrades from. A save whose state has no route forward is refused. Each step gets the plugin's old state and the same `MigrationTools` a game's migration gets, and returns the plugin's new state. | | `cooperates` | `string[]` | yes | | The ids of the plugins this one works with when the game has them. Content may name their calls in a game without them, where the condition is false and the effect does nothing. The content checker lets those calls pass. | | `contentVersion` | `number` | yes | | The version of the shape of the content and packs written for the plugin, its `data`, calls' arguments, strings and traits. 1 if left out. Bump it when that shape changes, and add the step that carries a pack of the previous version forward to `contentMigrations`. Packs record the version they were written for in `plugins`. | | `contentMigrations` | `Record` | yes | | The plugin's content migrations, one step per content version, keyed by the version each upgrades from. A version with no step changed nothing a pack holds. `upgradePack` runs them on every pack the game loads, mods included, after the engine's own steps for the same schema. See `ContentStep` and `ContentTools`. | | `commandVersion` | `number` | yes | | The version of the plugin's commands' arguments, which command logs record. 1 if left out. Bump it when a command is renamed or its arguments change, and add the step to `commandMigrations`, so an old log still replays. | | `commandMigrations` | `Record` | yes | | The plugin's command migrations, one step per command version, keyed by the version each upgrades from. `replay` runs an older log's commands through them. See `CommandStep`. | | `carry` | `((fresh:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, from:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`)` | yes | | Returns a New Game+'s state with what the plugin carries from the game before laid over it, such as the things the player kept. The plugin starts fresh if left out. `fresh` is the new game's state so far, and `context.get(from)` reads the old game's slice. `context.set` writes the new one, and the plugin may copy an entity made in play with `writeEntity`. | | `queries` | `Record) => unknown>` | yes | | The plugin's queries, answers other plugins ask for by name without importing it, such as `context.query('calendar/whenNext', { when })`. A query answers what a condition's yes or no can't, such as a location, a time or a list. | | `statModifiers` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => readonly` [`StatModifier[]`](#statmodifier) `\| undefined)` | yes | | Returns the changes to what the player's stats read now, worked out from the plugin's state, such as a timed boost. It must not read stats itself, or it reads itself. Nothing is written into the state. Every reading of the stat (conditions, derived stats, costs, the view) sees the changed value, and `stat` effects still write the kept value underneath. | | `onTurn` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`TurnContext`](#turncontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`)` | yes | | The hook run at the end of a turn, once the counter has moved on and `resets` are back. It returns the next state, and the hooks run in order, the game's first. `context.before` is the state as the turn ended, and a `turn` effect applied through `context.apply` does nothing. | | `onTurnDone` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`TurnContext`](#turncontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`)` | yes | | The hook run once every `onTurn` has run, so it sees their changes, such as the calendar's new day. It returns the next state and runs in the same order and context as `onTurn`. | | `onStat` | `((before:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, after:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, stat: string, by: number, context:` [`PluginContext`](#plugincontext)`<…` | yes | | The hook run when a `stat` effect changes one of the player's stats. `before` is the state before it, `after` the state with it, and `by` how far it moved. Return `before` to undo the change, `after` to keep it, or `after` with more changes. The hooks run in order, the game's first, each seeing what the one before returned. | | `onCommand` | `((before:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, after:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`)` | yes | | The hook run after every command that took, with the state before and the state after. It returns the next state, and its context is the state after. | | `guard` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, asked:` [`Asked`](#asked)`, context:` [`PluginContext`](#plugincontext)`) =>` [`Refusal`](#refusal) `\| undefined)` | yes | | Returns a `Refusal` for a command, given the effects it would apply, or undefined to let it through. The engine asks it after the locks, of every command but the ones that ignore locks. | | `price` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, effects: readonly` [`Effect[]`](https://ifloom.dev/docs/api/engine#effect)`, context:` [`PluginContext`](#plugincontext)`) => string[] \|…` | yes | | Returns the plugin's words for what a button costs that the engine can't say, such as `['until evening']`. The engine asks it with the effects the button would apply. | | `saveName` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => string \| undefined)` | yes | | Returns the name a save is listed under, such as the name the player typed. It is kept as `SaveMeta.playerName` and shown for `@you`'s lines. The first that answers names it, the game's first. With none, saves have no player name. | | `profile` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, previous:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, stored: unknown, context:` [`PluginContext`](#plugincontext)`) =>…` | yes | | Returns the value the plugin keeps in the player's profile, which outlives saves and new games, such as earned achievements. Return undefined to leave the stored value. The runner asks it after every command that took, with the state after, the state before and the value the plugin's profile namespace (its id) holds now. Only a runner with a `profile` asks, and `apply` never does. | | `check` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`, tools:` [`CheckTools`](#checktools)`) =>` [`PluginProblem[]`](#pluginproblem) | yes | | Returns the problems the plugin's own rules find that a reference can't express, such as two entries with one id or an exit to nowhere. The content checker runs it after the references. `tools` words problems with anything else the plugin names as the checker does. | | `conditions` | `Record) =>…` | yes | | The plugin's conditions content can test, by name without the prefix. | | `effects` | `Record) =>…` | yes | | The plugin's effects content can apply, by name without the prefix. Each takes the state the effects before it left and returns the next one, so two in one list compose. Prices and guards can't see what an effect does until it runs. An effect that only stands for other effects belongs in `macros` instead. | | `commands` | `Record> \| { [K in keyof` [`CallArgs`](#callargs)`]:…` | yes | | The plugin's commands a choice or action can send, by name without the prefix. | | `macros` | `Record> \| { [K in keyof` [`CallArgs`](#callargs)`]?:` [`Macro`](#macro)` readonly Reference[] panels?: (panel: string, args: PluginArgs, game: Game) => readonly Reference[] content?: (game: Game) => readonly ContentReferences[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `calls` | `(table:` [`CallTable`](#calltable)`, name: string, args:` [`PluginArgs`](#pluginargs)`, game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => readonly` [`Reference[]`](#reference) | yes | | Returns the references a call to one of the plugin's conditions, effects or commands makes, by name without the prefix, from the call's arguments. The checker asks it of every call it finds. A reference can be a location, a character or a prose key. A rule of the plugin's own about the arguments is a `{ problem }`, such as `{ problem: 'count must be a whole number' }`. | | `panels` | `(panel: string, args:` [`PluginArgs`](#pluginargs)`, game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => readonly` [`Reference[]`](#reference) | yes | | Returns the references opening one of the plugin's panels makes, from its `with`, such as `[{ entity: 'vendor:fish', carrying: 'shop/vendor' }]` for `panel: 'shop'`. The checker asks it of every panel it finds. Return nothing for a panel that isn't the plugin's. A UI checks a panel no plugin claims. | | `content` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => readonly` [`ContentReferences[]`](#contentreferences) | yes | | Returns the references the plugin's content makes, entry by entry, such as `{ list: 'locations', id: 'cafe', refs: [...] }`. The checker reports a problem against ` `, on the pack the entry came from. | ## PluginSlice [#pluginslice] Type. Explained in [Plugin migrations](https://ifloom.dev/docs/reference/plugin-migrations#pluginslice). The state a save keeps for one plugin, with the version of its shape. ```ts shape import type { PluginSlice } from '@ifloom/engine/plugin' type PluginSlice = { version: number state: unknown } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `version` | `number` | | | The plugin's `version` the state was written in. | | `state` | `unknown` | | | The plugin's state. | ## priceView [#priceview] Function. Explained in [The view](https://ifloom.dev/docs/reference/view#priceview). Returns the `Price` of some stats and notes, or null when it costs nothing. A plugin's view calls it for a price of its own, such as a vendor's full price. It lists each stat spent above 0 in the order given, worded as the stat's value is, then the `notes`, and joins them into one line in `text`. ```ts shape import { priceView } from '@ifloom/engine/plugin' function priceView(game: Game, stats: Readonly>, notes?: readonly string[]): Price | null ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`Price`](https://ifloom.dev/docs/api/engine#price). ## QueryAnswer [#queryanswer] Type. Explained in [Queries and partners](https://ifloom.dev/docs/reference/plugin-queries#queryargs-and-queryanswer). The answer a query gives, as `QueryRegistry` declares it, or `unknown` for an undeclared name. ```ts shape import type { QueryAnswer } from '@ifloom/engine/plugin' type QueryAnswer = K extends keyof QueryRegistry ? QueryRegistry[K] extends (...args: never[]) => infer R ? R : unknown : unknown ``` Uses: [`QueryRegistry`](https://ifloom.dev/docs/api/engine#queryregistry). ## QueryArgs [#queryargs] Type. Explained in [Queries and partners](https://ifloom.dev/docs/reference/plugin-queries#queryargs-and-queryanswer). The arguments a query takes, as `QueryRegistry` declares them, or an optional object for an undeclared name. ```ts shape import type { QueryArgs } from '@ifloom/engine/plugin' type QueryArgs = K extends keyof QueryRegistry ? QueryRegistry[K] extends (...args: infer A) => unknown ? A : [ PluginArgs? ] : [ PluginArgs? ] ``` Uses: [`QueryRegistry`](https://ifloom.dev/docs/api/engine#queryregistry), [`PluginArgs`](#pluginargs). ## RawCall [#rawcall] Type. Explained in [Plugin migrations](https://ifloom.dev/docs/reference/plugin-migrations#rawcall). A plugin call passed to a `ContentTools.calls` rewrite. ```ts shape import type { RawCall } from '@ifloom/engine/plugin' type RawCall = { name: string with: unknown form: CallForm } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | | | The call's full name, such as `'places/at'`. | | `with` | `unknown` | | | The call's arguments, unchanged from the pack. | | `form` | [`CallForm`](#callform) | | | The call's form in the pack. | ## RawCommand [#rawcommand] Type. Explained in [Plugin migrations](https://ifloom.dev/docs/reference/plugin-migrations#rawcommand). A command from a command log, in the shape of the engine or plugin version that wrote it. ```ts shape import type { RawCommand } from '@ifloom/engine/plugin' type RawCommand = { type: string } ``` It also takes any other key: `[key: string]: unknown`. | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `type` | `string` | | | The command's type, such as `choose` or a plugin's `quests/track`. | ## Receiver [#receiver] Type. Explained in [Plugin API](https://ifloom.dev/docs/reference/plugin-api#receiver-1). A plugin that keeps things, as the `receive` and `release` effects and the `owned` condition ask it. The core keeps nothing itself. It asks the game's receivers in the order of the game's `receivers`, else of its `plugins`. `to`, `from` and `of` are someone (`'player'`, `'you'` or a unique entity) or undefined, when the receiver chooses its own default. ```ts shape import type { Receiver } from '@ifloom/engine/plugin' type Receiver = { claims?: (state: GameState, ref: EntityRef, context: PluginContext) => boolean receive: (state: GameState, ref: EntityRef, count: number, to: string | undefined, context: PluginContext) => GameState owned: (state: GameState, ref: EntityRef, of: string | undefined, context: PluginContext) => number release: (state: GameState, ref: EntityRef, count: number, from: string | undefined, context: PluginContext) => GameState } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `claims` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, ref:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, context:` [`PluginContext`](#plugincontext)`) => boolean` | yes | | Returns true when the receiver takes this thing, such as a wardrobe for things that are worn. Every thing if left out. | | `receive` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, ref:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, count: number, to: string \| undefined, context:…` | | | Returns the state with `count` of the thing given to `to`. | | `owned` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, ref:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, of: string \| undefined, context:` [`PluginContext`](#plugincontext)`) =>…` | | | Returns how many of the thing `of` has here. | | `release` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, ref:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, count: number, from: string \| undefined, context:…` | | | Returns the state with `count` of the thing taken from `from`. The core never asks for more than `owned` says. | ## Reference [#reference] Type. Explained in [Checking content](https://ifloom.dev/docs/reference/checks#reference). One name a piece of content uses, such as an id, a file or a nested condition, for the content checker to resolve. The checker looks inside content that names more, such as a condition, effects, a command, blocks or a picture. The type is built from the core's kinds and each feature's (`references` in its shape), as `Condition` is. ```ts shape import type { Reference } from '@ifloom/engine/plugin' type Reference = | { effects: readonly Effect[] | undefined; } | { audio: string; } | { media: SceneMedia; } | { ui: unknown; on: UiTarget; id?: string; } | { entity: string; carrying?: string; } | { value: string; } | { storyline: string; } | { setting: string; is?: KvValue; } | { stat: string; of?: string; writes?: boolean; } | { stat: string; starts: string; } | { scene: string; as?: 'open' | 'go' | 'gate'; } | { timer: string; to?: unknown; by?: unknown; } | { blocks: readonly Block[] | undefined; } | { prose: string; } | { words: string | undefined; field: string; oldKey?: string; } | { outdated: string; } | { problem: string; } | { variants: string; } | { amount: unknown; } | { call: CallTable; name: string; with?: PluginArgs; } | { entry: string; plugin: string; list: string; noun: string; } | { reason: string | { string: string; } | undefined; } | { picture: string; } | { video: string; } | { markup: string; shownWhen?: Condition; } | { when: Condition | undefined; } | { command: CommandRef | undefined; } | { within: string; refs: readonly Reference[]; } | { kind: string; } | { speaker: string; } | { like: string; of?: string; } | { trait: string; } | { protagonist: string; } | { someone: string; } | { receiver?: string; } | { action: string; } | { input: string; } | { choice: string; } | { drawnFrom: string; } | { actionsIn: string | readonly Block[] | undefined; offers: readonly string[]; } | { minigame: string; } | { minigameKv: string; } | { jump: string; } | { channel: string; track: string | null | undefined; } | { sound: string; } | { pool: string; tags?: readonly string[]; } | { layered: PictureDef | undefined; choices: readonly string[] | null; } | { openPanel: string; with?: PluginArgs; } | { dice: unknown; key?: unknown; } ``` Uses: [`Effect`](https://ifloom.dev/docs/api/engine#effect), [`SceneMedia`](https://ifloom.dev/docs/api/engine#scenemedia), [`UiTarget`](https://ifloom.dev/docs/api/engine#uitarget), [`KvValue`](https://ifloom.dev/docs/api/engine#kvvalue), [`Block`](https://ifloom.dev/docs/api/engine#block), [`CallTable`](#calltable), [`PluginArgs`](#pluginargs), [`Condition`](https://ifloom.dev/docs/api/engine#condition), [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref), [`PictureDef`](https://ifloom.dev/docs/api/engine#picturedef). ## Refusal [#refusal] Type. Explained in [Plugin API](https://ifloom.dev/docs/reference/plugin-api#asked-and-refusal). A plugin guard's reason for refusing a command. A string refuses it as a lock does, and the button is disabled with that reason. `{ reason, soft: true }` is a warning instead. The button stays pressable and shows the warning, but the reducer still refuses the command, such as running the clock past dawn, where a UI offers bed in its place. ```ts shape import type { Refusal } from '@ifloom/engine/plugin' type Refusal = string | { reason: string; soft: true } ``` ## renderAction [#renderaction] Function. Explained in [The view](https://ifloom.dev/docs/reference/view#renderaction). Returns an action as a `RenderedChoice`, with its label, its price and the reason it's refused now, if any. A plugin calls it to offer actions outside the room, such as in a device's app. Availability comes from `whyNot`, so the button and the reducer always agree. `owner` is the id of the plugin whose action it is, so one with a cost or effects runs as `'/'` (see `Plugin.action`). Left out, the action is the game's. ```ts shape import { renderAction } from '@ifloom/engine/plugin' function renderAction(state: GameState, game: Game, action: ActionDef, owner?: string): RenderedChoice ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`ActionDef`](https://ifloom.dev/docs/api/engine#actiondef), [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice). ## RoomScene [#roomscene] Type. Explained in [A plugin's view, scene and actions](https://ifloom.dev/docs/reference/plugin-views#roomscene). The screen shown while no scene is open, from a plugin's `scene` provider. ```ts shape import type { RoomScene } from '@ifloom/engine/plugin' type RoomScene = { title: string image?: string body?: readonly Block[] id?: string ui?: Ui } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `title` | `string` | | | The room's title, such as a location's name. | | `image` | `string` | yes | | The room's picture, a path in the game's `art/` folder or a URL, such as a location's `image`. The view gives it as `view.scene.image`, which a UI shows with the room, as the React UI does above the words. | | `body` | `readonly` [`Block[]`](https://ifloom.dev/docs/api/engine#block) | yes | | The room's body, as a scene's blocks, such as prose keys, variants and conditions. | | `id` | `string` | yes | | The id the room's blocks are rendered under. The plugin's id if left out. Variants drawn here rotate per id, so a location gives its own id to keep its lines its own. | | `ui` | [`Ui`](https://ifloom.dev/docs/api/engine#ui)`<`[`SceneUi`](https://ifloom.dev/docs/api/engine#sceneui)`>` | yes | | The room's `ui` hints, carried to `view.scene.ui` as a scene's are. See `SceneUi`. | ## RulesDef [#rulesdef] Type. The game's rules `defineRules` takes. When they declare their `calls`, their conditions, effects, macros and commands must be exactly the declared ones, each given its arguments typed. ```ts fragment type RulesDef = { view?: ((state: GameState, context: PluginContext) => unknown) references?: PluginReferences traits?: readonly TraitDef[] actions?: ((state: GameState, context: PluginContext) => readonly ButtonDef[] | undefined) audio?: ((state: GameState, context: PluginContext) => Record | undefined) scene?: ((state: GameState, context: PluginContext) => RoomScene | undefined) action?: ((state: GameState, id: string, context: PluginContext) => ButtonDef | undefined) label?: ((state: GameState, context: PluginContext) => string | undefined) start?: ((game: Game) => S) values?: Record) => string | number> migrations?: Record GameState> queries?: Record) => unknown> statModifiers?: ((state: GameState, context: PluginContext) => readonly StatModifier[] | undefined) onTurn?: ((state: GameState, context: TurnContext) => GameState) onTurnDone?: ((state: GameState, context: TurnContext) => GameState) onStat?: ((before: GameState, after: GameState, stat: string, by: number, context: PluginContext) => GameState) onCommand?: ((before: GameState, after: GameState, context: PluginContext) => GameState) guard?: ((state: GameState, asked: Asked, context: PluginContext) => Refusal | undefined) price?: ((state: GameState, effects: readonly Effect[], context: PluginContext) => string[] | undefined) saveName?: ((state: GameState, context: PluginContext) => string | undefined) profile?: ((state: GameState, previous: GameState, stored: unknown, context: PluginContext) => unknown) check?: (game: Game, tools: CheckTools) => PluginProblem[] conditions?: Record) => boolean> | Implemented effects?: Record) => GameState> | Partial> commands?: Record> | { [K in keyof CallArgs]: PluginCommand[K]>; } macros?: Record> | { [K in keyof CallArgs]?: Macro[K]>; } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `view` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => unknown)` | yes | | Returns the plugin's view, which a UI reads at `view.plugins[id]`. Declare its type `V` in `ViewRegistry` under the plugin's id, and every view types `view.plugins[id]` as `V`. | | `references` | [`PluginReferences`](#pluginreferences) | yes | | The references the plugin's calls and content make, which the content checker resolves as it resolves the engine's own. See `PluginReferences`. | | `traits` | `readonly` [`TraitDef`](#traitdef)`[]` | yes | | The traits the plugin gives meaning to, each id the plugin's id, `/` and a name. A trait is data only, and the plugin's code decides what it does. Content writes them on a kind, an entity or content's `traits` table, and the plugin reads them with `traitOf` or `declaredTrait`. | | `actions` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => readonly` [`ButtonDef[]`](https://ifloom.dev/docs/api/engine#buttondef) `\| undefined)` | yes | | Returns the actions offered while no scene is open, such as a location's things to do. The view lists them before the game's own `actions`, rendered the same way. | | `audio` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => Record \|…` | yes | | Returns the tracks the plugin plays on background channels, by channel, such as a location's ambience. Null silences a channel, and the first plugin that names a channel wins it. A plugin's track is below an open scene's and an `audio` effect's, and above the game's default. A channel left out is the next plugin's, then the default's. | | `scene` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) =>` [`RoomScene`](#roomscene) `\| undefined)` | yes | | Returns the `RoomScene` the screen shows while no scene is open, such as a location's description or a dashboard's heading. The first plugin that answers fills it. With none, the room shows the game's title and its actions. | | `action` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, id: string, context:` [`PluginContext`](#plugincontext)`) =>` [`ButtonDef`](https://ifloom.dev/docs/api/engine#buttondef) `\| undefined)` | yes | | Returns one of the plugin's actions that isn't among its `actions` now, by id without the prefix, such as an app's. Undefined when there is none. `{ type: 'action', id: '/' }` runs it, as for an action with a cost or effects. Without this provider, the engine looks the id up among the plugin's `actions`. | | `label` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => string \| undefined)` | yes | | Returns a few words on the time or place in the game for a header or a save, such as "Day 3 · Wednesday morning". | | `start` | `((game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => S)` | yes | | Returns the plugin's state in a new game. A plugin with no state leaves it out. | | `values` | `Record) => string…` | yes | | The plugin's values, words and numbers content reads by name with arguments, as a condition is asked. Prose prints one as `{{id/name channel=texts}}`, and an `Amount` reads one as `{ value: 'id/name', with }`. | | `migrations` | `Record` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | yes | | The game's save migrations, keyed by the game `version` each upgrades from, so step 1 takes a version-1 save to version 2. A version with no step is carried forward unchanged. They run on the whole state when an older save loads, after the engine's and plugins' own migrations. | | `queries` | `Record) => unknown>` | yes | | The plugin's queries, answers other plugins ask for by name without importing it, such as `context.query('calendar/whenNext', { when })`. A query answers what a condition's yes or no can't, such as a location, a time or a list. | | `statModifiers` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => readonly` [`StatModifier[]`](#statmodifier) `\| undefined)` | yes | | Returns the changes to what the player's stats read now, worked out from the plugin's state, such as a timed boost. It must not read stats itself, or it reads itself. Nothing is written into the state. Every reading of the stat (conditions, derived stats, costs, the view) sees the changed value, and `stat` effects still write the kept value underneath. | | `onTurn` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`TurnContext`](#turncontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`)` | yes | | The hook run at the end of a turn, once the counter has moved on and `resets` are back. It returns the next state, and the hooks run in order, the game's first. `context.before` is the state as the turn ended, and a `turn` effect applied through `context.apply` does nothing. | | `onTurnDone` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`TurnContext`](#turncontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`)` | yes | | The hook run once every `onTurn` has run, so it sees their changes, such as the calendar's new day. It returns the next state and runs in the same order and context as `onTurn`. | | `onStat` | `((before:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, after:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, stat: string, by: number, context:` [`PluginContext`](#plugincontext)`<…` | yes | | The hook run when a `stat` effect changes one of the player's stats. `before` is the state before it, `after` the state with it, and `by` how far it moved. Return `before` to undo the change, `after` to keep it, or `after` with more changes. The hooks run in order, the game's first, each seeing what the one before returned. | | `onCommand` | `((before:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, after:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`)` | yes | | The hook run after every command that took, with the state before and the state after. It returns the next state, and its context is the state after. | | `guard` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, asked:` [`Asked`](#asked)`, context:` [`PluginContext`](#plugincontext)`) =>` [`Refusal`](#refusal) `\| undefined)` | yes | | Returns a `Refusal` for a command, given the effects it would apply, or undefined to let it through. The engine asks it after the locks, of every command but the ones that ignore locks. | | `price` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, effects: readonly` [`Effect[]`](https://ifloom.dev/docs/api/engine#effect)`, context:` [`PluginContext`](#plugincontext)`) => string[] \|…` | yes | | Returns the plugin's words for what a button costs that the engine can't say, such as `['until evening']`. The engine asks it with the effects the button would apply. | | `saveName` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, context:` [`PluginContext`](#plugincontext)`) => string \| undefined)` | yes | | Returns the name a save is listed under, such as the name the player typed. It is kept as `SaveMeta.playerName` and shown for `@you`'s lines. The first that answers names it, the game's first. With none, saves have no player name. | | `profile` | `((state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, previous:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, stored: unknown, context:` [`PluginContext`](#plugincontext)`) =>…` | yes | | Returns the value the plugin keeps in the player's profile, which outlives saves and new games, such as earned achievements. Return undefined to leave the stored value. The runner asks it after every command that took, with the state after, the state before and the value the plugin's profile namespace (its id) holds now. Only a runner with a `profile` asks, and `apply` never does. | | `check` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`, tools:` [`CheckTools`](#checktools)`) =>` [`PluginProblem[]`](#pluginproblem) | yes | | Returns the problems the plugin's own rules find that a reference can't express, such as two entries with one id or an exit to nowhere. The content checker runs it after the references. `tools` words problems with anything else the plugin names as the checker does. | | `conditions` | `Record) =>…` | yes | | The plugin's conditions content can test, by name without the prefix. | | `effects` | `Record) =>…` | yes | | The plugin's effects content can apply, by name without the prefix. Each takes the state the effects before it left and returns the next one, so two in one list compose. Prices and guards can't see what an effect does until it runs. An effect that only stands for other effects belongs in `macros` instead. | | `commands` | `Record> \| { [K in keyof` [`CallArgs`](#callargs)`]:…` | yes | | The plugin's commands a choice or action can send, by name without the prefix. | | `macros` | `Record> \| { [K in keyof` [`CallArgs`](#callargs)`]?:` [`Macro`](#macro)` { who: 'character' | 'player'; speaker?: EntityRef; name: string; image?: string } ``` Uses: [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref). ## speakerOf [#speakerof] Function. Explained in [A plugin's view, scene and actions](https://ifloom.dev/docs/reference/plugin-views#speakerof). Returns the speaker a speaker id names, with their entity's name, picture and hints. Returns null when the id names no entity in the game. The view renders a scene's `speaker` with it, and a plugin calls it for the sender of a message or a post. ```ts shape import { speakerOf } from '@ifloom/engine/plugin' function speakerOf(state: GameState, game: Game, id: string): SpeakerView | null ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`SpeakerView`](https://ifloom.dev/docs/api/engine#speakerview). ## StatModifier [#statmodifier] Type. Explained in [Plugin API](https://ifloom.dev/docs/reference/plugin-api#statmodifier). A change to what one of the player's stats reads, from a plugin's `statModifiers`. The stat reads `(value + adds) × multipliers`, held to its range, with its adds summed and its multipliers multiplied together. ```ts shape import type { StatModifier } from '@ifloom/engine/plugin' type StatModifier = { stat: string add?: number multiply?: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `stat` | `string` | | | The id of the stat the modifier changes. | | `add` | `number` | yes | | The amount added to the stat's value. 0 if left out. | | `multiply` | `number` | yes | | The factor the stat's value, with the adds, is multiplied by. 1 if left out. | ## styledBeats [#styledbeats] Function. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#styledbeats). Returns text and spoken beats with their bold, italics and UI pieces read into `spans`, and `text` with the words alone. A beat with none of these is returned unchanged. Use it for beats rendered outside a scene's view, such as a message's or a post's. Inline actions and tooltips stay in the words as written, since only the view has the choices and the prose. ```ts shape import { styledBeats } from '@ifloom/engine/plugin' function styledBeats(beats: readonly SceneBeat[]): SceneBeat[] ``` Uses: [`SceneBeat`](https://ifloom.dev/docs/api/engine#scenebeat). ## TraitDef [#traitdef] Type. Explained in [A plugin's view, scene and actions](https://ifloom.dev/docs/reference/plugin-views#traitdef). A trait a plugin declares in its `traits`, a named piece of data entities carry that the plugin gives meaning. The game declares its own in `rules.traits`, with ids that have no `/`. Name `K` to type the data as `TraitRegistry` declares it, as in `const washable: TraitDef<'laundry/washable'> = { id: 'laundry/washable', ... }`. ```ts shape import type { TraitDef } from '@ifloom/engine/plugin' type TraitDef = { id: K check?: ((data: TraitData, tools: TraitTools) => readonly string[]) references?: ((data: TraitData, tools: TraitTools) => readonly Reference[]) words?: WordShape state?: { start(data: TraitData): S } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `K` | | | The trait's id, the plugin's id, `/` and a name, such as `'laundry/washable'`. | | `check` | `((data:` [`TraitData`](https://ifloom.dev/docs/api/engine#traitdata)`, tools:` [`TraitTools`](#traittools)`) => readonly string[])` | yes | | Returns the problems with the data on one entity by the plugin's own rules, such as `['a slot needs a name']`. The content checker calls it. | | `references` | `((data:` [`TraitData`](https://ifloom.dev/docs/api/engine#traitdata)`, tools:` [`TraitTools`](#traittools)`) => readonly` [`Reference[]`](#reference)`)` | yes | | Returns the references the trait's data makes, such as a slot, a scene or a prose key, for the content checker to resolve. `tools.ref` is the entity the data is on, for a condition that names it as `'$'`. | | `words` | [`WordShape`](https://ifloom.dev/docs/api/engine#wordshape) | yes | | The fields of the data a player reads, for a translation's words table, such as `{ closed: true, body: 'blocks' }`. Each is keyed `entity..traits..`, or under the kind for a kind's default. See `WordShape`. | | `state` | `{ start(data:` [`TraitData`](https://ifloom.dev/docs/api/engine#traitdata)`): S }` | yes | | The trait's own state on each entity, such as the uses left in a torch, with `start` giving its value from the data. The save keeps it only once play writes it. Read it with `traitState` and write it with `setTraitState`. | ## TraitEntityDef [#traitentitydef] Type. Explained in [A plugin's view, scene and actions](https://ifloom.dev/docs/reference/plugin-views#traitentitydef). The definition a `TraitKind`'s `define` takes, with an entity's fields and the trait's side by side. A field both have, such as a location's `ui`, goes to the trait. ```ts shape import type { TraitEntityDef } from '@ifloom/engine/plugin' type TraitEntityDef = { of?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `of` | `string` | yes | | The entity's kind, the trait kind's `kind` if left out. | ## TraitKind [#traitkind] Type. Explained in [A plugin's view, scene and actions](https://ifloom.dev/docs/reference/plugin-views#traitkind). A kind of entity a plugin's trait makes, as `defineTraitKind` declares it, such as the places plugin's locations. It reads a bare id as an entity of its kind and gives the lookups, the definer and the checked arguments. ```ts shape import type { TraitKind } from '@ifloom/engine/plugin' type TraitKind = { readonly kind: string readonly trait: K ref: (id: string) => `${string}:${string}` id: (ref: string) => string all: (state: GameState, game: Game) => `${string}:${string}`[] get: (state: GameState, game: Game, id: string | null | undefined) => TraitData | undefined declaredAll: (game: Game) => `${string}:${string}`[] declaredGet: (game: Game, id: string | null | undefined) => TraitData | undefined define: (def: TraitEntityDef) => EntityDef entry: (id: string) => Reference arg: () => Arg args: () => Arg } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `kind` | `string` | | | The kind a bare id names. | | `trait` | `K` | | | The id of the trait that makes an entity one of these. | | `ref` | `(id: string) => '${string}:${string}'` | | | Returns the entity reference an id names. A bare id is one of the kind (`'park'` is `'location:park'`), and a reference stays as written. | | `id` | `(ref: string) => string` | | | Returns the id the plugin names an entity by, its bare id for one of the kind, else its whole reference. | | `all` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => '${string}:${string}'[]` | | | Returns every entity in the game now with the trait, those content declares in its order, then those made in play. | | `get` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`, id: string \| null \| undefined) =>` [`TraitData`](https://ifloom.dev/docs/api/engine#traitdata)` \| undefined` | | | Returns the trait of the entity an id or reference names, read through the entity it was made `like`. Undefined for an entity that isn't in the game or has no trait. | | `declaredAll` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`) => '${string}:${string}'[]` | | | Returns every entity content declares with the trait, in its order, for a check, which has no state. | | `declaredGet` | `(game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`, id: string \| null \| undefined) =>` [`TraitData`](https://ifloom.dev/docs/api/engine#traitdata)` \| undefined` | | | Returns the trait of an entity content declares, by id or reference, for a check, which has no state. | | `define` | `(def:` [`TraitEntityDef`](#traitentitydef)`) =>` [`EntityDef`](https://ifloom.dev/docs/api/engine#entitydef) | | | Returns an entity for content's `entities`, of the kind unless `of` says otherwise. The trait's fields go in `traits[trait]` and the rest stay on the entity. | | `entry` | `(id: string) =>` [`Reference`](#reference) | | | Returns the reference to an entity by id or reference, which the checker resolves to one the game has that carries the trait. | | `arg` | `() =>` [`Arg`](#arg)`` | | | Returns a call's argument naming one entity by id or reference, `'park'` or `'location:park'`, checked as `entry` is. | | `args` | `() =>` [`Arg`](#arg)`` | | | Returns a call's argument naming one entity or several, `'park'` or `['cafe', 'park']`, which the implementation gets as a list. | ## TraitKindSpec [#traitkindspec] Type. Explained in [A plugin's view, scene and actions](https://ifloom.dev/docs/reference/plugin-views#traitkindspec). Settings for `defineTraitKind`. ```ts shape import type { TraitKindSpec } from '@ifloom/engine/plugin' type TraitKindSpec = { kind: string trait: K fields: { readonly [F in keyof Required>]: true } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `kind` | `string` | | | The kind a bare id names, such as `'location'`, so `'park'` is `'location:park'`. | | `trait` | `K` | | | The id of the trait that makes an entity one of these, such as `'places/location'`. | | `fields` | `{ readonly [F in keyof Required<`[`TraitData`](https://ifloom.dev/docs/api/engine#traitdata)`>]: true }` | | | The trait's fields, as `{ exits: true, body: true, … }`, which `define` puts in the trait rather than on the entity. The type requires every field, so a field added to the trait can't be left out. | ## traitState [#traitstate] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#traitstate). Returns the state one entity keeps for one of its traits, the value play last wrote or else the trait's `state.start`. It returns undefined when the entity isn't in the game, lacks the trait, or the trait keeps no state. ```ts shape import { traitState } from '@ifloom/engine/plugin' function traitState(state: GameState, game: Game, ref: string, id: string): S | undefined ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game). ## TraitTools [#traittools] Type. Explained in [A plugin's view, scene and actions](https://ifloom.dev/docs/reference/plugin-views#traittools). The tools a trait's `check` and `references` get beside the data. ```ts shape import type { TraitTools } from '@ifloom/engine/plugin' type TraitTools = { game: Game ref: EntityRef } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `game` | [`Game`](https://ifloom.dev/docs/api/engine#game) | | | The loaded game. | | `ref` | [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | | | The entity the data is on. | ## TurnContext [#turncontext] Type. Explained in [Rules and hooks](https://ifloom.dev/docs/reference/rules#turncontext). The context `onTurn` and `onTurnDone` get, the game's and every plugin's, with `before` added. Its `apply` ends no turn, so a `turn` effect applied through it does nothing. ```ts shape import type { TurnContext } from '@ifloom/engine/plugin' type TurnContext = { game: Game query: Query value: (name: string, args?: PluginArgs) => string | number | undefined roll: (max: number, name: string) => number slice: S get: (on?: GameState | undefined) => S set: (next: S, on?: GameState | undefined) => GameState apply: (effects: readonly EffectRef[], on?: GameState) => GameState picks?: Record beats: (blocks: readonly Block[], id: string) => SceneBeat[] profile?: unknown before: GameState } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `game` | [`Game`](https://ifloom.dev/docs/api/engine#game) | | | The context's loaded game. | | `query` | [`Query`](https://ifloom.dev/docs/api/engine#query) | | | The context's query function, which asks a plugin or the game by full name (`query('loyalty/stampsLeft')`). | | `value` | `(name: string, args?:` [`PluginArgs`](#pluginargs)`) => string \| number \| undefined` | | | The context's value function, which returns a value by full name, a plugin's (`messages/unread`) or the game's, asked with `args`. It returns undefined when no plugin or game has that value. | | `roll` | `(max: number, name: string) => number` | | | The context's roll function, which returns a whole number from 0 to `max - 1`, drawn from the save's seed, the turn and `name`. The same save and turn always draw the same number. | | `slice` | `S` | | | The plugin's state in the game state the function was given, the same as `get()`. | | `get` | `(on?:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) `\| undefined) => S` | | | Returns the plugin's state in the game state the function was given, or in `on`. Its starting state (`start`) when the save has none yet. Pass `on` from a function that has already changed the game state, such as by applying effects, to read the plugin's state as it is now. It is the read that matches `set`. | | `set` | `(next: S, on?:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) `\| undefined) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | | | Returns the game state with the plugin's state replaced, on the state the function was given or on `on`. Pass `on` from a function that has already changed other parts of the game state. | | `apply` | `(effects: readonly` [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref)`, on?:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`) =>` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | | | Returns the state after a list of effects, applied to the state the function was given or to `on`. Any effect works, a custom one or another plugin's included. A plugin's effect ends a turn with `apply([{ turn: true }])`. | | `picks` | `Record` | yes | | The record of the pool picks a `view` makes, for the reducer to keep. It is set only in `view`. Pass it to `pictureView` so a picture's pick stays the same on every visit. `beats` records its own. | | `beats` | `(blocks: readonly` [`Block[]`](https://ifloom.dev/docs/api/engine#block)`, id: string) =>` [`SceneBeat[]`](https://ifloom.dev/docs/api/engine#scenebeat) | | | Returns blocks rendered as beats, the way a scene's body is, for a message's words, a post's or an app's. Only the blocks whose `when` holds are rendered. Words are filled in for this save, variants and pools drawn under `id` so a block's pick stays the same on every visit, spoken lines given their speakers, and bold, italics and UI pieces made spans. Inline actions and tooltips stay as plain words, since only a scene offers choices. In `view`, the reducer records the pool picks it makes. | | `profile` | `unknown` | yes | | The value the plugin's own profile namespace (its id) held when the runner last read or wrote it. It is set only in `view`, when a runner with a profile builds the view. It is frozen, so read it and never change it. It is undefined in a view built by `view(state, game)` alone and while nothing is stored. Conditions, effects, commands and hooks never see it, so a replay always plays the same. | | `before` | [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | | | The state as the turn ended, before the counter moved on and `resets` were put back. | ## WrittenAs [#writtenas] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#writtenas). The value content writes for a call of an `ArgShape`. It is the arguments, `true` or `{}` for a call with none, and either for a call whose arguments may all be left out. ```ts fragment type WrittenAs = [keyof S] extends [never] ? true | Record : [RequiredKeys] extends [never] ? true | { [K in keyof ({ [K in RequiredKeys]: ArgIn; } & { [K in OptionalKeys]?: ArgIn; })]: ({ [K in RequiredKeys]: ArgIn; } & { [K in OptionalKeys]?: ArgIn; })[K]; } : { [K in keyof ({ [K in RequiredKeys]: ArgIn; } & { [K in OptionalKeys]?: ArgIn; })]: ({ [K in RequiredKeys]: ArgIn; } & { [K in OptionalKeys]?: ArgIn; })[K]; } ``` Uses: [`ArgIn`](#argin). # @ifloom/engine/testing (https://ifloom.dev/docs/api/engine-testing) Generated from the source of `@ifloom/engine/testing` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. - Functions: [`boundaryProblems`](#boundaryproblems), [`exportedNames`](#exportednames), [`freshState`](#freshstate), [`loadChecked`](#loadchecked), [`partnerCases`](#partnercases), [`play`](#play), [`undocumentedExports`](#undocumentedexports) - Types: [`PartnerCase`](#partnercase) ## boundaryProblems [#boundaryproblems] Function. Explained in [Testing helpers](https://ifloom.dev/docs/reference/testing#boundaryproblems). Returns one line for each break of the plugin rules in a plugin package's source, or none. Give each file's text by its path, any path with `src/` in it, such as a glob's keys. - The main entry, everything in `src/` but `src/react/`, imports only `@ifloom/engine`, `@ifloom/engine/plugin` and its own files beside it, never its React UI. - It uses no browser global (`window.`, `document.`) outside strings and comments. - `src/react/`, the `/react` subpath, imports only the engine's main entry, `react`, `react-dom`, `@ifloom/react` and `@ifloom/react/kit`, its own files and `../index.ts`. ```ts shape import { boundaryProblems } from '@ifloom/engine/testing' function boundaryProblems(sources: Readonly>): string[] ``` ## exportedNames [#exportednames] Function. Explained in [Testing helpers](https://ifloom.dev/docs/reference/testing#exportednames). Returns the names a source exports, sorted, from its `export function`, `const`, `type` and the rest, and each export list. ```ts shape import { exportedNames } from '@ifloom/engine/testing' function exportedNames(source: string): string[] ``` ## freshState [#freshstate] Function. Explained in [Testing helpers](https://ifloom.dev/docs/reference/testing#freshstate). Returns a new game's state from `startingState` with no scene open, so the room shows a plugin's actions and panels. ```ts shape import { freshState } from '@ifloom/engine/testing' function freshState(game: Game, options?: StartOptions): GameState ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`StartOptions`](https://ifloom.dev/docs/api/engine#startoptions), [`GameState`](https://ifloom.dev/docs/api/engine#gamestate). ## loadChecked [#loadchecked] Function. Explained in [Testing helpers](https://ifloom.dev/docs/reference/testing#loadchecked). Returns the game `loadGame` builds, for a test. It throws an `Error` listing every problem the content checker finds. ```ts shape import { loadChecked } from '@ifloom/engine/testing' function loadChecked(content: readonly Content[], base: GameBase, options?: LoadOptions): Game ``` Uses: [`Content`](https://ifloom.dev/docs/api/engine#content), [`GameBase`](https://ifloom.dev/docs/api/engine#gamebase), [`LoadOptions`](https://ifloom.dev/docs/api/engine#loadoptions), [`Game`](https://ifloom.dev/docs/api/engine#game). ## PartnerCase [#partnercase] Type. Explained in [Testing helpers](https://ifloom.dev/docs/reference/testing#partnercase). One way to load a plugin for a test, alone or with one of the plugins it cooperates with. ```ts shape import type { PartnerCase } from '@ifloom/engine/testing' type PartnerCase = { name: string partner: string | null plugins: Plugin[] has: (id: string) => boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | | | The case's name for a test, `alone` or `with `. | | `partner` | `string \| null` | | | The partner's id, or `null` for the plugin alone. | | `plugins` | [`Plugin[]`](https://ifloom.dev/docs/api/engine-plugin#plugin) | | | The plugins to load, the partner first if there is one, then the plugin under test. | | `has` | `(id: string) => boolean` | | | Returns true when the case loads the plugin `id`, the plugin under test or the partner. | ## partnerCases [#partnercases] Function. Explained in [Testing helpers](https://ifloom.dev/docs/reference/testing#partnercases). Returns the `PartnerCase`s of a plugin, alone and then with each partner in turn, for a test to run in each. It throws for a partner missing from `cooperates` or listed twice. ```ts shape import { partnerCases } from '@ifloom/engine/testing' function partnerCases(plugin: Plugin, partners: readonly Plugin[]): PartnerCase[] ``` Uses: [`Plugin`](https://ifloom.dev/docs/api/engine-plugin#plugin), [`PartnerCase`](#partnercase). ## play [#play] Function. Explained in [Testing helpers](https://ifloom.dev/docs/reference/testing#play). Returns the state after each command in turn. It throws on the first command refused, naming it and the reason. ```ts shape import { play } from '@ifloom/engine/testing' function play(state: GameState, game: Game, ...commands: readonly CommandRef[]): GameState ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref). ## undocumentedExports [#undocumentedexports] Function. Explained in [Testing helpers](https://ifloom.dev/docs/reference/testing#undocumentedexports). Returns the names the entries' sources export that a docs page never mentions as a word, sorted. ```ts shape import { undocumentedExports } from '@ifloom/engine/testing' function undocumentedExports(sources: readonly string[], page: string): string[] ``` # @ifloom/engine (https://ifloom.dev/docs/api/engine) Generated from the source of `@ifloom/engine` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. - Functions: [`actionOf`](#actionof), [`amountOf`](#amountof), [`apply`](#apply), [`applyEffects`](#applyeffects), [`artSrc`](#artsrc), [`audioSrc`](#audiosrc), [`buildEffects`](#buildeffects), [`callOf`](#callof), [`cases`](#cases), [`chance`](#chance), [`checkGame`](#checkgame), [`choice`](#choice-1), [`clampStat`](#clampstat), [`commandOf`](#commandof), [`createRunner`](#createrunner), [`creditsOf`](#creditsof), [`decide`](#decide), [`declaredTrait`](#declaredtrait), [`declaredWithTrait`](#declaredwithtrait), [`describeProblem`](#describeproblem), [`dismiss`](#dismiss), [`draw`](#draw), [`drawOne`](#drawone), [`effectsOf`](#effectsof), [`entitiesOf`](#entitiesof), [`entityDescription`](#entitydescription), [`entityImage`](#entityimage), [`entityKv`](#entitykv), [`entityName`](#entityname), [`entityOf`](#entityof), [`entityTags`](#entitytags), [`explain`](#explain), [`explainText`](#explaintext), [`fillTokens`](#filltokens), [`fold`](#fold), [`hash`](#hash), [`holds`](#holds), [`image`](#image), [`inlineChoices`](#inlinechoices), [`inlineMarkup`](#inlinemarkup), [`inRange`](#inrange), [`isUnique`](#isunique), [`jump`](#jump), [`lackingLine`](#lackingline), [`loadGame`](#loadgame), [`loadState`](#loadstate), [`mediaType`](#mediatype), [`memoryDriver`](#memorydriver), [`minigame`](#minigame), [`mods`](#mods-1), [`need`](#need), [`notify`](#notify), [`ownedCount`](#ownedcount), [`panel`](#panel), [`parseRef`](#parseref), [`pluginQuery`](#pluginquery), [`point`](#point), [`profile`](#profile-1), [`proseBeats`](#prosebeats), [`protagonist`](#protagonist), [`reasonOf`](#reasonof), [`receiversOf`](#receiversof), [`receiveThing`](#receivething), [`releaseThing`](#releasething), [`replay`](#replay), [`resolveYou`](#resolveyou), [`saves`](#saves-1), [`say`](#say), [`sceneOf`](#sceneof), [`screen`](#screen-1), [`startingState`](#startingstate), [`statLevel`](#statlevel), [`statOf`](#statof), [`statValue`](#statvalue), [`storylineOpen`](#storylineopen), [`stringOf`](#stringof), [`text`](#text), [`traitOf`](#traitof), [`translatableFields`](#translatablefields), [`uiInContent`](#uiincontent-1), [`upgradePack`](#upgradepack), [`view`](#view-1), [`weighted`](#weighted), [`when`](#when), [`whyNot`](#whynot), [`withTrait`](#withtrait), [`writeEntity`](#writeentity) - Constants: [`PLAYER`](#player), [`SAVE_VERSION`](#save_version), [`SCHEMA`](#schema), [`STRINGS`](#strings), [`YOU`](#you) - Types: [`ActionCost`](#actioncost), [`ActionDef`](#actiondef), [`Amount`](#amount), [`Applied`](#applied), [`AudioChannelView`](#audiochannelview), [`AudioCue`](#audiocue), [`AudioState`](#audiostate), [`AudioView`](#audioview), [`AutosaveOptions`](#autosaveoptions), [`BacklogEntry`](#backlogentry), [`BacklogOptions`](#backlogoptions), [`BeatSize`](#beatsize), [`Block`](#block), [`Blocked`](#blocked), [`BlockExtras`](#blockextras), [`BlockUi`](#blockui), [`BrokenSave`](#brokensave), [`ButtonDef`](#buttondef), [`CarryOver`](#carryover), [`Change`](#change), [`ChangesDef`](#changesdef), [`ChangeView`](#changeview), [`ChannelDef`](#channeldef), [`Checked`](#checked), [`Choice`](#choice), [`ChoiceUi`](#choiceui), [`Command`](#command), [`CommandCall`](#commandcall), [`CommandLog`](#commandlog), [`CommandRef`](#commandref), [`CommandRegistry`](#commandregistry), [`Condition`](#condition), [`ConditionCall`](#conditioncall), [`ConditionRegistry`](#conditionregistry), [`Content`](#content), [`CreatedEntity`](#createdentity), [`CreateFields`](#createfields), [`Credit`](#credit), [`CreditGroup`](#creditgroup), [`CustomContext`](#customcontext), [`DataScene`](#datascene), [`Dice`](#dice), [`Effect`](#effect), [`EffectCall`](#effectcall), [`EffectRef`](#effectref), [`EffectRegistry`](#effectregistry), [`EntitiesView`](#entitiesview), [`EntityDef`](#entitydef), [`EntityRef`](#entityref), [`EntityState`](#entitystate), [`EntityUi`](#entityui), [`EntityView`](#entityview), [`Explanation`](#explanation), [`FileRef`](#fileref), [`FillPart`](#fillpart), [`FlowChoice`](#flowchoice), [`FlowState`](#flowstate), [`FlowStep`](#flowstep), [`Formula`](#formula), [`Game`](#game), [`GameAudio`](#gameaudio), [`GameBase`](#gamebase), [`GameMedia`](#gamemedia), [`GameRules`](#gamerules), [`GameState`](#gamestate), [`GameUi`](#gameui), [`HelperRegistry`](#helperregistry), [`HelpersIn`](#helpersin), [`HistoryOptions`](#historyoptions), [`HotspotDef`](#hotspotdef), [`HotspotView`](#hotspotview), [`InlinePart`](#inlinepart), [`InlineSpan`](#inlinespan), [`InlineUi`](#inlineui), [`InlineUiArgs`](#inlineuiargs), [`InputDef`](#inputdef), [`InputView`](#inputview), [`InstalledMod`](#installedmod), [`KindDef`](#kinddef), [`KvValue`](#kvvalue), [`Loaded`](#loaded), [`LoadedSave`](#loadedsave), [`LoadOptions`](#loadoptions), [`MediaState`](#mediastate), [`MigrationTools`](#migrationtools), [`MinigameDef`](#minigamedef), [`MinigameInput`](#minigameinput), [`MinigameSceneFields`](#minigamescenefields), [`MinigameState`](#minigamestate), [`MinigameStateDef`](#minigamestatedef), [`MinigameTarget`](#minigametarget), [`MinigameTransition`](#minigametransition), [`MinigameView`](#minigameview), [`ModFile`](#modfile), [`Mods`](#mods), [`Notice`](#notice), [`NoticesView`](#noticesview), [`NoticeView`](#noticeview), [`Once`](#once), [`OpenPanel`](#openpanel), [`Pack`](#pack), [`Patch`](#patch), [`Phrase`](#phrase), [`PhraseRow`](#phraserow), [`Phrases`](#phrases), [`PhraseWithArgs`](#phrasewithargs), [`PictureDef`](#picturedef), [`PictureLayer`](#picturelayer), [`PictureLayerView`](#picturelayerview), [`PictureView`](#pictureview), [`Played`](#played), [`PlaylistDef`](#playlistdef), [`PluginCall`](#plugincall), [`PoolFile`](#poolfile), [`Price`](#price), [`Probe`](#probe), [`Problem`](#problem), [`Profile`](#profile), [`ProseStore`](#prosestore), [`Query`](#query), [`QueryRegistry`](#queryregistry), [`Range`](#range), [`RawPack`](#rawpack), [`Reason`](#reason), [`RenderedChoice`](#renderedchoice), [`Result`](#result), [`Roll`](#roll), [`RollsState`](#rollsstate), [`Runner`](#runner), [`RunnerOptions`](#runneroptions), [`RunnerSnapshot`](#runnersnapshot), [`RunningTimer`](#runningtimer), [`SaveDriver`](#savedriver), [`SaveExtra`](#saveextra), [`SaveFile`](#savefile), [`SaveListing`](#savelisting), [`SaveMeta`](#savemeta), [`Saves`](#saves), [`SavingView`](#savingview), [`SceneBeat`](#scenebeat), [`SceneMedia`](#scenemedia), [`ScenePanel`](#scenepanel), [`SceneUi`](#sceneui), [`Screen`](#screen), [`ScreenChoice`](#screenchoice), [`ScreenScene`](#screenscene), [`Select`](#select), [`SettingDef`](#settingdef), [`SettingView`](#settingview), [`Someone`](#someone), [`SpeakerView`](#speakerview), [`StartOptions`](#startoptions), [`StatDef`](#statdef), [`StatKey`](#statkey), [`StatLevels`](#statlevels), [`StatRound`](#statround), [`Stats`](#stats), [`StatUi`](#statui), [`StatView`](#statview), [`StatWords`](#statwords), [`StoryletFields`](#storyletfields), [`StorylineDef`](#storylinedef), [`StorylineState`](#storylinestate), [`StringKey`](#stringkey), [`Strings`](#strings-1), [`TextLine`](#textline), [`TimerDef`](#timerdef), [`TimerView`](#timerview), [`Times`](#times), [`TrackDef`](#trackdef), [`TraitData`](#traitdata), [`TraitRegistry`](#traitregistry), [`TraitSource`](#traitsource), [`TraitTable`](#traittable), [`TriggerDef`](#triggerdef), [`Ui`](#ui), [`UiField`](#uifield), [`UiInContent`](#uiincontent), [`UiTarget`](#uitarget), [`ValueRef`](#valueref), [`VariantMember`](#variantmember), [`VideoFlags`](#videoflags), [`VideoView`](#videoview), [`View`](#view), [`ViewOptions`](#viewoptions), [`ViewRegistry`](#viewregistry), [`ViewsIn`](#viewsin), [`WordField`](#wordfield), [`WordPart`](#wordpart), [`WordShape`](#wordshape) ## ActionCost [#actioncost] Type. Explained in [Actions](https://ifloom.dev/docs/reference/actions#actioncost). A cost a choice or an action declares in its `cost`, the stats it spends. The engine refuses it while the player has too little of one. ```ts shape import type { ActionCost } from '@ifloom/engine' type ActionCost = { stats?: Record reasons?: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `stats` | `Record` | yes | | The stats the cost spends, by id, in the order the button lists them. | | `reasons` | `Record` | yes | | The refusal lines by stat id, used in place of the stat's own line when the player has too little. | ## ActionDef [#actiondef] Type. Explained in [Actions](https://ifloom.dev/docs/reference/actions#actiondef). An action the game declares in `actions`, or one a plugin offers (a location's, an app's). It has the fields of a `ButtonDef`, the same as a choice. Taking one with only a `command` sends that command. One with a cost, effects or `once` sends `{ type: 'action', id }`, which runs its command, pays its cost and applies its effects. The id is the game's own, or `'/'` for a plugin's. An action with no `label` is never rendered as a button, so only a choice's command, another action or a hotspot runs it. ```ts shape import type { ActionDef } from '@ifloom/engine' type ActionDef = { id: string label?: string labels?: { when?: Condition; label: string }[] when?: Condition blocked?: Blocked[] cost?: ActionCost effects?: EffectRef[] command?: CommandRef once?: Once tags?: string[] irreversible?: string ui?: Ui } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The choice's or action's id, unique among its scene's choices or among the actions. | | `label` | `string` | yes | | The button's words, with tokens filled, such as `'Order a tea'`. A choice with no label shows its id, and an action with none is never rendered as a button. | | `labels` | `{ when?:` [`Condition`](#condition)`; label: string }[]` | yes | | The button's words that depend on the state, such as "Not today" before you have bought it and "Right." after. The first entry whose `when` holds wins, and `label` is the fallback. | | `when` | [`Condition`](#condition) | yes | | The condition under which the choice or action is offered and can be taken. Always, if left out. | | `blocked` | [`Blocked[]`](#blocked) | yes | | The rules that refuse it for now. The first entry whose `when` holds greys the button out with its reason, or leaves it off with `hide`. | | `cost` | [`ActionCost`](#actioncost) | yes | | The stats it spends. The engine checks them before it runs, lists them on the button and pays them after its command. | | `effects` | [`EffectRef[]`](#effectref) | yes | | The effects it applies after its cost, in order. A plugin's or the game's effect in the short form does computed work. | | `command` | [`CommandRef`](#commandref) | yes | | The command the choice or action sends first, a plugin's in the short form or one of the engine's, but never `choose`. The button is refused with that command's reason while the command would be. An example is `{ 'devices/open': { id: 'messages' } }`. The button's price includes what the command spends. | | `once` | [`Once`](#once) | yes | | The limit of once a game (`{ per: 'game' }`) or once a turn (`{ per: 'turn' }`), counted in `state.chosen`. Once spent, a choice stays on screen and pays nothing more, and an action is refused, both with `reason`. | | `tags` | `string[]` | yes | | The tags a UI can style or filter it by. The engine gives them no meaning. | | `irreversible` | `string` | yes | | The warning that it can't be undone, which a UI shows on the button. | | `ui` | [`Ui`](#ui)`<`[`ChoiceUi`](#choiceui)`>` | yes | | The ui hints carried to its button in the view. See `ChoiceUi`. | ## actionOf [#actionof] Function. Explained in [Actions](https://ifloom.dev/docs/reference/actions#actionof). Returns the action that `{ type: 'action', id }` runs in this state. Returns undefined when there is none. A plain id names one of the game's `actions`. An id of the form `'/'` names a plugin's action, from its `action` provider, else from the actions it offers now. ```ts shape import { actionOf, type Game } from '@ifloom/engine' function actionOf(state: GameState, game: Game, id: string): ActionDef | undefined ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`ActionDef`](#actiondef). ## Amount [#amount] Type. Explained in [Amounts](https://ifloom.dev/docs/reference/amounts#amount). A number content names that the engine works out when it reads it. Read one with `amountOf`. An amount is a number, a stat of the player's by id, a stat with `{ stat, of? }`, a kv key's number with `{ kv, of? }` (a value that is not a number counts as 0), a value by name with `{ value, with? }`, or a count of entities with `{ count, where? }`, counted as the `count` condition counts. Amounts combine as a `Formula` does (`sum`, `product`, `min`, `max`, `scale`, `clamp`), with any amount as a part, and `of` names the owner as it does in conditions. Effects take one in `by` and `to`, ranges in their bounds, stats in `min` and `max`, and rolls in `plus` and `against`. So `{ stat: 'coins', gte: { stat: 'rent' } }` holds while the player has at least the rent. ```ts shape import type { Amount } from '@ifloom/engine' type Amount = number | StatKey | { stat: StatKey; of?: string } | { kv: string; of?: string } | ValueRef | { count: string | Select; where?: Condition } | { sum: Amount[] } | { product: Amount[] } | { min: Amount[] } | { max: Amount[] } | { scale: Amount; by: number } | { clamp: Amount; min?: number; max?: number } ``` Uses: [`StatKey`](#statkey), [`ValueRef`](#valueref), [`Select`](#select), [`Condition`](#condition). ## amountOf [#amountof] Function. Explained in [Amounts](https://ifloom.dev/docs/reference/amounts#amountof). Returns an amount worked out in this state. An amount that doesn't read as a finite number gives 0, and so does an owner that isn't there. An amount is a number, a stat (the player's by id, or `{ stat, of }`), a kv key's number (`{ kv, of }`), a value by name (`{ value, with }`), a count of entities (`{ count }`) or a formula of these. ```ts shape import { amountOf, type Game } from '@ifloom/engine' function amountOf(state: GameState, game: Game, amount: Amount): number ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`Amount`](#amount). ## Applied [#applied] Type. Explained in [Commands](https://ifloom.dev/docs/reference/commands#applied). The answer `apply` gives for a command, a `Result` with the state on both sides. When `ok` is false, the command was refused, `state` is unchanged and `reason` says why. `newGame` is true when the command was a `newGame` and `state` is the new game's first state. ```ts shape import type { Applied } from '@ifloom/engine' type Applied = { ok: true; state: GameState; reason?: never; newGame?: true } | { ok: false; state: GameState; reason: string } ``` Uses: [`GameState`](#gamestate). ## apply [#apply] Function. Explained in [Commands](https://ifloom.dev/docs/reference/commands#apply). Runs a command and returns the next state. A refused command returns the state unchanged, with the reason. A null state, or a `start` command, returns the game's starting state. ```ts shape import { apply, type Game } from '@ifloom/engine' function apply(state: GameState | null, game: Game, ref: CommandRef): Applied ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`CommandRef`](#commandref), [`Applied`](#applied). ## applyEffects [#applyeffects] Function. Explained in [Effects](https://ifloom.dev/docs/reference/effects#applyeffects). Returns the state after a list of effects, the engine's and plugins' short calls alike (`{ 'quests/start': { quest: 'bread' } }`). A call to an effect no plugin declares is skipped. A plugin's `context.apply` runs effects the same way. ```ts shape import { applyEffects, type Game } from '@ifloom/engine' function applyEffects(state: GameState, game: Game, effects: readonly EffectRef[]): GameState ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`EffectRef`](#effectref). ## artSrc [#artsrc] Function. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#artsrc). Returns a picture's or video's path in the game's `art/` folder, relative to the page. A URL (`https:`, `data:`, `//host/…`) is returned unchanged. `'photo/ava.svg'` and `'art/photo/ava.svg'` both give `'art/photo/ava.svg'`. A name with no extension gets `.jpg`, or `.mp4` when `type` is `'video'`. ```ts shape import { artSrc } from '@ifloom/engine' function artSrc(path: string, type?: 'image' | 'video'): string ``` ## AudioChannelView [#audiochannelview] Type. Explained in [Audio](https://ifloom.dev/docs/reference/audio#audiochannelview). An audio channel as the audio player needs it, in `view.audio.channels`. ```ts shape import type { AudioChannelView } from '@ifloom/engine' type AudioChannelView = { mode: 'background' | 'cue' track: string | null src: string | null loop: boolean volume: number volumeSetting: string | null crossfade: number duck: { under: string[]; to: number } | null playlist?: { tracks: string[]; srcs: string[]; volumes: number[]; order: 'inOrder' | 'loop' | 'shuffle' } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `mode` | `'background' \| 'cue'` | | | The channel's mode. `background` plays a track or playlist until it changes, and `cue` plays one-shot sounds, listed in `cues`. | | `track` | `string \| null` | | | The id of the track or playlist playing. Null for silence, and always null on a cue channel. | | `src` | `string \| null` | | | The file to play, through `audioSrc`, a playlist's first. Null for silence. | | `loop` | `boolean` | | | The channel's loop mark, true when the track repeats. A playlist repeats as a whole unless its order is `'inOrder'`. | | `volume` | `number` | | | The track's own volume, from 0 to 1, or a playlist's first track's. The player multiplies it by the volume setting's value. | | `volumeSetting` | `string \| null` | | | The id of the ui setting that sets the channel's volume. Null when there's none. | | `crossfade` | `number` | | | The milliseconds to fade between tracks. 0 on a cue channel. | | `duck` | `{ under: string[]; to: number } \| null` | | | The channel's ducking, quietening it to `to` (0 to 1) while any channel in `under` plays. Null when it doesn't duck. | | `playlist` | `{ tracks: string[]; srcs: string[]; volumes: number[]; order: 'inOrder' \| 'loop' \| '…` | yes | | The playlist's tracks, files, volumes and order, already shuffled when it shuffles. Left out for a single track. | ## AudioCue [#audiocue] Type. Explained in [Audio](https://ifloom.dev/docs/reference/audio#audiocue). A one-shot sound that is due, in `view.audio.cues`. The audio player plays each key once. ```ts shape import type { AudioCue } from '@ifloom/engine' type AudioCue = { key: string channel: string track: string src: string volume: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `key` | `string` | | | The cue's key, the same for the same sound in the same visit across view calls and reloads. | | `channel` | `string` | | | The cue channel the sound plays on, `sfx` or `voice` unless the game declares others. | | `track` | `string` | | | The track's id in `audio.tracks`. | | `src` | `string` | | | The file to play, through `audioSrc`. | | `volume` | `number` | | | The track's own volume, from 0 to 1. The player multiplies it by the channel's volume setting. | ## audioSrc [#audiosrc] Function. Explained in [Audio](https://ifloom.dev/docs/reference/audio#audiosrc). Returns a sound file's path relative to the page, under `audio/`. A bare name gets `.ogg`. Like `artSrc`, the path is relative and never starts with `/`. ```ts shape import { audioSrc } from '@ifloom/engine' function audioSrc(path: string): string ``` ## AudioState [#audiostate] Type. Explained in [Audio](https://ifloom.dev/docs/reference/audio#audiostate). The audio a save keeps, in `state.audio`. The engine reads the tracks and channels from content. ```ts shape import type { AudioState } from '@ifloom/engine' type AudioState = { channels: Record cues: { seq: number; track: string }[] seq: number shown: number started: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `channels` | `Record` | | | The tracks `audio` effects have put on background channels, by channel. Null is silence, and a channel missing here is left to the scene, the plugins and the defaults. | | `cues` | `{ seq: number; track: string }[]` | | | The last 20 `sound` effects, oldest first, each with its number in the running count. | | `seq` | `number` | | | The number of `sound` effects there have been. | | `shown` | `number` | | | The number of times a scene has been entered, all scenes together. Each visit's sounds get keys of their own from it. | | `started` | `Record` | | | The track each background channel is playing and the turn it started, for a shuffled playlist's draw. | ## AudioView [#audioview] Type. Explained in [Audio](https://ifloom.dev/docs/reference/audio#audioview). The audio as the audio player needs it, in `view.audio`. It's empty when the game has no audio. ```ts shape import type { AudioView } from '@ifloom/engine' type AudioView = { channels: Record cues: AudioCue[] muteSetting: string | null soundSetting: string | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `channels` | `Record` | | | Every channel with its track resolved, from the open scene, then an effect, then a plugin, then the game's default. | | `cues` | [`AudioCue[]`](#audiocue) | | | The sounds that are due, from `sound` effects and the open scene's sound and voice beats, in order. | | `muteSetting` | `string \| null` | | | The id of the ui setting that mutes everything while it's on. Null when there's none. | | `soundSetting` | `string \| null` | | | The id of the ui setting that mutes everything while it's off. Null when there's none. | ## AutosaveOptions [#autosaveoptions] Type. Explained in [The runner](https://ifloom.dev/docs/reference/runner#autosaveoptions). Settings for autosave, when the runner saves on its own. Autosave is off unless `createRunner` is given these. ```ts shape import type { AutosaveOptions } from '@ifloom/engine' type AutosaveOptions = { slot?: string every: 'command' | 'scene' | 'turn' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `slot` | `string` | yes | | The slot autosave writes to. `'auto'` if left out. | | `every` | `'command' \| 'scene' \| 'turn'` | | | The moment autosave writes, after every command or only when the scene or the turn changes. It skips a save while the game's `saveable` refuses saving. | ## BacklogEntry [#backlogentry] Type. Explained in [The runner](https://ifloom.dev/docs/reference/runner#backlogentry). One scene of the backlog, as the player saw it. The backlog keeps scenes only, never the room or a minigame. ```ts shape import type { BacklogEntry } from '@ifloom/engine' type BacklogEntry = { turn: number when: string | null sceneId: string title: string beats: SceneBeat[] chose?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `turn` | `number` | | | The turn the scene was shown in. | | `when` | `string \| null` | | | The time in the game when the scene was shown, from `view.when`, or null when no plugin gives one. | | `sceneId` | `string` | | | The scene's id. | | `title` | `string` | | | The scene's title as it was shown. | | `beats` | [`SceneBeat[]`](#scenebeat) | | | The scene's beats as the player read them. | | `chose` | `string` | yes | | The label of the choice the player made in the scene, once they made one. A choice at a decision of a flow shows in `beats` instead. | ## BacklogOptions [#backlogoptions] Type. Explained in [The runner](https://ifloom.dev/docs/reference/runner#backlogoptions). Settings for the backlog, the list of scenes the player has seen with the choice made in each. The backlog is off unless `createRunner` is given these or `true`. ```ts shape import type { BacklogOptions } from '@ifloom/engine' type BacklogOptions = { limit?: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `limit` | `number` | yes | | The number of entries the backlog keeps, dropping the oldest. 200 if left out. | ## BeatSize [#beatsize] Type. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#beatsize). The width of an `image` or `video` beat, `inline` in the column with the words or `wide` across it. ```ts shape import type { BeatSize } from '@ifloom/engine' type BeatSize = 'inline' | 'wide' ``` ## Block [#block] Type. Explained in [Scenes](https://ifloom.dev/docs/reference/scenes#block). One entry of a scene's body, told apart by its key, such as `{ text }`, `{ say }` or `{ decide }`. A block with a `when` is left out while it fails. The body is composed from blocks rather than read whole from one prose key. So a conditional line is one more block, and each block's words mean one thing. ```ts shape import type { Block } from '@ifloom/engine' type Block = ({ text: string; id?: string; when?: Condition } | { prose: string; when?: Condition } | { variants: string; when?: Condition; gate?: Record; image?: Record } | { media: SceneMedia; when?: Condition } | { say: string; speaker: string; voice?: string; id?: string; when?: Condition } | { blocks: Block[]; when?: Condition } | { cases: Block[]; when?: Condition } | { decide: string; choices: FlowChoice[]; when?: Condition } | { point: string; when?: undefined } | { minigame: string; when?: Condition } | { panel: string; with?: PluginArgs; when?: Condition }) & { ui?: Ui } ``` Uses: [`Condition`](#condition), [`SceneMedia`](#scenemedia), [`FlowChoice`](#flowchoice), [`PluginArgs`](https://ifloom.dev/docs/api/engine-plugin#pluginargs), [`Ui`](#ui), [`BlockUi`](#blockui). ## Blocked [#blocked] Type. Explained in [Actions](https://ifloom.dev/docs/reference/actions#blocked). A rule that refuses a choice, an action, a location or an app while its `when` holds. The first entry of a `blocked` list whose `when` holds gives the `reason` the button shows. ```ts shape import type { Blocked } from '@ifloom/engine' type Blocked = { when: Condition reason: Reason hide?: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `when` | [`Condition`](#condition) | | | The rule's condition, which refuses the choice or action while it holds. | | `reason` | [`Reason`](#reason) | | | The rule's reason, which the player reads on the greyed-out button and as the refusal. | | `hide` | `boolean` | yes | | The rule's hide mark. When true, the button is left off the screen while `when` holds, rather than greyed out. | ## BlockExtras [#blockextras] Type. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#blockextras). The fields any block can have beside its own, a condition and ui hints. ```ts shape import type { BlockExtras } from '@ifloom/engine' type BlockExtras = { when?: Condition ui?: Ui } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `when` | [`Condition`](#condition) | yes | | The block's condition, which leaves it out while it fails. | | `ui` | [`Ui`](#ui)`<`[`BlockUi`](#blockui)`>` | yes | | The block's ui hints. See `BlockUi`. | ## BlockUi [#blockui] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#sceneui-choiceui-blockui-entityui-statui-and-gameui). The ui hints a block of a scene's body takes in its `ui`, carried on the first beat the block makes. The engine declares none, and a UI package augments this interface with its own. ```ts shape import type { BlockUi } from '@ifloom/engine' type BlockUi = { // … } ``` Plugins add fields of their own to it, which their pages list. ## BrokenSave [#brokensave] Type. Explained in [Saves](https://ifloom.dev/docs/reference/saves#brokensave). A save in a slot that can't be read, as `list()` gives it. The listing keeps it so the player can delete it. ```ts shape import type { BrokenSave } from '@ifloom/engine' type BrokenSave = { slot: string broken: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `slot` | `string` | | | The broken save's slot. | | `broken` | `string` | | | The reason the save can't be read, in the words `read` would give. | ## buildEffects [#buildeffects] Function. Explained in [Calls by name](https://ifloom.dev/docs/reference/custom#buildeffects). Returns the effects ready for the reducer, without the calls no plugin or game has. The content checker (`checkGame`) reports each call it leaves out. Every other effect stays as written. A call runs in its turn, on the state the effects before it left. ```ts shape import { buildEffects, type Game } from '@ifloom/engine' function buildEffects(game: Game, refs: readonly EffectRef[]): Effect[] ``` Uses: [`Game`](#game), [`EffectRef`](#effectref), [`Effect`](#effect). ## ButtonDef [#buttondef] Type. Explained in [Actions](https://ifloom.dev/docs/reference/actions#buttondef). The fields a scene's choice (`Choice`) and an action (`ActionDef`) share, read the same way for both. Taking one runs its command, then pays its cost, then applies its effects. ```ts shape import type { ButtonDef } from '@ifloom/engine' type ButtonDef = { id: string label?: string labels?: { when?: Condition; label: string }[] when?: Condition blocked?: Blocked[] cost?: ActionCost effects?: EffectRef[] command?: CommandRef once?: Once tags?: string[] irreversible?: string ui?: Ui } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The choice's or action's id, unique among its scene's choices or among the actions. | | `label` | `string` | yes | | The button's words, with tokens filled, such as `'Order a tea'`. A choice with no label shows its id, and an action with none is never rendered as a button. | | `labels` | `{ when?:` [`Condition`](#condition)`; label: string }[]` | yes | | The button's words that depend on the state, such as "Not today" before you have bought it and "Right." after. The first entry whose `when` holds wins, and `label` is the fallback. | | `when` | [`Condition`](#condition) | yes | | The condition under which the choice or action is offered and can be taken. Always, if left out. | | `blocked` | [`Blocked[]`](#blocked) | yes | | The rules that refuse it for now. The first entry whose `when` holds greys the button out with its reason, or leaves it off with `hide`. | | `cost` | [`ActionCost`](#actioncost) | yes | | The stats it spends. The engine checks them before it runs, lists them on the button and pays them after its command. | | `effects` | [`EffectRef[]`](#effectref) | yes | | The effects it applies after its cost, in order. A plugin's or the game's effect in the short form does computed work. | | `command` | [`CommandRef`](#commandref) | yes | | The command the choice or action sends first, a plugin's in the short form or one of the engine's, but never `choose`. The button is refused with that command's reason while the command would be. An example is `{ 'devices/open': { id: 'messages' } }`. The button's price includes what the command spends. | | `once` | [`Once`](#once) | yes | | The limit of once a game (`{ per: 'game' }`) or once a turn (`{ per: 'turn' }`), counted in `state.chosen`. Once spent, a choice stays on screen and pays nothing more, and an action is refused, both with `reason`. | | `tags` | `string[]` | yes | | The tags a UI can style or filter it by. The engine gives them no meaning. | | `irreversible` | `string` | yes | | The warning that it can't be undone, which a UI shows on the button. | | `ui` | [`Ui`](#ui)`<`[`ChoiceUi`](#choiceui)`>` | yes | | The ui hints carried to its button in the view. See `ChoiceUi`. | ## callOf [#callof] Function. Explained in [Calls by name](https://ifloom.dev/docs/reference/custom#callof). Returns the name and arguments of a call in the short form, or undefined for the engine's own conditions and effects. A plugin's guard or price uses it to read effects. `{ 'calendar/pass': { by: 2 } }` gives `{ name: 'calendar/pass', with: { by: 2 } }`. ```ts shape import { callOf } from '@ifloom/engine' function callOf(entry: object): { name: string; with: Record } | undefined ``` ## CarryOver [#carryover] Type. Explained in [Game state](https://ifloom.dev/docs/reference/state#carryover). The stats and kv keys a New Game+ carries over from the game before, declared in `carryOver`. A plugin carries its own state with its `carry`. ```ts shape import type { CarryOver } from '@ifloom/engine' type CarryOver = { stats?: string[] kv?: string[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `stats` | `string[]` | yes | | The player's stats to carry, by id. | | `kv` | `string[]` | yes | | The player's kv keys to carry, by key. | ## cases [#cases] Function. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#cases). Returns a `{ cases }` block that shows only the first of `blocks` whose own `when` holds, or that has none. Leave the last without a `when` as the fallback. A `when` in `extras` leaves the whole block out while it fails. ```ts fragment cases([ text(`Rain streaks the window.`, { when: { kv: 'rain' } }), text(`Ava's umbrella is by the door.`, { when: { kv: 'cloudy' } }), text(`The street is dry.`), ]) ``` ```ts shape import { cases } from '@ifloom/engine' function cases(blocks: Block[], extras?: BlockExtras): Block ``` Uses: [`Block`](#block), [`BlockExtras`](#blockextras). ## chance [#chance] Function. Explained in [Randomness](https://ifloom.dev/docs/reference/random#chance). Returns true `numerator` times in `outOf`, drawn from `parts`. ```ts shape import { chance } from '@ifloom/engine' function chance(numerator: number, outOf: number, ...parts: (string | number)[]): boolean ``` ## Change [#change] Type. Explained in [Changes](https://ifloom.dev/docs/reference/changes#change). A stat the last command moved, with its old and new values and the change in the stat's own format. `state.changes` keeps these. ```ts shape import type { Change } from '@ifloom/engine' type Change = { stat: string of?: EntityRef from: number to: number by: number label: string text: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `stat` | `string` | | | The stat's id. | | `of` | [`EntityRef`](#entityref) | yes | | The entity the stat is kept on. Left out for the player's stat. | | `from` | `number` | | | The stat's value before the command. | | `to` | `number` | | | The stat's value after the command. | | `by` | `number` | | | The amount the stat moved, `to - from`, above 0 when it went up. | | `label` | `string` | | | The stat's `label`. | | `text` | `string` | | | The change in the stat's `format`, signed, such as `'+30 coins'` or `'-£5'`. | ## ChangesDef [#changesdef] Type. Explained in [Changes](https://ifloom.dev/docs/reference/changes#changesdef). The stats the game declares in `changes` for `view.changes` to track, by id. An entity stat's id covers that stat on every entity. ```ts shape import type { ChangesDef } from '@ifloom/engine' type ChangesDef = { stats: string[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `stats` | `string[]` | | | The ids of the stats to track. | ## ChangeView [#changeview] Type. Explained in [Changes](https://ifloom.dev/docs/reference/changes#changeview). A stat change as the player sees it, in `view.changes`. It adds the words that say what moved to a `Change`. ```ts shape import type { ChangeView } from '@ifloom/engine' type ChangeView = { stat: string of?: EntityRef from: number to: number by: number label: string text: string name?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `stat` | `string` | | | The stat's id. | | `of` | [`EntityRef`](#entityref) | yes | | The entity the stat is kept on. Left out for the player's stat. | | `from` | `number` | | | The stat's value before the command. | | `to` | `number` | | | The stat's value after the command. | | `by` | `number` | | | The amount the stat moved, `to - from`, above 0 when it went up. | | `label` | `string` | | | The stat's `label`. | | `text` | `string` | | | The change in the stat's `format`, signed, such as `'+30 coins'` or `'-£5'`. | | `name` | `string` | yes | | The words to show after `text`, so the change says what moved. Left out when the stat's format already says it (`+30 coins`). It's the entity's name for an entity's stat (`+4 Ava`), else the stat's `label` when `text` has no words in it (`+1 Charm`, `+20% Mood`). | ## ChannelDef [#channeldef] Type. Explained in [Audio](https://ifloom.dev/docs/reference/audio#channeldef). An audio channel the game declares in `audio.channels`, merged over the default channels. It sets whether its sounds replace each other or overlap, and how they fade. ```ts shape import type { ChannelDef } from '@ifloom/engine' type ChannelDef = { mode: 'background' | 'cue' crossfade?: number volume?: string duck?: { under: string[]; to: number } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `mode` | `'background' \| 'cue'` | | | The channel's mode. A `background` channel plays one thing until it changes, and a `cue` channel plays each sound once, overlapping. | | `crossfade` | `number` | yes | | The milliseconds a background channel takes to fade from one track to the next. 1000 for `music`, 600 for `ambience` and 1000 for others. | | `volume` | `string` | yes | | The id of the ui setting, a range, that sets the channel's volume. | | `duck` | `{ under: string[]; to: number }` | yes | | The channel's ducking, quietening it to `to` (0 to 1) while any channel in `under` plays. No ducking if left out. | ## Checked [#checked] Type. Explained in [Checking content](https://ifloom.dev/docs/reference/checks#checked). The report `checkGame` returns, with the content's problems, warnings and files. ```ts shape import type { Checked } from '@ifloom/engine' type Checked = { problems: Problem[] warnings: Problem[] files: FileRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `problems` | [`Problem[]`](#problem) | | | The content's faults, such as a broken reference, a key declared twice, or a call with the wrong arguments. Any problem fails `ifloom check`. | | `warnings` | [`Problem[]`](#problem) | | | The faults that may show in play but aren't problems, such as a token that may be unset with no fallback. A warning fails no check. | | `files` | [`FileRef[]`](#fileref) | | | The files the content names (pictures, videos, sounds) and where, for a build to check they exist. | ## checkGame [#checkgame] Function. Explained in [Checking content](https://ifloom.dev/docs/reference/checks#checkgame). Returns the `Checked` report of a game's content, its problems, warnings and the files it names. It runs on any `Game`, hand-built or loaded. Give `probes` to also render every scene against each state, so the report includes a scene that throws for one through the game's own conditions or values. A hand-built game's problems name the pack `game`. ```ts shape import { checkGame, type Game } from '@ifloom/engine' function checkGame(game: Game, options?: { probes?: readonly Probe[] }): Checked ``` Uses: [`Game`](#game), [`Probe`](#probe), [`Checked`](#checked). ## Choice [#choice] Type. Explained in [Scenes](https://ifloom.dev/docs/reference/scenes#choice). A choice a scene declares in its `choices` or a decision, with the fields of a `ButtonDef`. The player sends it as `{ type: 'choose', id }`, and `state.chosen` counts it as `#`. A spent `once` choice stays on screen with its `once.reason` and pays nothing more. ```ts shape import type { Choice } from '@ifloom/engine' type Choice = { id: string label?: string labels?: { when?: Condition; label: string }[] when?: Condition blocked?: Blocked[] cost?: ActionCost effects?: EffectRef[] command?: CommandRef once?: Once tags?: string[] irreversible?: string ui?: Ui } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The choice's or action's id, unique among its scene's choices or among the actions. | | `label` | `string` | yes | | The button's words, with tokens filled, such as `'Order a tea'`. A choice with no label shows its id, and an action with none is never rendered as a button. | | `labels` | `{ when?:` [`Condition`](#condition)`; label: string }[]` | yes | | The button's words that depend on the state, such as "Not today" before you have bought it and "Right." after. The first entry whose `when` holds wins, and `label` is the fallback. | | `when` | [`Condition`](#condition) | yes | | The condition under which the choice or action is offered and can be taken. Always, if left out. | | `blocked` | [`Blocked[]`](#blocked) | yes | | The rules that refuse it for now. The first entry whose `when` holds greys the button out with its reason, or leaves it off with `hide`. | | `cost` | [`ActionCost`](#actioncost) | yes | | The stats it spends. The engine checks them before it runs, lists them on the button and pays them after its command. | | `effects` | [`EffectRef[]`](#effectref) | yes | | The effects it applies after its cost, in order. A plugin's or the game's effect in the short form does computed work. | | `command` | [`CommandRef`](#commandref) | yes | | The command the choice or action sends first, a plugin's in the short form or one of the engine's, but never `choose`. The button is refused with that command's reason while the command would be. An example is `{ 'devices/open': { id: 'messages' } }`. The button's price includes what the command spends. | | `once` | [`Once`](#once) | yes | | The limit of once a game (`{ per: 'game' }`) or once a turn (`{ per: 'turn' }`), counted in `state.chosen`. Once spent, a choice stays on screen and pays nothing more, and an action is refused, both with `reason`. The choice's limit of once a game or once a turn. See `Once`. | | `tags` | `string[]` | yes | | The tags a UI can style or filter it by. The engine gives them no meaning. | | `irreversible` | `string` | yes | | The warning that it can't be undone, which a UI shows on the button. | | `ui` | [`Ui`](#ui)`<`[`ChoiceUi`](#choiceui)`>` | yes | | The ui hints carried to its button in the view. See `ChoiceUi`. | ## choice [#choice-1] Function. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#choice). Returns a choice for a decision or a scene's ending choices, with `label` as its words. Its id is unique within the scene. Every other field of a `Choice` goes in `fields`, such as `effects`, `cost`, `blocked`, `once` or `command`, and `then`, the blocks the flow shows once the player chooses it. ```ts shape import { choice } from '@ifloom/engine' function choice(id: string, label: string, fields?: Omit): FlowChoice ``` Uses: [`FlowChoice`](#flowchoice). ## ChoiceUi [#choiceui] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#sceneui-choiceui-blockui-entityui-statui-and-gameui). The ui hints a choice or an action takes in its `ui`. The engine declares none, and a UI package augments this interface with its own. ```ts shape import type { ChoiceUi } from '@ifloom/engine' type ChoiceUi = { // … } ``` Plugins add fields of their own to it, which their pages list. ## clampStat [#clampstat] Function. Explained in [Stats](https://ifloom.dev/docs/reference/stats#clampstat). Returns `value` held to the stat's declared range. The range is 0 to 100 unless the stat declares one. ```ts shape import { clampStat, type Game } from '@ifloom/engine' function clampStat(state: GameState, game: Game, id: string, value: number): number ``` Uses: [`GameState`](#gamestate), [`Game`](#game). ## Command [#command] Type. Explained in [Commands](https://ifloom.dev/docs/reference/commands#command). A request to change the game, told apart by its `type`, such as `{ type: 'choose', id }`. The reducer applies it or refuses it. ```ts shape import type { Command } from '@ifloom/engine' type Command = | { type: 'setting'; id: string; to: KvValue; } | { type: 'scene'; id: string; } | { type: 'action'; id: string; } | { type: 'input'; id: string; to?: KvValue; } | { type: 'minigame'; input: string; } | { type: 'start'; seed?: number; kv?: Record; } | { type: 'newGame'; } | { type: 'custom'; name: string; with?: Record; } | { type: 'dismiss'; id?: string; } | { type: 'choose'; id: string; } | { type: 'leave'; } | { type: 'tick'; ms: number; } | { type: 'closePanel'; } ``` Uses: [`KvValue`](#kvvalue). ## CommandCall [#commandcall] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#conditioncall-effectcall-and-commandcall). A plugin's or the game's command in the short form, type-checked against `CommandRegistry`. ```ts shape import type { CommandCall } from '@ifloom/engine' type CommandCall = CallIn ``` Uses: [`CallIn`](https://ifloom.dev/docs/api/engine-plugin#callin), [`CommandRegistry`](#commandregistry). ## CommandLog [#commandlog] Type. Explained in [The runner](https://ifloom.dev/docs/reference/runner#commandlog). A record of play, the state it started from and every command since. The engine is deterministic, so `replay` gives the same state from it every time. A log makes a bug report a developer can step through, or plays two versions of a game the same way to compare them. ```ts shape import type { CommandLog } from '@ifloom/engine' type CommandLog = { game: string start: GameState commands: Command[] schema?: number plugins?: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `game` | `string` | | | The id of the game the log was played in, so it isn't played against another game. | | `start` | [`GameState`](#gamestate) | | | The state the log's first command was applied to. | | `commands` | [`Command[]`](#command) | | | The log's commands, oldest first, refused ones included. | | `schema` | `number` | yes | | The engine's `SCHEMA` the log's commands were written in. A log without one is read as the oldest schema. | | `plugins` | `Record` | yes | | The `commandVersion` of each plugin the log's commands were written in, by plugin id. | ## commandOf [#commandof] Function. Explained in [Calls by name](https://ifloom.dev/docs/reference/custom#commandof). Returns the command the engine runs for `ref`. A short-form call becomes `{ type: 'custom', name, with }`. ```ts shape import { commandOf } from '@ifloom/engine' function commandOf(ref: CommandRef): Command ``` Uses: [`CommandRef`](#commandref), [`Command`](#command). ## CommandRef [#commandref] Type. Explained in [Calls by name](https://ifloom.dev/docs/reference/custom#commandref). A command in content, a plain command or a plugin's in the short form (`{ 'places/go': { id: 'cafe' } }`), checked against `CommandRegistry`. ```ts shape import type { CommandRef } from '@ifloom/engine' type CommandRef = Command | CommandCall ``` Uses: [`Command`](#command), [`CommandCall`](#commandcall). ## CommandRegistry [#commandregistry] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#conditionregistry-effectregistry-commandregistry-queryregistry-and-viewregistry). The registry of commands plugins and the game add, by full name, with each one's arguments. It works as `ConditionRegistry` does. ```ts shape import type { CommandRegistry } from '@ifloom/engine' type CommandRegistry = { // … } ``` Plugins add fields of their own to it, which their pages list. ## Condition [#condition] Type. Explained in [Conditions](https://ifloom.dev/docs/reference/conditions#condition). A test of the state that holds or doesn't, written as plain data on a block, a choice or a variants member. Each kind is told apart by its one key, such as `{ stat: 'coins', gte: 3 }`. A plugin's condition, or the game's own from its `rules`, is a `PluginCall` in the short form (`{ 'quests/done': { quest: 'bakery' } }`), checked against `ConditionRegistry` when its name is declared there. Being data, a condition stays serialisable and the content checker can check it. ```ts shape import type { Condition } from '@ifloom/engine' type Condition = | { kv: string; is?: KvValue | readonly KvValue[]; of?: string; } & Range | { all: Condition[]; } | { any: Condition[]; } | { not: Condition; } | { count: string | Select; where?: Condition; } & Range | { entity: string; } | { owned: string; of?: string; via?: string; } & Range | { turn: Range; } | { value: string; with?: PluginArgs; is?: KvValue | readonly KvValue[]; } & Range | { storyline: string; open?: boolean; } | { setting: string; is?: KvValue; } & Range | { stat: string; of?: string; } & Range | { level: string; of?: string; } & Range | { chose: string; } & Range | { seen: string; } & Range | { since: string; last?: boolean; } & Range | { scene: string[]; } | { timer: string; } & Range | { roll: string; passed?: boolean; critical?: boolean | 'max' | 'min'; } | ConditionCall ``` Uses: [`KvValue`](#kvvalue), [`Range`](#range), [`Select`](#select), [`PluginArgs`](https://ifloom.dev/docs/api/engine-plugin#pluginargs), [`ConditionCall`](#conditioncall). ## ConditionCall [#conditioncall] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#conditioncall-effectcall-and-commandcall). A plugin's or the game's condition in the short form, type-checked against `ConditionRegistry`. ```ts shape import type { ConditionCall } from '@ifloom/engine' type ConditionCall = CallIn ``` Uses: [`CallIn`](https://ifloom.dev/docs/api/engine-plugin#callin), [`ConditionRegistry`](#conditionregistry). ## ConditionRegistry [#conditionregistry] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#conditionregistry-effectregistry-commandregistry-queryregistry-and-viewregistry). The registry of conditions plugins and the game add, by full name, with each one's arguments, or `true` for none. A plugin augments it, and a call to a declared name is type-checked against it. ```ts fragment declare module '@ifloom/engine' { interface ConditionRegistry { 'quests/done': { quest: string } 'calendar/weekend': true } } ``` ```ts shape import type { ConditionRegistry } from '@ifloom/engine' type ConditionRegistry = { // … } ``` Plugins add fields of their own to it, which their pages list. ## Content [#content] Type. Explained in [Content and packs](https://ifloom.dev/docs/reference/content#content). One file of the game's own content, such as `story/cafe.ts`. Each scene, stat or prose key may be declared only once across the game's content. Content has no id or schema, since it is compiled with the engine it runs on. ```ts fragment type Content = { name?: string strings?: Record prose?: Record words?: Record variants?: Record data?: Record> kinds?: KindDef[] entities?: EntityDef[] traits?: TraitTable player?: PlayerDef | undefined kv?: Record resets?: Record storylines?: StorylineDef[] actions?: ActionDef[] triggers?: TriggerDef[] inputs?: InputDef[] settings?: SettingDef[] stats?: StatDef[] introScene?: string scenes?: DataScene[] minigames?: MinigameDef[] timers?: TimerDef[] audio?: Partial media?: GameMedia ui?: Ui saveable?: Blocked[] locks?: Lock[] phrases?: Phrases changes?: ChangesDef carryOver?: CarryOver finished?: Condition credits?: CreditGroup[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | yes | | The content's name in problems, such as `story.cafe`. `content` if left out. | | `strings` | `Record` | yes | | The lines that replace the engine's and plugins' strings, by key. | | `prose` | `Record` | yes | | The prose keys' lines, by key. | | `words` | `Record` | yes | | The words table, other words for the fields a player reads, by key. A translation is one pack with this table and its own `prose`. Each key names one field, as `translatableFields` lists them (`action.wait.label`, `entity.character:ava.name`, `scene.cafe.counter.text.intro`). `loadGame` lays it over the merged content, a later pack's over an earlier one's, and reports a key that names no field. | | `variants` | `Record` | yes | | The variants lists' members by list name, in order. Content and packs append to a list. A member is a prose key, or `{ prose: key, weight }` to be drawn more or less often than the rest. | | `data` | `Record>` | yes | | The plugins' content, by plugin id and then list, such as `{ quests: { quests: [...] } }`. A pack's entry replaces the one with the same id, as its scenes do. | | `kinds` | [`KindDef[]`](#kinddef) | yes | | The pack's kinds. A later pack's kind replaces an earlier one with the same id. | | `entities` | [`EntityDef[]`](#entitydef) | yes | | The pack's entities at the start. A later pack's entity replaces an earlier one with the same kind and id. | | `traits` | [`TraitTable`](#traittable) | yes | | The pack's traits, by trait id and then entity, over what each entity declares itself, such as `{ 'laundry/washable': { 'clothing:scarf': { temp: 30 } } }`. A later pack's row replaces an earlier one's. | | `player` | `PlayerDef \| undefined` | yes | | The pack's player. It replaces the content's `player` whole. | | `kv` | `Record` | yes | | The pack's starting kv store, by key. A later pack's value replaces an earlier one's. | | `resets` | `Record` | yes | | The pack's keys reset each turn, by key. A later pack's value replaces an earlier one's. | | `storylines` | [`StorylineDef[]`](#storylinedef) | yes | | The pack's storylines, merged by id over the content's. | | `actions` | [`ActionDef[]`](#actiondef) | yes | | The pack's actions, by id. A later pack's action replaces an earlier one with the same id. | | `triggers` | [`TriggerDef[]`](#triggerdef) | yes | | The pack's triggers, merged by id over the content's. | | `inputs` | [`InputDef[]`](#inputdef) | yes | | The pack's inputs, merged by id over the content's. | | `settings` | [`SettingDef[]`](#settingdef) | yes | | The pack's settings. A later pack's setting replaces an earlier one with the same id. | | `stats` | [`StatDef[]`](#statdef) | yes | | The pack's stats. A later pack's stat replaces an earlier one with the same id. | | `introScene` | `string` | yes | | The scene open on the first frame. A later pack's replaces an earlier one's. | | `scenes` | [`DataScene[]`](#datascene) | yes | | The pack's scenes. A later pack's scene replaces an earlier one with the same id. | | `minigames` | [`MinigameDef[]`](#minigamedef) | yes | | The pack's minigames. A later pack's minigame replaces an earlier one with the same id. | | `timers` | [`TimerDef[]`](#timerdef) | yes | | The pack's timers. A later pack's timer replaces an earlier one with the same id. | | `audio` | `Partial<`[`GameAudio`](#gameaudio)`>` | yes | | The pack's tracks, channels and defaults, over the content's. A later pack's track or channel replaces an earlier one with the same id, and its `mute`, `sound` and `default` entries win too. | | `media` | [`GameMedia`](#gamemedia) | yes | | The pack's pools of pictures and videos. A later pack's pool replaces an earlier one with the same id, files and all. | | `ui` | [`Ui`](#ui)`<`[`GameUi`](#gameui)`>` | yes | | The pack's ui hints for the whole game, merged hint by hint. A later pack's hint replaces an earlier one's, and the rest stay. | | `saveable` | [`Blocked[]`](#blocked) | yes | | The pack's reasons to refuse saving, added after the content's. An entry with the `id` of an earlier one replaces it. | | `locks` | [`Lock[]`](https://ifloom.dev/docs/api/engine-plugin#lock) | yes | | The pack's locks, added after the content's. A lock with the `id` of an earlier one replaces it. | | `phrases` | [`Phrases`](#phrases) | yes | | The pack's phrases, words that change with the state, printed in a line as `{{name}}`. Each is a plain string or a list of `{ when?, text }` rows tried in order, and an object is a group. A later pack's phrase replaces an earlier one with the same full name, and a pack can add phrases to a group. | | `changes` | [`ChangesDef`](#changesdef) | yes | | The pack's tracked stats, by id, such as `{ stats: ['coins', 'trust'] }`. The engine adds every file's and pack's lists together. | | `carryOver` | [`CarryOver`](#carryover) | yes | | The pack's rules for a New Game+. They replace the content's `carryOver` whole. | | `finished` | [`Condition`](#condition) | yes | | The pack's condition for the game being finished. It replaces the content's, and the runner records the first time it holds in the profile's `core:finished`. | | `credits` | [`CreditGroup[]`](#creditgroup) | yes | | The pack's credits, in groups. A group whose id is already declared gets these credits after its own. Its `title` or `description` replaces the earlier one, and a new id adds a group after the others. | ## CreatedEntity [#createdentity] Type. Explained in [Effects](https://ifloom.dev/docs/reference/effects#createdentity). The fields a `create` effect gives a new entity in its `with`. The engine reads each one left out from the entity it's made `like`, else from its kind. ```ts shape import type { CreatedEntity } from '@ifloom/engine' type CreatedEntity = { id?: string name?: string description?: string image?: string tags?: string[] traits?: Record stats?: Record kv?: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | yes | | The entity's id within its kind. The next free number (`#1`, `#2`) if left out. | | `name` | `string` | yes | | The entity's name. The `like` entity's if left out. | | `description` | `string` | yes | | The entity's description, with tokens filled when it's read. The `like` entity's if left out. | | `image` | `string` | yes | | The entity's picture, through `artSrc`. The `like` entity's if left out. | | `tags` | `string[]` | yes | | The entity's own tags, after its kind's and its `like` entity's. | | `traits` | `Record` | yes | | The entity's trait data, by trait id, over its `like` entity's or its kind's. | | `stats` | `Record` | yes | | The entity's starting stats, over its `like` entity's. | | `kv` | `Record` | yes | | The entity's starting kv keys, over its `like` entity's. | ## CreateFields [#createfields] Type. Explained in [Effects](https://ifloom.dev/docs/reference/effects#createfields). The fields a `create` effect takes besides its kind. ```ts shape import type { CreateFields } from '@ifloom/engine' type CreateFields = { like?: string with?: CreatedEntity effects?: EffectRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `like` | `string` | yes | | The entity of the same kind the new one reads what it isn't given from. | | `with` | [`CreatedEntity`](#createdentity) | yes | | The new entity's fields, its id, name, description, picture, tags, traits, stats and kv. | | `effects` | [`EffectRef[]`](#effectref) | yes | | Effects that run once the entity is made, with `'$'` as it, such as `[{ receive: '$' }]` to hand it over. | ## createRunner [#createrunner] Function. Explained in [The runner](https://ifloom.dev/docs/reference/runner#createrunner). Returns a `Runner` that plays a game from a start state. Undo, the backlog, saving, autosave and the profile are off unless `RunnerOptions` turns them on. The runner wraps `apply` with undo and redo, a backlog, a command log, saving, loading and autosave, and tells listeners when the state changes. ```ts shape import { createRunner, type Game } from '@ifloom/engine' function createRunner(game: Game, start: GameState, options?: RunnerOptions): Runner ``` Uses: [`Game`](#game), [`GameState`](#gamestate), [`RunnerOptions`](#runneroptions), [`Runner`](#runner). ## Credit [#credit] Type. Explained in [Credits](https://ifloom.dev/docs/reference/credits#credit). One credit in a group, such as a person, a studio or a source the game thanks. Only `name` is needed. ```ts shape import type { Credit } from '@ifloom/engine' type Credit = { name: string role?: string description?: string href?: string licence?: string art?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | | | The person, studio or source credited, as the credits page shows it. It's a name, so a translation leaves it alone. | | `role` | `string` | yes | | The credit's role, the part they played or gave, such as `'Writer'`, `'Cover photograph'` or `'Gold patron'`. | | `description` | `string` | yes | | A line more about the credit, such as `'The harbour at dawn, via Unsplash'`. | | `href` | `string` | yes | | A link to them or to the source, `http:`, `https:` or `mailto:`. | | `licence` | `string` | yes | | The licence the work is used under, such as `'CC BY 4.0'`. | | `art` | `string` | yes | | The path of a picture beside the credit, such as a portrait or the credited image itself. | ## CreditGroup [#creditgroup] Type. Explained in [Credits](https://ifloom.dev/docs/reference/credits#creditgroup). A group of credits the game declares in `credits`, such as the team or the patrons, shown under its title in order. ```ts shape import type { CreditGroup } from '@ifloom/engine' type CreditGroup = { id: string title: string description?: string credits: Credit[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The group's id. Content and packs that name the same id add to one group. | | `title` | `string` | | | The group's heading, such as `'Patrons'`. | | `description` | `string` | yes | | A line under the heading, such as `'With thanks to everyone on Patreon'`. | | `credits` | [`Credit[]`](#credit) | | | The group's credits, in order. | ## creditsOf [#creditsof] Function. Explained in [Credits](https://ifloom.dev/docs/reference/credits#creditsof). Returns the game's credit groups that have at least one credit, in order, as a credits page shows them. Empty when the game credits no one. ```ts shape import { creditsOf, type Game } from '@ifloom/engine' function creditsOf(game: Pick): readonly CreditGroup[] ``` Uses: [`Game`](#game), [`CreditGroup`](#creditgroup). ## CustomContext [#customcontext] Type. Explained in [Calls by name](https://ifloom.dev/docs/reference/custom#customcontext). The context every plugin or game function gets beside the state, with the game, queries, values and seeded draws. `PluginContext` extends it. ```ts shape import type { CustomContext, Game } from '@ifloom/engine' type CustomContext = { game: Game query: Query value: (name: string, args?: PluginArgs) => string | number | undefined roll: (max: number, name: string) => number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `game` | [`Game`](#game) | | | The context's loaded game. | | `query` | [`Query`](#query) | | | The context's query function, which asks a plugin or the game by full name (`query('loyalty/stampsLeft')`). | | `value` | `(name: string, args?:` [`PluginArgs`](https://ifloom.dev/docs/api/engine-plugin#pluginargs)`) => string \| number \| undefined` | | | The context's value function, which returns a value by full name, a plugin's (`messages/unread`) or the game's, asked with `args`. It returns undefined when no plugin or game has that value. | | `roll` | `(max: number, name: string) => number` | | | The context's roll function, which returns a whole number from 0 to `max - 1`, drawn from the save's seed, the turn and `name`. The same save and turn always draw the same number. | ## DataScene [#datascene] Type. Explained in [Scenes](https://ifloom.dev/docs/reference/scenes#datascene). A scene the game declares in `scenes`, with its body and its choices. Its id is unique across the game. ```ts shape import type { DataScene } from '@ifloom/engine' type DataScene = { drawnFrom?: string[] weight?: number when?: Condition minigame?: string id: string title?: string speaker?: string tags?: string[] panel?: ScenePanel audio?: Record picture?: PictureDef ui?: Ui body: Block[] choices: Choice[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `drawnFrom` | `string[]` | yes | | The sets the scene can be drawn from, by name, such as `['cafe']`. A `{ scene: { from: 'cafe' } }` effect draws one of the scenes that name `'cafe'` here. It's separate from `tags`, which only style the scene. | | `weight` | `number` | yes | | The scene's weight in a draw, against the other scenes it could be drawn with. 1 if left out, and it needs `drawnFrom`. | | `when` | [`Condition`](#condition) | yes | | The storylet's condition. The scene can be drawn only while it holds, but a `scene` command or effect that names the scene opens it regardless. | | `minigame` | `string` | yes | | The id of the minigame that starts when the scene is entered. The scene shows again once it ends. | | `id` | `string` | | | The scene's id, unique across the game, such as `'cafe.counter'`. | | `title` | `string` | yes | | The scene's title, in `view.scene.title`. The room's title, else the game's, if left out. | | `speaker` | `string` | yes | | The scene's speaker, by entity id or reference (`'ava'`, `'character:ava'`), in `view.scene.speaker` and `view.scene.image`. | | `tags` | `string[]` | yes | | The tags a UI can style the scene by, such as `['letter']` or `['flashback']`. The engine gives them no meaning. | | `panel` | [`ScenePanel`](#scenepanel) | yes | | The panel held open for as long as the scene is, such as `{ panel: 'counter', with: { vendor: 'cafe' } }`. It is `view.panel`, as one the `panel` effect opens is, with the scene's id in `scene`. See `ScenePanel`. | | `audio` | `Record` | yes | | The tracks that play on background channels while the scene is open, by channel, such as `{ ambience: 'rain' }`. Null silences one. | | `picture` | [`PictureDef`](#picturedef) | yes | | The scene's layered picture with hotspots, in `view.scene.picture`. See `PictureDef`. | | `ui` | [`Ui`](#ui)`<`[`SceneUi`](#sceneui)`>` | yes | | The scene's ui hints, carried to `view.scene.ui`. See `SceneUi`. | | `body` | [`Block[]`](#block) | | | The scene's body, its blocks from top to bottom. See `Block`. | | `choices` | [`Choice[]`](#choice) | | | The scene's ending choices, offered under the body once the flow ends. A flowing scene's other choices are in its decisions. | ## decide [#decide] Function. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#decide). Returns a decision, where the flow waits until the player chooses one of `choices`. Its id is unique within the scene. The chosen choice's `then` comes next, then the blocks after the decision. ```ts shape import { decide } from '@ifloom/engine' function decide(id: string, choices: FlowChoice[], extras?: BlockExtras): Block ``` Uses: [`FlowChoice`](#flowchoice), [`BlockExtras`](#blockextras), [`Block`](#block). ## declaredTrait [#declaredtrait] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#declaredtrait). Returns the data of one trait on one entity from content alone, typed by `TraitRegistry`, or undefined when it lacks the trait. Use it for a check, or anywhere with no state. A row in a content `traits` table wins, then the entity's own `traits`, each laid over its kind's default. An entity made in play gets its kind's default here, and `traitOf` adds the data it was made with. It doesn't ask whether the entity is still in the game. ```ts shape import { declaredTrait } from '@ifloom/engine' function declaredTrait(game: TraitSource, ref: string, id: K): TraitData | undefined ``` Uses: [`TraitSource`](#traitsource), [`TraitData`](#traitdata). ## declaredWithTrait [#declaredwithtrait] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#declaredwithtrait). Returns every declared entity that has a trait, as references in content order. It reads content alone, as `declaredTrait` does. ```ts shape import { declaredWithTrait } from '@ifloom/engine' function declaredWithTrait(game: TraitSource, id: string): EntityRef[] ``` Uses: [`TraitSource`](#traitsource), [`EntityRef`](#entityref). ## describeProblem [#describeproblem] Function. Explained in [Checking content](https://ifloom.dev/docs/reference/checks#describeproblem). Returns a `Problem` as one line, `pack · where · what`. ```ts shape import { describeProblem } from '@ifloom/engine' function describeProblem(problem: Problem): string ``` Uses: [`Problem`](#problem). ## Dice [#dice] Type. Explained in [Dice rolls](https://ifloom.dev/docs/reference/rolls#dice). Dice a `roll` effect throws, in notation (`'2d6+1'`, `'1d20'`, `'d100'`) or as a count of dice and their sides. A count of 1 if left out. ```ts shape import type { Dice } from '@ifloom/engine' type Dice = string | { count?: number; sides: number } ``` ## dismiss [#dismiss] Function. Explained in [Commands](https://ifloom.dev/docs/reference/commands#dismiss). Returns the state with the notice `id` marked seen, or every notice when `id` is left out. ```ts shape import { dismiss } from '@ifloom/engine' function dismiss(state: GameState, id?: string): GameState ``` Uses: [`GameState`](#gamestate). ## draw [#draw] Function. Explained in [Randomness](https://ifloom.dev/docs/reference/random#draw). Returns a whole number from 0 up to but not including `max`, drawn from `parts`. Returns 0 when `max` is 0 or less. ```ts shape import { draw } from '@ifloom/engine' function draw(max: number, ...parts: (string | number)[]): number ``` ## drawOne [#drawone] Function. Explained in [Randomness](https://ifloom.dev/docs/reference/random#drawone). Returns one entry of `items`, drawn from `parts`. Every entry is equally likely. ```ts shape import { drawOne } from '@ifloom/engine' function drawOne(items: readonly T[], ...parts: (string | number)[]): T ``` ## Effect [#effect] Type. Explained in [Effects](https://ifloom.dev/docs/reference/effects#effect). A change to the state, told apart by its one key as a condition is (`{ stat: 'coins', by: -2 }`, `{ scene: null }`). It runs in its turn, on the state the effects before it left. A plugin's effect, or the game's own, is a `PluginCall` in the short form, such as `{ 'quests/start': { quest: 'bakery' } }` or `{ 'game/payRent': {} }`. ```ts shape import type { Effect } from '@ifloom/engine' type Effect = | { kv: string; to: KvValue; of?: string; } | { kv: string; by: Amount; of?: string; } | { kv: string; random: [Amount, Amount]; of?: string; } | { audio: string; to?: string | null; } | { turn: true | { by: number; }; } | { stat: string; by: Amount; of?: string; } | { stat: string; to: Amount; of?: string; } | { scene: string | { from: string; otherwise?: string; } | null; } | { timer: string; to?: number | null; } | { timer: string; by: number; } | { roll: string; dice: Dice; plus?: Amount; against?: Amount; } | { you: string | null; } | { minigame: string; } | { sound: string; } | { remove: string; } | { create: string; } & CreateFields | { each: string | Select; where?: Condition; effects: Effect[]; } | { receive: string; by?: Amount; to?: string; via?: string; } | { release: string; by?: Amount; from?: string; via?: string; } | { closeStoryline: string; turns: number; } | { notify: string; text?: string; image?: string; tag?: string; id?: string; } | { point: string; } | { panel: string | null; with?: PluginArgs; } | EffectCall ``` Uses: [`KvValue`](#kvvalue), [`Amount`](#amount), [`Dice`](#dice), [`CreateFields`](#createfields), [`Select`](#select), [`Condition`](#condition), [`PluginArgs`](https://ifloom.dev/docs/api/engine-plugin#pluginargs), [`EffectCall`](#effectcall). ## EffectCall [#effectcall] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#conditioncall-effectcall-and-commandcall). A plugin's or the game's effect in the short form, type-checked against `EffectRegistry`. ```ts shape import type { EffectCall } from '@ifloom/engine' type EffectCall = CallIn ``` Uses: [`CallIn`](https://ifloom.dev/docs/api/engine-plugin#callin), [`EffectRegistry`](#effectregistry). ## EffectRef [#effectref] Type. Explained in [Calls by name](https://ifloom.dev/docs/reference/custom#effectref). An effect in content, one of the engine's or a plugin's or the game's in the short form. It is the same type as `Effect`. ```ts shape import type { EffectRef } from '@ifloom/engine' type EffectRef = Effect ``` Uses: [`Effect`](#effect). ## EffectRegistry [#effectregistry] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#conditionregistry-effectregistry-commandregistry-queryregistry-and-viewregistry). The registry of effects plugins and the game add, by full name, with each one's arguments. It works as `ConditionRegistry` does. ```ts shape import type { EffectRegistry } from '@ifloom/engine' type EffectRegistry = { // … } ``` Plugins add fields of their own to it, which their pages list. ## effectsOf [#effectsof] Function. Explained in [Actions](https://ifloom.dev/docs/reference/actions#effectsof). Returns the effects a command would apply, worked out before it runs. Plugins' guards and prices, and locks on an effect, read them. An action gives its cost as stat effects, then its effects. A choice gives its effects, and a plugin command gives its `effectsOf`. Any other command gives none. ```ts shape import { effectsOf, type Game } from '@ifloom/engine' function effectsOf(state: GameState, game: Game, command: CommandRef): Effect[] ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`CommandRef`](#commandref), [`Effect`](#effect). ## entitiesOf [#entitiesof] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#entitiesof). Returns every entity of a kind in the game, as references. Declared ones come first in content order, then those made in play in the order they were made. ```ts shape import { entitiesOf, type Game } from '@ifloom/engine' function entitiesOf(state: GameState, game: Game, kind: string): EntityRef[] ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`EntityRef`](#entityref). ## EntitiesView [#entitiesview] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#entitiesview-and-entityview). A listed kind as the player sees it, in `view.entities`, with its listed entities. ```ts shape import type { EntitiesView } from '@ifloom/engine' type EntitiesView = { id: string label: string plural: string unique: boolean entries: EntityView[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The kind's id, such as `'character'`. | | `label` | `string` | | | The kind's label for one entity, such as `'Character'`. | | `plural` | `string` | | | The kind's label for several, for a heading, such as `'Characters'`. Its `label` when the kind gives none. | | `unique` | `boolean` | | | The kind's `unique` mark, true when each entity is one particular thing that can hold others. | | `entries` | [`EntityView[]`](#entityview) | | | The kind's listed, visible entities, declared ones first, then those created in play. | ## EntityDef [#entitydef] Type. Explained in [Entities](https://ifloom.dev/docs/reference/entities#entitydef). An entity the game declares in `entities`, there from the start of the game. Its id is unique within its kind. ```ts shape import type { EntityDef } from '@ifloom/engine' type EntityDef = { id: string of: string name: string description?: string image?: string tags?: string[] visible?: Condition stats?: Record kv?: Record traits?: { [K in keyof TraitRegistry]?: Partial } & Record ui?: Ui } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The entity's id, unique within its kind. | | `of` | `string` | | | The id of the entity's kind. | | `name` | `string` | | | The entity's name, as the player reads it, such as "Ana". The engine fills its tokens when it reads it. | | `description` | `string` | yes | | The entity's description, a line or two the player reads, with its tokens filled as the name's are. | | `image` | `string` | yes | | The entity's picture, a path in the game's `art/` folder or a URL, read through `artSrc`. | | `tags` | `string[]` | yes | | The entity's tags, after its kind's, which a UI or a plugin can sort or filter it by. | | `visible` | [`Condition`](#condition) | yes | | The entity's visibility condition, asked with `'$'` as it, which narrows its kind's `listed`. Always visible if left out. | | `stats` | `Record` | yes | | The entity's starting stats, where they differ from each stat's `start`. | | `kv` | `Record` | yes | | The entity's starting kv keys. | | `traits` | `{ [K in keyof` [`TraitRegistry`](#traitregistry)`]?: Partial<`[`TraitRegistry`](#traitregistry)`[K]> } & Record` | yes | | The entity's traits, by trait id, such as `{ 'laundry/washable': { temp: 30 } }`. They go over its kind's and under a content `traits` row for the entity, and an object merges with its kind's field by field. | | `ui` | [`Ui`](#ui)`<`[`EntityUi`](#entityui)`>` | yes | | The entity's ui hints, laid over its kind's field by field and carried to the view. See `EntityUi`. | ## entityDescription [#entitydescription] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#entitydescription). Returns an entity's description with its tokens filled, or undefined when it has none. ```ts shape import { entityDescription, type Game } from '@ifloom/engine' function entityDescription(state: GameState, game: Game, ref: string): string | undefined ``` Uses: [`GameState`](#gamestate), [`Game`](#game). ## entityImage [#entityimage] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#entityimage). Returns an entity's picture before `artSrc`, the one it was made with, else its definition's, else its `like`'s. ```ts shape import { entityImage, type Game } from '@ifloom/engine' function entityImage(state: GameState, game: Game, ref: string): string | undefined ``` Uses: [`GameState`](#gamestate), [`Game`](#game). ## entityKv [#entitykv] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#entitykv). Returns an entity's kv store, the keys of its `like` and then its definition's, with the keys play set laid over them. ```ts shape import { entityKv, type Game } from '@ifloom/engine' function entityKv(state: GameState, game: Game, ref: string): Record ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`KvValue`](#kvvalue). ## entityName [#entityname] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#entityname). Returns an entity's name with its tokens filled, the name it was created with or else its definition's. Returns the entity's id when it has neither. ```ts shape import { entityName, type Game } from '@ifloom/engine' function entityName(state: GameState, game: Game, ref: string): string ``` Uses: [`GameState`](#gamestate), [`Game`](#game). ## entityOf [#entityof] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#entityof). Returns the save's record of an entity, or `{}` for a declared one play hasn't changed. Returns undefined when the entity isn't in the game. ```ts shape import { entityOf, type Game } from '@ifloom/engine' function entityOf(state: GameState, game: Game, ref: string): EntityState | undefined ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`EntityState`](#entitystate). ## EntityRef [#entityref] Type. Explained in [Common types](https://ifloom.dev/docs/reference/common#entityref). A reference to an entity, its kind and its id joined by `:`, such as `'staff:ana'`. A bare id or a typo with no `:` fails to compile where a reference is wanted. Inside an `each` or a `count`'s `where`, content writes `'$'` for the entity being looked at, in fields typed as plain strings. ```ts shape import type { EntityRef } from '@ifloom/engine' type EntityRef = `${string}:${string}` ``` ## EntityState [#entitystate] Type. Explained in [Entities](https://ifloom.dev/docs/reference/entities#entitystate). The state a save keeps for one entity, only the fields play changed. A declared entity has no record until play changes it, and reads every other field from content. ```ts shape import type { EntityState } from '@ifloom/engine' type EntityState = { name?: string description?: string image?: string like?: EntityRef tags?: string[] traitData?: Record stats?: Stats kv?: Record traits?: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | yes | | The name the entity was made with in play. The engine reads a declared entity's name from content. | | `description` | `string` | yes | | The description the entity was made with in play. | | `image` | `string` | yes | | The picture the entity was made with in play. | | `like` | [`EntityRef`](#entityref) | yes | | The entity the entity was made like. The fields it doesn't have itself (name, description, picture, tags, stats, kv and traits), the engine reads from that one. | | `tags` | `string[]` | yes | | The tags the entity was made with, after its kind's and its `like`'s. | | `traitData` | `Record` | yes | | The trait data the entity was made with, by trait id, over its `like`'s or its kind's. Its traits' state is in `traits`. | | `stats` | [`Stats`](#stats) | yes | | The entity's stats changed in play, by id. The engine reads the others from its definition, then from the stat's `start`. | | `kv` | `Record` | yes | | The entity's kv keys set in play. The engine reads the others from its definition. | | `traits` | `Record` | yes | | The state of the entity's traits that keep one, by trait id, once play changed it. See `traitState`. | ## entityTags [#entitytags] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#entitytags). Returns an entity's tags, its kind's, then its `like`'s, then its own, each once. ```ts shape import { entityTags, type Game } from '@ifloom/engine' function entityTags(state: GameState, game: Game, ref: string): string[] ``` Uses: [`GameState`](#gamestate), [`Game`](#game). ## EntityUi [#entityui] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#sceneui-choiceui-blockui-entityui-statui-and-gameui). The ui hints a kind takes for each of its entities, and an entity takes over its kind's. The engine declares none, and a UI package augments this interface with its own. ```ts shape import type { EntityUi } from '@ifloom/engine' type EntityUi = { // … } ``` Plugins add fields of their own to it, which their pages list. ## EntityView [#entityview] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#entitiesview-and-entityview). An entity as the player sees it, in an `EntitiesView`'s `entries`. ```ts shape import type { EntityView } from '@ifloom/engine' type EntityView = { id: string ref: string name: string description: string | null image: string | null tags: string[] flags: Record stats: StatView[] kv: Record ui?: Ui } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The entity's id within its kind. | | `ref` | `string` | | | The entity's reference, such as `'staff:ana'`. | | `name` | `string` | | | The entity's name, with its prose tokens filled in. | | `description` | `string \| null` | | | The entity's description, with its tokens filled in. Null if it has none. | | `image` | `string \| null` | | | The entity's picture, as a path through `artSrc`. Null if it has none. | | `tags` | `string[]` | | | The entity's tags, its kind's first and then its own. | | `flags` | `Record` | | | The answer to each of the kind's `flags` for this entity, by name. Empty when the kind declares none. | | `stats` | [`StatView[]`](#statview) | | | The kind's listed stats the player can see on this entity, in the order the game declares them. | | `kv` | `Record` | | | The entity's kv store as it reads now, its declared keys with play's changes over them. | | `ui` | [`Ui`](#ui)`<`[`EntityUi`](#entityui)`>` | yes | | The entity's ui hints (a `EntityUi`), its own over its kind's, kept as written. Left out if it has none. | ## explain [#explain] Function. Explained in [Conditions](https://ifloom.dev/docs/reference/conditions#explain). Returns the `Explanation` of a condition against a state, part by part. An undefined condition always holds. ```ts shape import { explain, type Game } from '@ifloom/engine' function explain(state: GameState, game: Game, condition: Condition | undefined): Explanation ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`Condition`](#condition), [`Explanation`](#explanation). ## explainText [#explaintext] Function. Explained in [Conditions](https://ifloom.dev/docs/reference/conditions#explaintext). Returns an `Explanation` as indented lines with ✓ or ✗ on each, for a log or a debug panel. ```ts shape import { explainText } from '@ifloom/engine' function explainText(explanation: Explanation, depth?: number): string ``` Uses: [`Explanation`](#explanation). ## Explanation [#explanation] Type. Explained in [Conditions](https://ifloom.dev/docs/reference/conditions#explanation). A condition's tree with each part marked as holding or not, returned by `explain`. Each leaf says what it read and what it wanted. It answers the question authors ask most, why a choice is refused or missing. ```ts shape import type { Explanation } from '@ifloom/engine' type Explanation = { holds: boolean why: string parts?: Explanation[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `holds` | `boolean` | | | True when this part of the condition holds. | | `why` | `string` | | | The part's one line, saying what it checked and what it found. | | `parts` | [`Explanation[]`](#explanation) | yes | | The parts of an `all`, `any` or `not`, each explained. | ## FileRef [#fileref] Type. Explained in [Checking content](https://ifloom.dev/docs/reference/checks#fileref). A file the game names, with the place that names it. Its `path` is the one the page asks for, after `artSrc` or `audioSrc`. ```ts shape import type { FileRef } from '@ifloom/engine' type FileRef = { path: string type: 'picture' | 'video' | 'audio' where: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `path` | `string` | | | The file's path, as the page asks for it. | | `type` | `'picture' \| 'video' \| 'audio'` | | | The file's type. | | `where` | `string` | | | The place the content names the file, written as a `Problem`'s `where` is. | ## FillPart [#fillpart] Type. Explained in [Saves](https://ifloom.dev/docs/reference/saves#fillpart). A part of the state `MigrationTools.fill` can fill, named by the feature that fills it. The parts are the player's stats (start values), kv keys (the content's starting kv and per-turn resets) and play settings (defaults). ```ts shape import type { FillPart } from '@ifloom/engine' type FillPart = | 'kv' | 'settings' | 'stats' ``` ## fillTokens [#filltokens] Function. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#filltokens). Returns `text` with its `{{…}}` tokens filled for this state. An unset bare name prints nothing, and any other token that names nothing stays as written, so the missing name shows on screen. The tokens are these: - `{{name}}` reads one of the game's phrases (content's `phrases`, with `.` between groups: `{{outfit.verdict}}`), then a value in `rules.values`, then a kv key such as `{{playerName}}`. - `{{plugin/name}}` reads a plugin's value, with any arguments after the name (`{{messages/unread channel=texts}}`). - `{{kv:key of=storyline:baker}}` reads a key in another kv store. - `{{v:game/name}}` and `{{v:plugin/name}}` are the older way to write a value, and still work. A token can end in `|` and the words shown while it is unset, as in `{{flatmateName|Your flatmate}}`. A token is unset when its kv key is missing or not text or a number, no row of its phrase holds, no one has its value, or its value is `''`. The fallback is shown as written, with no tokens filled. The engine never reads a token's printed words for tokens again, but it fills a phrase's own words when it prints the phrase. ```ts shape import { fillTokens, type Game } from '@ifloom/engine' function fillTokens(state: GameState, game: Game, text: string): string ``` Uses: [`GameState`](#gamestate), [`Game`](#game). ## FlowChoice [#flowchoice] Type. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#flowchoice). A choice at a decision, a `Choice` with the blocks the flow shows once the player chooses it. ```ts shape import type { FlowChoice } from '@ifloom/engine' type FlowChoice = { id: string label?: string labels?: { when?: Condition; label: string }[] when?: Condition blocked?: Blocked[] cost?: ActionCost effects?: EffectRef[] command?: CommandRef once?: Once tags?: string[] irreversible?: string ui?: Ui then?: Block[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The choice's or action's id, unique among its scene's choices or among the actions. | | `label` | `string` | yes | | The button's words, with tokens filled, such as `'Order a tea'`. A choice with no label shows its id, and an action with none is never rendered as a button. | | `labels` | `{ when?:` [`Condition`](#condition)`; label: string }[]` | yes | | The button's words that depend on the state, such as "Not today" before you have bought it and "Right." after. The first entry whose `when` holds wins, and `label` is the fallback. | | `when` | [`Condition`](#condition) | yes | | The condition under which the choice or action is offered and can be taken. Always, if left out. | | `blocked` | [`Blocked[]`](#blocked) | yes | | The rules that refuse it for now. The first entry whose `when` holds greys the button out with its reason, or leaves it off with `hide`. | | `cost` | [`ActionCost`](#actioncost) | yes | | The stats it spends. The engine checks them before it runs, lists them on the button and pays them after its command. | | `effects` | [`EffectRef[]`](#effectref) | yes | | The effects it applies after its cost, in order. A plugin's or the game's effect in the short form does computed work. | | `command` | [`CommandRef`](#commandref) | yes | | The command the choice or action sends first, a plugin's in the short form or one of the engine's, but never `choose`. The button is refused with that command's reason while the command would be. An example is `{ 'devices/open': { id: 'messages' } }`. The button's price includes what the command spends. | | `once` | [`Once`](#once) | yes | | The limit of once a game (`{ per: 'game' }`) or once a turn (`{ per: 'turn' }`), counted in `state.chosen`. Once spent, a choice stays on screen and pays nothing more, and an action is refused, both with `reason`. The choice's limit of once a game or once a turn. See `Once`. | | `tags` | `string[]` | yes | | The tags a UI can style or filter it by. The engine gives them no meaning. | | `irreversible` | `string` | yes | | The warning that it can't be undone, which a UI shows on the button. | | `ui` | [`Ui`](#ui)`<`[`ChoiceUi`](#choiceui)`>` | yes | | The ui hints carried to its button in the view. See `ChoiceUi`. | | `then` | [`Block[]`](#block) | yes | | The blocks shown once the choice is chosen. The flow then carries on after the decision, or from its `{ point }` effect's point. | ## FlowState [#flowstate] Type. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#flowstate). The visit a save keeps for the open scene, with its path so far and the wait the flow stands at. The engine reads the scene's body from content. ```ts shape import type { FlowState } from '@ifloom/engine' type FlowState = { scene: string path: FlowStep[] waiting: { minigame: string } | { panel: string } | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `scene` | `string` | | | The id of the scene the visit is of. | | `path` | [`FlowStep[]`](#flowstep) | | | The visit's steps in order, the choices made, the points jumped to and the minigames and panels done with. The view replays them to render the visit. | | `waiting` | `{ minigame: string } \| { panel: string } \| null` | | | The minigame being played or the panel open where the flow stands, until it's done. Null while the flow waits on neither. | ## FlowStep [#flowstep] Type. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#flowstep). A step of a visit's path in `state.flow`, kept in the order the steps came. `{ chose }` is a choice at a decision or among the ending choices, `{ point }` a jump a choice made, and `{ minigame }` or `{ panel }` a wait done with. ```ts shape import type { FlowStep } from '@ifloom/engine' type FlowStep = { chose: string } | { point: string } | { minigame: string } | { panel: string } ``` ## fold [#fold] Function. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#fold). Returns a fold, a section the player can open and shut under `label`, such as a letter to read. A UI without the `fold` hint shows the blocks open. A fold is presentation only, a section with the React UI's `fold` hint, and keeps no state. ```ts shape import { fold } from '@ifloom/engine' function fold(label: string, blocks: Block[], extras?: BlockExtras): Block ``` Uses: [`Block`](#block), [`BlockExtras`](#blockextras). ## Formula [#formula] Type. Explained in [Stats](https://ifloom.dev/docs/reference/stats#formula). A formula a derived stat declares in its `derive`, to work the stat out from other stats. A number is itself, and a string is another stat's value. For a stat with `of`, a string names the same entity's stat. The other forms combine formulas: - `{ sum: [...] }`, `{ product: [...] }`, `{ min: [...] }` and `{ max: [...] }` combine a list. - `{ scale: f, by: n }` is f times n. - `{ clamp: f, min?, max? }` holds f between the two. ```ts shape import type { Formula } from '@ifloom/engine' type Formula = number | string | { sum: Formula[] } | { product: Formula[] } | { min: Formula[] } | { max: Formula[] } | { scale: Formula; by: number } | { clamp: Formula; min?: number; max?: number } ``` ## Game [#game] Type. Explained in [The game](https://ifloom.dev/docs/reference/game#game). A loaded game, the core's fields and each feature's. `loadGame` makes it from the base, the content and the packs. ```ts fragment type Game = { id: string title: string version?: number packs?: string[] prose?: ProseStore rules?: GameRules strings?: Record plugins?: readonly Plugin[] receivers?: readonly string[] data?: Record> kinds?: KindDef[] entities?: EntityDef[] traits?: TraitTable player?: PlayerDef | undefined kv?: Record resets?: Record storylines?: StorylineDef[] actions?: ActionDef[] triggers?: TriggerDef[] inputs?: InputDef[] settings?: SettingDef[] stats?: StatDef[] introScene?: string scenes: DataScene[] minigames?: MinigameDef[] timers?: TimerDef[] audio?: GameAudio media?: GameMedia ui?: Ui saveable?: Blocked[] locks?: Lock[] phrases?: Record changes?: ChangesDef carryOver?: CarryOver finished?: Condition credits?: CreditGroup[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The game's id. Saves and packs record it, so a save from another game is refused. | | `title` | `string` | | | The game's title, which a title page shows. | | `version` | `number` | yes | | The game's own version, a whole number from 1. Saves record it, and `rules.migrations` carry an older save forward. 1 if left out. Declaring it also stops the engine filling new stats, settings and entities into old saves by itself, so your migration steps fill them with `tools.fill()`. | | `packs` | `string[]` | yes | | The ids of the packs the game was loaded with, in order. Saves record them, and the game's own content has no id. | | `prose` | [`ProseStore`](#prosestore) | yes | | The game's prose keys and variants lists, with their weights. `loadGame` makes it from the content's `prose`. | | `rules` | [`GameRules`](#gamerules) | yes | | The game's own code, its hooks, providers and the calls content makes as `game/`. See `GameRules`. | | `strings` | `Record` | yes | | The game's lines in place of the engine's and plugins' strings, by key, such as `{ finishFirst: 'Not yet.', 'quests/notDoing': 'Not on your list.' }`. Packs can add theirs, and a later pack's line wins. | | `plugins` | `readonly` [`Plugin`](https://ifloom.dev/docs/api/engine-plugin#plugin)`[]` | yes | | The plugins the game is built with, in the order their hooks run. | | `receivers` | `readonly string[]` | yes | | The order the `receive` effect asks the plugins that keep things, by plugin id. The order of `plugins` if left out. `['wardrobe', 'inventory']` sends clothes to the wardrobe and the rest to the inventory. | | `data` | `Record>` | yes | | The plugins' content, by plugin id and then list, such as `data.quests.quests`. `loadGame` merges packs' entries by id, as it does scenes. | | `kinds` | [`KindDef[]`](#kinddef) | yes | | The game's kinds, the sorts of entity it keeps, each with its own stats. | | `entities` | [`EntityDef[]`](#entitydef) | yes | | The game's entities at the start. Play can create more. | | `traits` | [`TraitTable`](#traittable) | yes | | The game's traits, by trait id and then entity. In content given to `loadGame` they're rows over what entities declare. On the game `loadGame` returns, they're every entity's traits, worked out. Read them with `declaredTrait`. | | `player` | `PlayerDef \| undefined` | yes | | The game's player, such as their picture beside their own spoken lines. | | `kv` | `Record` | yes | | The kv store a new game starts with, such as the stretch it opens in, `{ phase: 'arrival' }`. | | `resets` | `Record` | yes | | The keys the engine puts back at the start of each turn, with the value each goes back to. Use them to count something once a turn. | | `storylines` | [`StorylineDef[]`](#storylinedef) | yes | | The game's storylines, threads of story each with its own kv store, which a `closeStoryline` effect rests for some turns. None if left out. | | `actions` | [`ActionDef[]`](#actiondef) | yes | | The game's actions, by id. None if left out. An action with a `label` is a button in the room while no scene is open, and one with no label is done only by `{ type: 'action', id }`. | | `triggers` | [`TriggerDef[]`](#triggerdef) | yes | | The game's triggers, effects that run by themselves the first time a condition holds. They fire in this order. | | `inputs` | [`InputDef[]`](#inputdef) | yes | | The game's inputs, the fields the player fills in, each writing a kv key. | | `settings` | [`SettingDef[]`](#settingdef) | yes | | The game's settings, which the player changes from a settings page. None if left out. | | `stats` | [`StatDef[]`](#statdef) | yes | | The game's stats. The engine has none of its own. | | `introScene` | `string` | yes | | The scene open on the first frame. The game opens on the room if left out. | | `scenes` | [`DataScene[]`](#datascene) | | | The game's scenes, as data. | | `minigames` | [`MinigameDef[]`](#minigamedef) | yes | | The game's minigames. None if left out. | | `timers` | [`TimerDef[]`](#timerdef) | yes | | The game's timers. None if left out. | | `audio` | [`GameAudio`](#gameaudio) | yes | | The game's tracks and channels. No audio if left out. | | `media` | [`GameMedia`](#gamemedia) | yes | | The game's pools of pictures and videos. None if left out. | | `ui` | [`Ui`](#ui)`<`[`GameUi`](#gameui)`>` | yes | | The game's ui hints, such as how every screen comes in. The engine carries them to the view as written and gives them no meaning. | | `saveable` | [`Blocked[]`](#blocked) | yes | | The game's reasons to refuse saving, as `blocked` entries refused while their `when` holds. The first entry that holds gives the reason, and saving is always allowed if left out. | | `locks` | [`Lock[]`](https://ifloom.dev/docs/api/engine-plugin#lock) | yes | | The game's locks, checked in order. The first one that stops a command gives the reason. | | `phrases` | `Record` | yes | | The game's phrases, by full dotted name (`outfit.verdict`), each as its rows or its rows with the arguments it takes. None if left out. | | `changes` | [`ChangesDef`](#changesdef) | yes | | The stats the engine tracks changes of, from the content and every pack together. Nothing is tracked if left out. | | `carryOver` | [`CarryOver`](#carryover) | yes | | The game's rules for a New Game+, the parts of the last game a new one keeps. `startingState`'s `carry` applies them. | | `finished` | [`Condition`](#condition) | yes | | The game's condition for being finished. The runner records the first time it holds in the profile's `core:finished`, so a title page can offer New Game+. | | `credits` | [`CreditGroup[]`](#creditgroup) | yes | | The game's credits, in groups, in the order they were first declared. None if left out. | ## GameAudio [#gameaudio] Type. Explained in [Audio](https://ifloom.dev/docs/reference/audio#gameaudio). The audio the game declares in `audio`, its tracks, the channels they play on and the settings that set their volume. ```ts shape import type { GameAudio } from '@ifloom/engine' type GameAudio = { tracks: Record channels?: Record mute?: string sound?: string default?: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `tracks` | `Record` | | | The game's tracks and playlists, by id, each a file with its volume or a list of tracks to play in turn. | | `channels` | `Record` | yes | | The game's channels, merged over the defaults, `music` and `ambience` (background) and `sfx` and `voice` (cue). | | `mute` | `string` | yes | | The id of the ui setting, a toggle, that mutes everything while it's on, such as a "Mute" box. | | `sound` | `string` | yes | | The id of the ui setting, a toggle, that plays sound only while it's on, such as a "Sound" box. It's the reverse of `mute`. | | `default` | `Record` | yes | | The track each background channel plays when nothing else sets one, by channel. | ## GameBase [#gamebase] Type. Explained in [Content and packs](https://ifloom.dev/docs/reference/content#gamebase). The base `loadGame` takes beside the content, the game's `id`, `title`, `version`, `plugins` and `rules`. Anything a mod could change goes in the content or a pack instead. ```ts shape import type { GameBase } from '@ifloom/engine' type GameBase = { id: string title: string version?: number plugins?: readonly Plugin[] receivers?: readonly string[] rules?: GameRules } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The game's id. Saves and packs record it, so a save from another game is refused. | | `title` | `string` | | | The game's title, which a title page shows. | | `version` | `number` | yes | | The game's own version, a whole number from 1. Saves record it, and `rules.migrations` carry an older save forward. 1 if left out. Declaring it also stops the engine filling new stats, settings and entities into old saves by itself, so your migration steps fill them with `tools.fill()`. | | `plugins` | `readonly` [`Plugin`](https://ifloom.dev/docs/api/engine-plugin#plugin)`[]` | yes | | The plugins the game is built with, in the order their hooks run. | | `receivers` | `readonly string[]` | yes | | The order the `receive` effect asks the plugins that keep things, by plugin id. The order of `plugins` if left out. `['wardrobe', 'inventory']` sends clothes to the wardrobe and the rest to the inventory. | | `rules` | [`GameRules`](#gamerules) | yes | | The game's own code, its hooks, providers and the calls content makes as `game/`. See `GameRules`. | ## GameMedia [#gamemedia] Type. Explained in [Media](https://ifloom.dev/docs/reference/media#gamemedia). The media the game declares in `media`, pools of pictures and videos by id. ```ts shape import type { GameMedia } from '@ifloom/engine' type GameMedia = { pools?: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `pools` | `Record` | yes | | The game's pools, named lists of files content draws from, as in `[[img:@door\|night]]` or `{ pool: 'door', tags: ['night'] }`. | ## GameRules [#gamerules] Type. Explained in [Rules and hooks](https://ifloom.dev/docs/reference/rules#gamerules). The game's own code, a plain object with the members a plugin has. Content calls its members with `game` as the plugin id, such as the condition `{ 'game/tired': true }`. The engine runs it as the plugin `game`, before every other plugin, with the same context (`PluginContext`, and `TurnContext` for the turn hooks). Its `slice`, `get` and `set` read and write the game's own state when it has a `start`. Every member is optional and means what a plugin's does (see `Plugin`), except `migrations`, which carry the whole save from one version of the game to the next. A plugin's id, versions, content, strings and data are the game's own content, so `GameRules` leaves them out. Locks and per-turn resets are content too, in `locks` and `resets`. Its `calls`, declared with `defineCalls('game', …)` and passed through `defineRules`, type its members' arguments and let the content checker check every `game/` call against them. ```ts shape import type { GameRules, Game } from '@ifloom/engine' type GameRules = { conditions?: Record) => boolean> effects?: Record) => GameState> view?: ((state: GameState, context: PluginContext) => unknown) references?: PluginReferences commands?: Record> traits?: readonly TraitDef[] actions?: ((state: GameState, context: PluginContext) => readonly ButtonDef[] | undefined) audio?: ((state: GameState, context: PluginContext) => Record | undefined) scene?: ((state: GameState, context: PluginContext) => RoomScene | undefined) action?: ((state: GameState, id: string, context: PluginContext) => ButtonDef | undefined) label?: ((state: GameState, context: PluginContext) => string | undefined) start?: ((game: Game) => S) values?: Record) => string | number> calls?: AnyCalls macros?: Record> queries?: Record) => unknown> statModifiers?: ((state: GameState, context: PluginContext) => readonly StatModifier[] | undefined) onTurn?: ((state: GameState, context: TurnContext) => GameState) onTurnDone?: ((state: GameState, context: TurnContext) => GameState) onStat?: ((before: GameState, after: GameState, stat: string, by: number, context: PluginContext) => GameState) onCommand?: ((before: GameState, after: GameState, context: PluginContext) => GameState) guard?: ((state: GameState, asked: Asked, context: PluginContext) => Refusal | undefined) price?: ((state: GameState, effects: readonly Effect[], context: PluginContext) => string[] | undefined) saveName?: ((state: GameState, context: PluginContext) => string | undefined) profile?: ((state: GameState, previous: GameState, stored: unknown, context: PluginContext) => unknown) check?: (game: Game, tools: CheckTools) => PluginProblem[] migrations?: Record GameState> } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `conditions` | `Record) => boolean>` | yes | | The plugin's conditions content can test, by name without the prefix. | | `effects` | `Record) =>…` | yes | | The plugin's effects content can apply, by name without the prefix. Each takes the state the effects before it left and returns the next one, so two in one list compose. Prices and guards can't see what an effect does until it runs. An effect that only stands for other effects belongs in `macros` instead. | | `view` | `((state:` [`GameState`](#gamestate)`, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`) => unknown)` | yes | | Returns the plugin's view, which a UI reads at `view.plugins[id]`. Declare its type `V` in `ViewRegistry` under the plugin's id, and every view types `view.plugins[id]` as `V`. | | `references` | [`PluginReferences`](https://ifloom.dev/docs/api/engine-plugin#pluginreferences) | yes | | The references the plugin's calls and content make, which the content checker resolves as it resolves the engine's own. See `PluginReferences`. | | `commands` | `Record>` | yes | | The plugin's commands a choice or action can send, by name without the prefix. | | `traits` | `readonly` [`TraitDef`](https://ifloom.dev/docs/api/engine-plugin#traitdef)`[]` | yes | | The traits the plugin gives meaning to, each id the plugin's id, `/` and a name. A trait is data only, and the plugin's code decides what it does. Content writes them on a kind, an entity or content's `traits` table, and the plugin reads them with `traitOf` or `declaredTrait`. | | `actions` | `((state:` [`GameState`](#gamestate)`, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`) => readonly` [`ButtonDef[]`](#buttondef) `\| undefined)` | yes | | Returns the actions offered while no scene is open, such as a location's things to do. The view lists them before the game's own `actions`, rendered the same way. | | `audio` | `((state:` [`GameState`](#gamestate)`, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`) => Record \|…` | yes | | Returns the tracks the plugin plays on background channels, by channel, such as a location's ambience. Null silences a channel, and the first plugin that names a channel wins it. A plugin's track is below an open scene's and an `audio` effect's, and above the game's default. A channel left out is the next plugin's, then the default's. | | `scene` | `((state:` [`GameState`](#gamestate)`, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`) =>` [`RoomScene`](https://ifloom.dev/docs/api/engine-plugin#roomscene) `\| undefined)` | yes | | Returns the `RoomScene` the screen shows while no scene is open, such as a location's description or a dashboard's heading. The first plugin that answers fills it. With none, the room shows the game's title and its actions. | | `action` | `((state:` [`GameState`](#gamestate)`, id: string, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`) =>` [`ButtonDef`](#buttondef) `\| undefined)` | yes | | Returns one of the plugin's actions that isn't among its `actions` now, by id without the prefix, such as an app's. Undefined when there is none. `{ type: 'action', id: '/' }` runs it, as for an action with a cost or effects. Without this provider, the engine looks the id up among the plugin's `actions`. | | `label` | `((state:` [`GameState`](#gamestate)`, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`) => string \| undefined)` | yes | | Returns a few words on the time or place in the game for a header or a save, such as "Day 3 · Wednesday morning". | | `start` | `((game:` [`Game`](#game)`) => S)` | yes | | Returns the plugin's state in a new game. A plugin with no state leaves it out. | | `values` | `Record) => string…` | yes | | The plugin's values, words and numbers content reads by name with arguments, as a condition is asked. Prose prints one as `{{id/name channel=texts}}`, and an `Amount` reads one as `{ value: 'id/name', with }`. | | `calls` | [`AnyCalls`](https://ifloom.dev/docs/api/engine-plugin#anycalls) | yes | | The declaration of the plugin's conditions, effects and commands, each with the arguments it takes, from `defineCalls`. Every declared call needs an implementation, and every implementation a declaration. The implementations get their arguments read by it. The content checker reports a call that leaves an argument out, gets one wrong or names something the game lacks, and a translation reaches the words in a call's arguments. | | `macros` | `Record>` | yes | | The plugin's macros, effects that stand for other effects, by name without the prefix. A name is an effect's or a macro's, never both. Content calls one as any effect. It returns the effects it stands for, worked out from the state, so a button's price and the guards see what it would do. See `Macro`. | | `queries` | `Record) => unknown>` | yes | | The plugin's queries, answers other plugins ask for by name without importing it, such as `context.query('calendar/whenNext', { when })`. A query answers what a condition's yes or no can't, such as a location, a time or a list. | | `statModifiers` | `((state:` [`GameState`](#gamestate)`, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`) => readonly` [`StatModifier[]`](https://ifloom.dev/docs/api/engine-plugin#statmodifier) `\| undefined)` | yes | | Returns the changes to what the player's stats read now, worked out from the plugin's state, such as a timed boost. It must not read stats itself, or it reads itself. Nothing is written into the state. Every reading of the stat (conditions, derived stats, costs, the view) sees the changed value, and `stat` effects still write the kept value underneath. | | `onTurn` | `((state:` [`GameState`](#gamestate)`, context:` [`TurnContext`](https://ifloom.dev/docs/api/engine-plugin#turncontext)`) =>` [`GameState`](#gamestate)`)` | yes | | The hook run at the end of a turn, once the counter has moved on and `resets` are back. It returns the next state, and the hooks run in order, the game's first. `context.before` is the state as the turn ended, and a `turn` effect applied through `context.apply` does nothing. | | `onTurnDone` | `((state:` [`GameState`](#gamestate)`, context:` [`TurnContext`](https://ifloom.dev/docs/api/engine-plugin#turncontext)`) =>` [`GameState`](#gamestate)`)` | yes | | The hook run once every `onTurn` has run, so it sees their changes, such as the calendar's new day. It returns the next state and runs in the same order and context as `onTurn`. | | `onStat` | `((before:` [`GameState`](#gamestate)`, after:` [`GameState`](#gamestate)`, stat: string, by: number, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`<…` | yes | | The hook run when a `stat` effect changes one of the player's stats. `before` is the state before it, `after` the state with it, and `by` how far it moved. Return `before` to undo the change, `after` to keep it, or `after` with more changes. The hooks run in order, the game's first, each seeing what the one before returned. | | `onCommand` | `((before:` [`GameState`](#gamestate)`, after:` [`GameState`](#gamestate)`, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`) =>` [`GameState`](#gamestate)`)` | yes | | The hook run after every command that took, with the state before and the state after. It returns the next state, and its context is the state after. | | `guard` | `((state:` [`GameState`](#gamestate)`, asked:` [`Asked`](https://ifloom.dev/docs/api/engine-plugin#asked)`, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`) =>` [`Refusal`](https://ifloom.dev/docs/api/engine-plugin#refusal) `\| undefined)` | yes | | Returns a `Refusal` for a command, given the effects it would apply, or undefined to let it through. The engine asks it after the locks, of every command but the ones that ignore locks. | | `price` | `((state:` [`GameState`](#gamestate)`, effects: readonly` [`Effect[]`](#effect)`, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`) => string[] \|…` | yes | | Returns the plugin's words for what a button costs that the engine can't say, such as `['until evening']`. The engine asks it with the effects the button would apply. | | `saveName` | `((state:` [`GameState`](#gamestate)`, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`) => string \| undefined)` | yes | | Returns the name a save is listed under, such as the name the player typed. It is kept as `SaveMeta.playerName` and shown for `@you`'s lines. The first that answers names it, the game's first. With none, saves have no player name. | | `profile` | `((state:` [`GameState`](#gamestate)`, previous:` [`GameState`](#gamestate)`, stored: unknown, context:` [`PluginContext`](https://ifloom.dev/docs/api/engine-plugin#plugincontext)`) =>…` | yes | | Returns the value the plugin keeps in the player's profile, which outlives saves and new games, such as earned achievements. Return undefined to leave the stored value. The runner asks it after every command that took, with the state after, the state before and the value the plugin's profile namespace (its id) holds now. Only a runner with a `profile` asks, and `apply` never does. | | `check` | `(game:` [`Game`](#game)`, tools:` [`CheckTools`](https://ifloom.dev/docs/api/engine-plugin#checktools)`) =>` [`PluginProblem[]`](https://ifloom.dev/docs/api/engine-plugin#pluginproblem) | yes | | Returns the problems the plugin's own rules find that a reference can't express, such as two entries with one id or an exit to nowhere. The content checker runs it after the references. `tools` words problems with anything else the plugin names as the checker does. | | `migrations` | `Record` [`GameState`](#gamestate)`>` | yes | | The game's save migrations, keyed by the game `version` each upgrades from, so step 1 takes a version-1 save to version 2. A version with no step is carried forward unchanged. They run on the whole state when an older save loads, after the engine's and plugins' own migrations. | ## GameState [#gamestate] Type. Explained in [Game state](https://ifloom.dev/docs/reference/state#gamestate). The state a save keeps, the core's fields and each feature's. The engine reads definitions from content, so the save holds only what play changed. Each field declares its new-game value and load default once, in `FIELDS` or in its feature's `state`. ```ts shape import type { GameState, Notice } from '@ifloom/engine' type GameState = { version: typeof SAVE_VERSION seed: number plugins: Record gameVersion?: number entities: Record> created: Record removed: string[] you: EntityRef | null turn: number kv: Record storylines: Record notices: Notice[] fired: Record settings: Record stats: Stats sceneId: string | null seen: Record chosen: Record minigame: MinigameState | null flow: FlowState | null timers: Record audio: AudioState media: MediaState panel: OpenPanel | null rolls: RollsState changes: Change[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `version` | `typeof SAVE_VERSION` | | | The save format's version, `SAVE_VERSION`. `loadState` carries an older save forward. | | `seed` | `number` | | | The save's random seed, fixed when the game starts. Every seeded draw (variants, pools, rolls, storylets) mixes it in, so two games draw differently. | | `plugins` | `Record` | | | The plugins' own state, by plugin id. | | `gameVersion` | `number` | yes | | The game's own version (`game.version`) the save was made with. It is set only when the game declares a version, and a save without it counts as version 1. | | `entities` | `Record>` | | | The changes play has made to the game's entities, by kind and id, such as `entities.staff.ana`. A declared entity has no record until something changes it. An entity created in play has a record from the start. | | `created` | `Record` | | | The number of entities of each kind created in play, for the next one's id. | | `removed` | `string[]` | | | The references of declared entities removed in play. A `create` with the same id brings one back. | | `you` | [`EntityRef`](#entityref) `\| null` | | | The protagonist the player is playing, which `'you'` names. Null while the player plays themselves. | | `turn` | `number` | | | The number of turns that have passed, the engine's one clock. It starts at 0. The game decides how long a turn is (a day, an hour, a week or a chapter). The engine dates `seen`, `fired` and notices in turns. | | `kv` | `Record` | | | The player's kv store, keys with a true/false, number or text value. | | `storylines` | `Record` | | | The storylines a save keeps, by id, each with its kv store and the turn it stays closed until. | | `notices` | [`Notice[]`](#notice) | | | The notices the game has raised, oldest first. The state keeps the last 50. | | `fired` | `Record` | | | The turn each trigger last fired on, by trigger id. | | `settings` | `Record` | | | The value of each `play` setting the game declares, by id. | | `stats` | [`Stats`](#stats) | | | The player's stats, by id. An entity's stats are kept on the entity. | | `sceneId` | `string \| null` | | | The id of the open scene. Null while no scene is open and the room shows. | | `seen` | `Record` | | | The scenes the player has entered, by id, with a count and the first and last turn of each. Content can gate a chain of scenes on it without a kv key per link. Entering the scene that's already open, such as a hub rendered again after a choice, doesn't count. | | `chosen` | `Record` | | | The choices the player has chosen, by `scene#choice`, with a count and the first and last turn of each. Content can gate on an earlier decision with it, and a choice's `once` reads it. | | `minigame` | [`MinigameState`](#minigamestate) `\| null` | | | The minigame being played, or null. | | `flow` | [`FlowState`](#flowstate) `\| null` | | | The open scene's visit, each choice, jump and wait passed in order, and the wait the flow stands at. It starts again each time a scene is entered. Null while no scene is open, and for a visit with nothing to keep yet. | | `timers` | `Record` | | | The running timers, by id, in the order they started. | | `audio` | [`AudioState`](#audiostate) | | | The audio a save keeps, the tracks effects put on channels, the last sounds and the count of scenes entered. | | `media` | [`MediaState`](#mediastate) | | | The file each pool request was given, so a revisit and a reload show the same one. | | `panel` | [`OpenPanel`](#openpanel) `\| null` | | | The panel the `panel` effect opened over the story, or null. | | `rolls` | [`RollsState`](#rollsstate) | | | The rolls this save has made. | | `changes` | [`Change[]`](#change) | | | The stats the last command moved, in the order the game declares them, the player's first. A `tick` that moved nothing keeps the list from before it. | ## GameUi [#gameui] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#sceneui-choiceui-blockui-entityui-statui-and-gameui). The ui hints the whole game takes in its `ui`. The engine declares none, and a UI package augments this interface with its own. ```ts shape import type { GameUi } from '@ifloom/engine' type GameUi = { // … } ``` Plugins add fields of their own to it, which their pages list. ## hash [#hash] Function. Explained in [Randomness](https://ifloom.dev/docs/reference/random#hash). Returns a 32-bit unsigned hash of `text`. Texts that differ in one character give unrelated numbers. ```ts shape import { hash } from '@ifloom/engine' function hash(text: string): number ``` ## HelperRegistry [#helperregistry] Type. Explained in [The runner](https://ifloom.dev/docs/reference/runner#helperregistry). The registry of helper reports, by helper id, that a helper augments to type its own. It is empty until a helper augments it, as `startUnlocks` from `@ifloom/plugin-unlocks` does for `unlocks`. A helper types its report here as a plugin types its view in `ViewRegistry`. ```ts shape import type { HelperRegistry } from '@ifloom/engine' type HelperRegistry = { // … } ``` Plugins add fields of their own to it, which their pages list. ## HelpersIn [#helpersin] Type. Explained in [The runner](https://ifloom.dev/docs/reference/runner#helpersin). The helpers' reports, by helper id. Each report a helper declares in `HelperRegistry` is typed, and the rest are `unknown`. ```ts shape import type { HelpersIn } from '@ifloom/engine' type HelpersIn = { [key: string]: unknown // … } ``` Plugins add fields of their own to it, which their pages list. ## HistoryOptions [#historyoptions] Type. Explained in [The runner](https://ifloom.dev/docs/reference/runner#historyoptions). Settings for undo and redo. Undo is off unless `createRunner` is given these or `true`, and never steps back past a barrier these set. ```ts shape import type { HistoryOptions } from '@ifloom/engine' type HistoryOptions = { depth?: number stopAtIrreversible?: boolean stopAtNewTurn?: boolean stopWhen?: Condition } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `depth` | `number` | yes | | The number of steps back undo reaches. 50 if left out. | | `stopAtIrreversible` | `boolean` | yes | | The setting that stops undo at a choice marked `irreversible`. On unless set to false. | | `stopAtNewTurn` | `boolean` | yes | | The setting that stops undo at the start of a new turn. Off if left out. | | `stopWhen` | [`Condition`](#condition) | yes | | A condition that stops undo at any state where it holds, tested after each command. | ## holds [#holds] Function. Explained in [Conditions](https://ifloom.dev/docs/reference/conditions#holds). Returns true when `condition` holds in this state. An undefined condition always holds. The engine finds a condition's kind by its one key. A condition with no known key, or with two, never holds, and the content checker reports it. A range bound that is an `Amount` is worked out first, so the kind reads a number. ```ts shape import { holds, type Game } from '@ifloom/engine' function holds(state: GameState, game: Game, condition: Condition | undefined): boolean ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`Condition`](#condition). ## HotspotDef [#hotspotdef] Type. Explained in [Media](https://ifloom.dev/docs/reference/media#hotspotdef). A hotspot on a picture, a clickable area the UI renders as a button. It either sends `command` or chooses the open scene's choice `choice`. ```ts shape import type { HotspotDef } from '@ifloom/engine' type HotspotDef = { id: string rect: [ number, number, number, number ] label: string command?: CommandRef choice?: string when?: Condition layer?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The hotspot's id. | | `rect` | `[ number, number, number, number ]` | | | The hotspot's area, in percent of the picture, as `[x, y, width, height]` from the top left. | | `label` | `string` | | | The hotspot's label, which a screen reader reads and the tooltip shows. | | `command` | [`CommandRef`](#commandref) | yes | | The command the hotspot sends, written as an action's `command`. | | `choice` | `string` | yes | | The id of the open scene's choice the hotspot chooses. | | `when` | [`Condition`](#condition) | yes | | The hotspot's condition. The hotspot shows only while it holds. | | `layer` | `string` | yes | | The id of the layer the hotspot goes with. The hotspot shows only while that layer does. | ## HotspotView [#hotspotview] Type. Explained in [Media](https://ifloom.dev/docs/reference/media#hotspotview). A hotspot as the player sees it, in a `PictureView`'s `hotspots`. The UI renders it as a button over the picture. ```ts shape import type { HotspotView } from '@ifloom/engine' type HotspotView = { id: string rect: [ number, number, number, number ] label: string command: Command disabled?: string warning?: string layer?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The hotspot's id. | | `rect` | `[ number, number, number, number ]` | | | The hotspot's area, in percent of the picture, as `[x, y, width, height]` from the top left. | | `label` | `string` | | | The hotspot's label. | | `command` | [`Command`](#command) | | | The command pressing the hotspot sends, its own `command` or the command that chooses its `choice`. | | `disabled` | `string` | yes | | The reason the hotspot can't be pressed now, as on a button's `disabled`. Left out when it can. | | `warning` | `string` | yes | | The warning a plugin gives against pressing the hotspot, as on a button's `warning`. | | `layer` | `string` | yes | | The id of the layer the hotspot goes with. Left out for a hotspot on the whole picture. | ## image [#image] Function. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#image). Returns a `{ media }` block, a picture or a video at this place in the flow, such as `image('cafe/cup', { alt: 'A cup of tea' })`. ```ts shape import { image } from '@ifloom/engine' function image(src: string, media?: Omit & BlockExtras): Block ``` Uses: [`SceneMedia`](#scenemedia), [`BlockExtras`](#blockextras), [`Block`](#block). ## inlineChoices [#inlinechoices] Function. Explained in [The view](https://ifloom.dev/docs/reference/view#inlinechoices). Returns the choices and actions that a scene's or a room's beats hold inline, in the order they come. ```ts shape import { inlineChoices } from '@ifloom/engine' function inlineChoices(beats: readonly SceneBeat[]): RenderedChoice[] ``` Uses: [`SceneBeat`](#scenebeat), [`RenderedChoice`](#renderedchoice). ## inlineMarkup [#inlinemarkup] Function. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#inlinemarkup). Returns a line of prose cut at its inline markup (`[[act:…]]`, `[[tip:…]]`, `[[ui:…]]`, `**bold**`, `*italic*`). Returns null when it has none. Broken markup stays in the words as written, so it shows on screen, and the content checker reports it. Broken markup is markup with no id or key, a tooltip or UI piece with no words, a UI piece whose name isn't an id or that has an empty argument, or stars that don't close. A `\*` is a star shown unchanged, and bold and italics inside or around inline markup are not read. ```ts shape import { inlineMarkup } from '@ifloom/engine' function inlineMarkup(text: string): InlinePart[] | null ``` Uses: [`InlinePart`](#inlinepart). ## InlinePart [#inlinepart] Type. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#inlinepart). One piece of a line of prose as `inlineMarkup` reads it, told apart by its `type`. Each marked piece keeps its source in `markup`. ```ts shape import type { InlinePart } from '@ifloom/engine' type InlinePart = { type: 'text'; text: string } | { type: 'act'; id: string; text?: string; markup: string } | { type: 'tip'; key: string; text: string; markup: string } | { type: 'ui'; name: string; text: string; args: string[]; markup: string } | { type: 'bold'; text: string; markup: string } | { type: 'italic'; text: string; markup: string } ``` ## InlineSpan [#inlinespan] Type. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#inlinespan). One piece of a paragraph that holds inline markup, in a beat's `spans`, in order. Each piece is told apart by its `type`. ```ts shape import type { InlineSpan } from '@ifloom/engine' type InlineSpan = { type: 'text'; text: string } | { type: 'action'; text: string; choice: RenderedChoice } | { type: 'tip'; text: string; tip: string } | { type: 'bold'; text: string } | { type: 'italic'; text: string } | { type: 'ui'; name: string; text: string; args: string[] } ``` Uses: [`RenderedChoice`](#renderedchoice). ## InlineUi [#inlineui] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#inlineui). The UI pieces a UI renders inside a line of prose from `[[ui:name|words|arg|…]]`, by name. Each name maps to the arguments it takes after the words, as a tuple of text. The engine declares none, and a UI package augments this interface with its own: ```ts fragment declare module '@ifloom/engine' { interface InlineUi { modal: [key: string, title?: string] } } ``` The engine never reads it. The view's `{ type: 'ui' }` span has `name: string` and `args: string[]`, so a name no UI declared still comes through, and this interface only types a UI's components. ```ts shape import type { InlineUi } from '@ifloom/engine' type InlineUi = { // … } ``` Plugins add fields of their own to it, which their pages list. ## InlineUiArgs [#inlineuiargs] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#inlineuiargs). The arguments of the UI piece named `N`, as a UI package declared them in `InlineUi`. Any text when no package declared `N`. ```ts shape import type { InlineUiArgs } from '@ifloom/engine' type InlineUiArgs = N extends keyof InlineUi ? InlineUi[N] : readonly string[] ``` Uses: [`InlineUi`](#inlineui). ## InputDef [#inputdef] Type. Explained in [Inputs](https://ifloom.dev/docs/reference/inputs#inputdef). An input the game declares in `inputs`, a field the player fills in, such as a pet's name. The `input` command writes its value to a kv key and refuses one the declaration doesn't allow. ```ts shape import type { InputDef } from '@ifloom/engine' type InputDef = { id: string label: string type: 'text' | 'number' | 'choice' key?: string when?: Condition maxLength?: number min?: number max?: number options?: { value: KvValue; label: string }[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The input's id, which the `input` command names. | | `label` | `string` | | | The input's label, the name of the field the player fills in. | | `type` | `'text' \| 'number' \| 'choice'` | | | The input's type, `text` (typed words), `number` or `choice` (one of `options`). | | `key` | `string` | yes | | The kv key the input writes. The input's id if left out. | | `when` | [`Condition`](#condition) | yes | | The input's condition. The input is on offer only while it holds. | | `maxLength` | `number` | yes | | The most characters a `text` input takes, after trimming. 40 if left out. | | `min` | `number` | yes | | The lowest number a `number` input takes, included. No bound if left out. | | `max` | `number` | yes | | The highest number a `number` input takes, included. No bound if left out. | | `options` | `{ value:` [`KvValue`](#kvvalue)`; label: string }[]` | yes | | The values a `choice` input offers, each with the label the player reads. | ## InputView [#inputview] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#inputview). An input as the player sees it, in `view.inputs`. Only inputs whose `when` holds are listed. ```ts shape import type { InputView } from '@ifloom/engine' type InputView = { id: string label: string type: InputDef['type'] maxLength: number | null min: number | null max: number | null options: { value: KvValue; label: string }[] value: KvValue | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The input's id, which the `input` command names. | | `label` | `string` | | | The input's label, the name of the field. | | `type` | [`InputDef`](#inputdef)`['type']` | | | The input's type, `text`, `number` or `choice`. | | `maxLength` | `number \| null` | | | The most characters a `text` input takes, after trimming, 40 unless the input sets it. Null for a number or a choice. | | `min` | `number \| null` | | | The lowest number the input takes. Null with no bound, and for text or a choice. | | `max` | `number \| null` | | | The highest number the input takes. Null with no bound, and for text or a choice. | | `options` | `{ value:` [`KvValue`](#kvvalue)`; label: string }[]` | | | The values a `choice` input offers, each with its label. Empty for text or a number. | | `value` | [`KvValue`](#kvvalue) `\| null` | | | The value the input's kv key holds now. Null when it's unset. | ## inRange [#inrange] Function. Explained in [Conditions](https://ifloom.dev/docs/reference/conditions#inrange). Returns true when `value` is in the range, with each bound worked out in this state first. A range with no bounds holds above 0. So `{ gte: { stat: 'rent' } }` compares the value with the rent. ```ts shape import { inRange, type Game } from '@ifloom/engine' function inRange(state: GameState, game: Game, value: number, range: Range): boolean ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`Range`](#range). ## InstalledMod [#installedmod] Type. Explained in [Mods](https://ifloom.dev/docs/reference/mods#installedmod). A mod the player has added, as the mod store keeps it. ```ts shape import type { InstalledMod } from '@ifloom/engine' type InstalledMod = { id: string name: string version?: string description?: string enabled: boolean pack: Pack } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The mod's id. | | `name` | `string` | | | The mod's name, for a mods page. | | `version` | `string` | yes | | The mod's own version, as its author writes it. | | `description` | `string` | yes | | The mod's description, a line for a mods page. | | `enabled` | `boolean` | | | True when the mod is on. A mod that is off stays installed and is left out of the game. | | `pack` | [`Pack`](#pack) | | | The pack the mod adds, as the file wrote it, with its id set to `mod:`. `loadGame` upgrades it. | ## isUnique [#isunique] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#isunique). Returns true when the entity's kind is `unique`, so each entity is one particular someone or something. ```ts shape import { isUnique, type Game } from '@ifloom/engine' function isUnique(game: Pick, ref: string): boolean ``` Uses: [`Game`](#game). ## jump [#jump] Function. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#jump). Returns the jump effect `{ point: id }`, which carries the flow on from a point instead of after the choice's decision, once its `then` is done. A flow loops only this way, through a choice. It goes in a choice's `effects`, never its `then`: it's the same object as `point(id)`, so in a `then` it's a point. ```ts shape import { jump } from '@ifloom/engine' function jump(id: string): { point: string } ``` ## KindDef [#kinddef] Type. Explained in [Entities](https://ifloom.dev/docs/reference/entities#kinddef). A kind of entity the game declares in `kinds`, such as the staff of a café or the dishes on its menu. Each entity of the kind has its own stats and kv keys. So a stat declared with `of: 'staff'` belongs to each member of staff, not to the player. ```ts shape import type { KindDef } from '@ifloom/engine' type KindDef = { id: string label: string plural?: string unique?: boolean listed?: boolean | Condition tags?: string[] flags?: Record traits?: { [K in keyof TraitRegistry]?: Partial } & Record ui?: Ui } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The kind's id, the part before the `:` in each of its entity references. | | `label` | `string` | | | The kind's label for one entity, as the player reads it, such as "Member of staff". | | `plural` | `string` | yes | | The kind's label for more than one, such as "Staff". The `label` if left out. | | `unique` | `boolean` | yes | | The kind's unique mark. True when each entity is one particular thing that can hold others, such as a person, and false when its things stack, such as dishes. | | `listed` | `boolean \|` [`Condition`](#condition) | yes | | The kind's listing rule for the view, `true`, `false` or a condition asked of each entity with `'$'` as it. A game's kinds are listed if left out, and a plugin's are not. | | `tags` | `string[]` | yes | | The tags every entity of the kind has, before its own `tags`. | | `flags` | `Record` | yes | | The kind's flags, named conditions asked of each listed entity with `'$'` as it, such as `{ met: { 'cast/met': { character: '$' } } }`. The view answers them in each entity's `flags`. | | `traits` | `{ [K in keyof` [`TraitRegistry`](#traitregistry)`]?: Partial<`[`TraitRegistry`](#traitregistry)`[K]> } & Record` | yes | | The default traits of every entity of the kind, by trait id. An entity's own object for a trait is laid over this one field by field, and any other value replaces it whole. | | `ui` | [`Ui`](#ui)`<`[`EntityUi`](#entityui)`>` | yes | | The ui hints of every entity of the kind, under each entity's own. See `EntityUi`. | ## KvValue [#kvvalue] Type. Explained in [Common types](https://ifloom.dev/docs/reference/common#kvvalue). A value in the kv store, which is true or false, a number or text. ```ts shape import type { KvValue } from '@ifloom/engine' type KvValue = boolean | number | string ``` ## lackingLine [#lackingline] Function. Explained in [Stats](https://ifloom.dev/docs/reference/stats#lackingline). Returns the refusal for a cost the player can't cover, from the stat's `lacking`, else the `notEnough` string with the stat's label in lower case. ```ts shape import { lackingLine, type Game } from '@ifloom/engine' function lackingLine(game: Game, id: string, amount: number): string ``` Uses: [`Game`](#game). ## Loaded [#loaded] Type. Explained in [Content and packs](https://ifloom.dev/docs/reference/content#loaded). The result of `loadGame`, the merged game with its prose, its variants and the problems found. ```ts shape import type { Loaded, Game } from '@ifloom/engine' type Loaded = { game: Game prose: Record variants: Record problems: Problem[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `game` | [`Game`](#game) | | | The loaded game, ready to run. | | `prose` | `Record` | | | The game's prose keys' lines, merged from the content and the packs. | | `variants` | `Record` | | | The game's variants lists by name, each with its members' prose keys. | | `problems` | [`Problem[]`](#problem) | | | The problems with the content and the packs, each naming the one it came from. Empty when there are none. | ## LoadedSave [#loadedsave] Type. Explained in [Saves](https://ifloom.dev/docs/reference/saves#loadedsave). A save read back, with its state carried forward to this game through `loadState`. ```ts shape import type { LoadedSave } from '@ifloom/engine' type LoadedSave = { meta: SaveMeta state: GameState missingPacks: string[] missingPlugins: string[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `meta` | [`SaveMeta`](#savemeta) | | | The save's `SaveMeta`. | | `state` | [`GameState`](#gamestate) | | | The save's state, carried forward to this game's version through `loadState`. | | `missingPacks` | `string[]` | | | The ids of the mods the save was made with that the game wasn't loaded with, such as a mod since turned off. | | `missingPlugins` | `string[]` | | | The ids of the plugins the save was made with that this game does not have. The save keeps their state, unused. | ## loadGame [#loadgame] Function. Explained in [Content and packs](https://ifloom.dev/docs/reference/content#loadgame). Returns the game merged from the base, the content and then the packs in order, with every problem found. Each problem names the content or pack that brought it. The content checker (`checkGame`) checks the merged game. `loadGame` adds where each problem came from, and the problems with the content and packs themselves, such as a key declared twice or a key they can't hold. So a mod author reads "mod:spicier · scene allie.talk · choice kiss · unknown scene 'allie.snog'", not a stack trace. ```ts shape import { loadGame } from '@ifloom/engine' function loadGame(content: readonly Content[], base: GameBase, options?: LoadOptions): Loaded ``` Uses: [`Content`](#content), [`GameBase`](#gamebase), [`LoadOptions`](#loadoptions), [`Loaded`](#loaded). ## LoadOptions [#loadoptions] Type. Explained in [Content and packs](https://ifloom.dev/docs/reference/content#loadoptions). Settings for `loadGame`. A game loaded without them has no packs. ```ts shape import type { LoadOptions } from '@ifloom/engine' type LoadOptions = { packs?: readonly Pack[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `packs` | `readonly` [`Pack[]`](#pack) | yes | | The packs to load over the content, in order, each over the ones before, such as mods and unlocked content. | ## loadState [#loadstate] Function. Explained in [Saves](https://ifloom.dev/docs/reference/saves#loadstate). Returns a state from a save, a command log or a test made ready to play in this game. Returns a failed `Result` with a reason the player can read when it can't be. It runs the engine's own steps and each field's load default, then the plugins' migrations, then the game's migrations, and last fills in the values the game declares and the save lacks. ```ts shape import { loadState, type Game } from '@ifloom/engine' function loadState(raw: unknown, game: Game): Result ``` Uses: [`Game`](#game), [`Result`](#result), [`GameState`](#gamestate). ## MediaState [#mediastate] Type. Explained in [Media](https://ifloom.dev/docs/reference/media#mediastate). The media a save keeps, in `state.media`. The engine reads the pools from content. ```ts shape import type { MediaState } from '@ifloom/engine' type MediaState = { picks: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `picks` | `Record` | | | The file each pool request was given, by the key `pickKey` returns. | ## mediaType [#mediatype] Function. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#mediatype). Returns `'video'` for a file with a video extension (`.mp4`, `.webm`), else `'image'`. ```ts shape import { mediaType } from '@ifloom/engine' function mediaType(src: string): 'image' | 'video' ``` ## memoryDriver [#memorydriver] Function. Explained in [Saves](https://ifloom.dev/docs/reference/saves#memorydriver). Returns a `SaveDriver` that keeps saves in memory, gone when the page is. Use it for tests and previews. ```ts shape import { memoryDriver } from '@ifloom/engine' function memoryDriver(): SaveDriver ``` Uses: [`SaveDriver`](#savedriver). ## MigrationTools [#migrationtools] Type. Explained in [Saves](https://ifloom.dev/docs/reference/saves#migrationtools). The tools a step of `rules.migrations` or a plugin's `migrations` gets beside the state. ```ts shape import type { MigrationTools, Game } from '@ifloom/engine' type MigrationTools = { game: Game fill: (parts?: FillPart[]) => GameState } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `game` | [`Game`](#game) | | | The game the save is loading into, for a step that reads its content, such as the entity an old id now names. | | `fill` | `(parts?:` [`FillPart[]`](#fillpart)`) =>` [`GameState`](#gamestate) | | | Returns the state the step was given, with the values the game declares and the save lacks filled in. It fills the parts asked for, or every part if left out. A migration fills nothing unless its step calls this. See `FillPart`. | ## minigame [#minigame] Function. Explained in [Commands](https://ifloom.dev/docs/reference/commands#minigame). Returns a `{ minigame }` block, a minigame played at this place in the flow. The flow waits until it ends, then carries on. ```ts shape import { minigame } from '@ifloom/engine' function minigame(id: string, extras?: BlockExtras): Block ``` Uses: [`BlockExtras`](#blockextras), [`Block`](#block). ## MinigameDef [#minigamedef] Type. Explained in [Minigames](https://ifloom.dev/docs/reference/minigames#minigamedef). A minigame the game declares in `minigames`, a small state machine played with named inputs and timed by ticks. Every key it uses must be in its `kv`. ```ts shape import type { MinigameDef } from '@ifloom/engine' type MinigameDef = { id: string title?: string start: string kv?: Record keys?: Record states: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The minigame's id, which the `minigame` effect and a scene's `minigame` name. | | `title` | `string` | yes | | The minigame's title. | | `start` | `string` | | | The id of the state the minigame starts in. | | `kv` | `Record` | yes | | The minigame's kv store, with each key's starting number, such as `{ score: 0 }`. Content reads and writes the keys with `of: 'minigame'`. | | `keys` | `Record` | yes | | The keys a UI maps to each input, by input name, such as `{ up: ['ArrowUp', 'w'] }`. Key names are those `KeyboardEvent.key` gives, and a UI picks its own if left out. | | `states` | `Record` | | | The minigame's states, by name. | ## MinigameInput [#minigameinput] Type. Explained in [Minigames](https://ifloom.dev/docs/reference/minigames#minigameinput). An input of the running minigame as the player sees it, in `view.minigame.inputs`. It has what a `RenderedChoice` needs, so a UI renders it as any button. ```ts shape import type { MinigameInput } from '@ifloom/engine' type MinigameInput = { id: string label: string command: { type: 'minigame'; input: string } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The input's name, as the minigame's `on` names it, such as `'up'`. | | `label` | `string` | | | The input's label, from its `on` entry, else the `minigame.` string (`Up`, `Space`), else its name with a capital. | | `command` | `{ type: 'minigame'; input: string }` | | | The command pressing the input sends. | ## MinigameSceneFields [#minigamescenefields] Type. Explained in [Minigames](https://ifloom.dev/docs/reference/minigames#minigamescenefields). The scene field that starts a minigame. ```ts shape import type { MinigameSceneFields } from '@ifloom/engine' type MinigameSceneFields = { minigame?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `minigame` | `string` | yes | | The id of the minigame that starts when the scene is entered. The scene shows again once it ends. | ## MinigameState [#minigamestate] Type. Explained in [Minigames](https://ifloom.dev/docs/reference/minigames#minigamestate). The running minigame a save keeps, in `state.minigame`. The engine reads its states from content. ```ts shape import type { MinigameState } from '@ifloom/engine' type MinigameState = { id: string state: string elapsed: number kv: Record steps: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The minigame's id. | | `state` | `string` | | | The name of the state the minigame is in. | | `elapsed` | `number` | | | The milliseconds of ticks since the minigame entered that state. | | `kv` | `Record` | | | The minigame's kv store, as play has left it. | | `steps` | `number` | | | The number of transitions the minigame has taken, part of its random draws' seed. | ## MinigameStateDef [#minigamestatedef] Type. Explained in [Minigames](https://ifloom.dev/docs/reference/minigames#minigamestatedef). A state of a minigame, in its `states`. It can wait (`after`), listen to inputs (`on`), move on by itself (`always`) or end the minigame (`final`). ```ts shape import type { MinigameStateDef } from '@ifloom/engine' type MinigameStateDef = { label?: string after?: { ms: number } & MinigameTransition on?: ({ input: string; when?: Condition; label?: string } & MinigameTransition)[] always?: ({ when?: Condition } & MinigameTransition)[] final?: { effects?: EffectRef[]; copy?: Record } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `label` | `string` | yes | | The words the player reads while the minigame is in this state, with tokens filled. | | `after` | `{ ms: number } &` [`MinigameTransition`](#minigametransition) | yes | | The state's timer. Once `ms` milliseconds of ticks have passed in the state, the engine takes the transition, and one that stays put starts the timer again. The `tick` that runs down the game's named timers runs it down too, in the order they run out. | | `on` | `({ input: string; when?:` [`Condition`](#condition)`; label?: string } &` [`MinigameTransition`](#minigametransition)`)[]` | yes | | The state's inputs. For each input, the first entry whose `when` holds is taken, and an input with no such entry isn't live. `label` is the input's words for its button in this state, with tokens filled, such as a quiz's answer. The first live entry with one gives it. Without one the button reads the `minigame.` string, else the input's name. | | `always` | `({ when?:` [`Condition`](#condition) `} &` [`MinigameTransition`](#minigametransition)`)[]` | yes | | The state's automatic transitions, the first whose `when` holds taken on entering the state. Use them for a state that only decides where to go next, such as a win. | | `final` | `{ effects?:` [`EffectRef[]`](#effectref)`; copy?: Record }` | yes | | The state's ending. Entering the state ends the minigame. `copy` writes keys of the minigame's kv store to the player's (`{ score: 'arrows.best' }`). Then the minigame closes and `effects` run. | ## MinigameTarget [#minigametarget] Type. Explained in [Minigames](https://ifloom.dev/docs/reference/minigames#minigametarget). A state a transition can go to at random, as its id or as its id with a weight. The weight is 1 if left out. ```ts shape import type { MinigameTarget } from '@ifloom/engine' type MinigameTarget = string | { state: string; weight?: number } ``` ## MinigameTransition [#minigametransition] Type. Explained in [Minigames](https://ifloom.dev/docs/reference/minigames#minigametransition). A minigame transition, the state it goes to and the effects it runs on the way. With no `go` or `to` it stays in its state. ```ts shape import type { MinigameTransition } from '@ifloom/engine' type MinigameTransition = { go?: string to?: MinigameTarget[] effects?: EffectRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `go` | `string` | yes | | The id of the state the transition goes to. | | `to` | [`MinigameTarget[]`](#minigametarget) | yes | | The states the transition draws one from at random, by weight, when there's no `go`. The draw is seeded by the save. | | `effects` | [`EffectRef[]`](#effectref) | yes | | The effects the transition runs before it moves. Any effect works, such as a `kv` effect with `of: 'minigame'` or a `turn`. | ## MinigameView [#minigameview] Type. Explained in [Minigames](https://ifloom.dev/docs/reference/minigames#minigameview). The running minigame as the player sees it, in `view.minigame`. ```ts shape import type { MinigameView } from '@ifloom/engine' type MinigameView = { id: string title: string | null state: string label: string | null timeLeft: number | null timeTotal: number | null inputs: MinigameInput[] kv: Record keys: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The minigame's id. | | `title` | `string \| null` | | | The minigame's title, or null. | | `state` | `string` | | | The name of the state the minigame is in. | | `label` | `string \| null` | | | The state's `label`, with tokens filled, or null. `view.scene.body` has it rendered. | | `timeLeft` | `number \| null` | | | The milliseconds left on the state's timer. Null when the state has no timer. | | `timeTotal` | `number \| null` | | | The whole length of the state's timer in milliseconds. Null when the state has no timer. | | `inputs` | [`MinigameInput[]`](#minigameinput) | | | The inputs that are live now, in the order the state lists them. | | `kv` | `Record` | | | The minigame's kv store now. | | `keys` | `Record` | | | The keys the game maps to each input, by input name. Empty when it maps none. | ## ModFile [#modfile] Type. Explained in [Mods](https://ifloom.dev/docs/reference/mods#modfile). A mod as a JSON file, with the game it is for and the pack it adds. A mod is data only, so no code runs that the game didn't ship. ```ts shape import type { ModFile } from '@ifloom/engine' type ModFile = { ifloomMod: 1 id: string name: string version?: string game: string description?: string pack: Pack } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `ifloomMod` | `1` | | | The file's format, 1. | | `id` | `string` | | | The mod's id. Its pack is loaded as `mod:`. | | `name` | `string` | | | The mod's name, for a mods page. | | `version` | `string` | yes | | The mod's own version, as its author writes it, such as `'1.2'`. | | `game` | `string` | | | The id of the game the mod was made for. | | `description` | `string` | yes | | The mod's description, a line for a mods page. | | `pack` | [`Pack`](#pack) | | | The `Pack` the mod adds, laid over the game's content. | ## Mods [#mods] Type. Explained in [Mods](https://ifloom.dev/docs/reference/mods#mods). One game's mod store, returned by `mods`. No call rejects, and a driver's failure answers with a reason and the driver's error as its `cause`. ```ts shape import type { Mods } from '@ifloom/engine' type Mods = { list: () => Promise> add: (text: string) => Promise> remove: (id: string) => Promise> setEnabled: (id: string, enabled: boolean) => Promise> packs: () => Promise> } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `list` | `() => Promise<`[`Result`](#result)`<`[`InstalledMod[]`](#installedmod)`>>` | | | Returns the installed mods, on or off, in name order. A mod stored unreadably is left out. | | `add` | `(text: string) => Promise<`[`Result`](#result)`<`[`InstalledMod`](#installedmod)`>>` | | | Adds a mod from a file's text, turned on, replacing one with the same id. It returns the mod, or the reason it can't be added. | | `remove` | `(id: string) => Promise<`[`Result`](#result)`>` | | | Removes a mod, and does nothing if it isn't installed. | | `setEnabled` | `(id: string, enabled: boolean) => Promise<`[`Result`](#result)`>` | | | Turns a mod on or off, and does nothing if it isn't installed. | | `packs` | `() => Promise<`[`Result`](#result)`<`[`Pack[]`](#pack)`>>` | | | Returns the packs of the mods that are on, in name order, to pass to `loadGame` as `packs`. | ## mods [#mods-1] Function. Explained in [Mods](https://ifloom.dev/docs/reference/mods#mods-1). Returns the `Mods` store of a game, kept by a driver. In a browser, an IndexedDB driver keeps mods across reloads with no server. ```ts shape import { mods } from '@ifloom/engine' function mods(gameId: string, driver: SaveDriver): Mods ``` Uses: [`SaveDriver`](#savedriver), [`Mods`](#mods). ## need [#need] Function. Explained in [Actions](https://ifloom.dev/docs/reference/actions#need). Returns a `blocked` entry written the other way round, refused with `reason` unless `when` holds. For example `need('Not on an empty stomach.', { stat: 'energy', gte: 2 })`. ```ts shape import { need } from '@ifloom/engine' function need(reason: Reason, when: Condition): Blocked ``` Uses: [`Reason`](#reason), [`Condition`](#condition), [`Blocked`](#blocked). ## Notice [#notice] Type. Explained in [Notices](https://ifloom.dev/docs/reference/notices#notice). A message the game gives the player outside a scene, such as a quest moving on or the rent falling due. The `notify` effect raises one, and the `dismiss` command marks it seen. A UI shows a notice as a badge or a toast. ```ts shape import type { Notice } from '@ifloom/engine' type Notice = { id: string title: string text?: string image?: string tag?: string turn: number seen: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The notice's id. A notice raised with the id of an earlier one replaces it. | | `title` | `string` | | | The notice's short line, kept as written. The view fills its tokens. | | `text` | `string` | yes | | The notice's longer words, kept as written. The view fills their tokens. | | `image` | `string` | yes | | The notice's picture, as a path in the game's `art/` folder (`'notes/bins.jpg'`) or a URL. | | `tag` | `string` | yes | | The notice's subject, for grouping badges, such as `'messages'` or `'quests'`. | | `turn` | `number` | | | The turn the notice was raised on. | | `seen` | `boolean` | | | The notice's seen mark, true once the player has dismissed it. | ## NoticesView [#noticesview] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#noticesview-and-noticeview). The notices as the player sees them, in `view.notices`. Only notices the player hasn't dismissed are listed. ```ts shape import type { NoticesView } from '@ifloom/engine' type NoticesView = { unseen: NoticeView[] byTag: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `unseen` | [`NoticeView[]`](#noticeview) | | | The notices the player hasn't dismissed, newest first. | | `byTag` | `Record` | | | The number of unseen notices for each tag, for badges. Untagged notices count under `''`. | ## NoticeView [#noticeview] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#noticesview-and-noticeview). A notice as the player sees it, in `view.notices.unseen`. ```ts shape import type { NoticeView } from '@ifloom/engine' type NoticeView = { id: string title: string text: string image: string | null tag: string | null turn: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The notice's id, which the `dismiss` command takes. | | `title` | `string` | | | The notice's short line, with its tokens filled in. | | `text` | `string` | | | The notice's longer words, with their tokens filled in. Empty if it has none. | | `image` | `string \| null` | | | The notice's picture, as a path through `artSrc`. Null if it has none. | | `tag` | `string \| null` | | | The notice's subject, for grouping badges, such as `'messages'`. Null if it has none. | | `turn` | `number` | | | The turn the notice was raised on. | ## notify [#notify] Function. Explained in [Effects](https://ifloom.dev/docs/reference/effects#notify). Returns the state with a notice raised. A notice with the id of an earlier one replaces it, unseen, as the newest. ```ts shape import { notify, type Notice } from '@ifloom/engine' function notify(state: GameState, notice: Omit & { id?: string }): GameState ``` Uses: [`GameState`](#gamestate), [`Notice`](#notice). ## Once [#once] Type. Explained in [Actions](https://ifloom.dev/docs/reference/actions#once). A limit of once a game or once a turn on a choice, an action or a plugin's entry, such as a cheat. The engine counts a choice's or an action's uses in `state.chosen`. ```ts shape import type { Once } from '@ifloom/engine' type Once = { per: 'game' | 'turn' reason?: Reason } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `per` | `'game' \| 'turn'` | | | The limit's span, `'game'` for once in the whole game or `'turn'` for once a turn. | | `reason` | [`Reason`](#reason) | yes | | The reason the player reads once the limit is spent. For a choice or an action, the engine's `done` string ("Already done.") if left out. | ## OpenPanel [#openpanel] Type. Explained in [Panels](https://ifloom.dev/docs/reference/panels#openpanel). The open panel, a named piece of UI over the story, with the arguments it was opened with. `state.panel` and `view.panel` hold it. ```ts shape import type { OpenPanel } from '@ifloom/engine' type OpenPanel = { panel: string with: PluginArgs scene?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `panel` | `string` | | | The panel's name, which the UI renders it by, such as `'shop'`, `'jobs'` or one of the game's own. | | `with` | [`PluginArgs`](https://ifloom.dev/docs/api/engine-plugin#pluginargs) | | | The panel's arguments, such as `{ vendor: 'cafe' }`. Empty if the effect gave none. | | `scene` | `string` | yes | | The scene that holds the panel open, for a scene's own `panel`, which stays open as long as the scene does. It's left out for a panel the `panel` effect opened. `closePanel` doesn't close a panel a scene holds open. | ## ownedCount [#ownedcount] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#receivething-releasething-and-ownedcount). Returns how many of a thing `of` has, added up across the receivers, or in the one `via` names. ```ts shape import { ownedCount, type Game } from '@ifloom/engine' function ownedCount(state: GameState, game: Game, ref: EntityRef, of?: string, via?: string): number ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`EntityRef`](#entityref). ## Pack [#pack] Type. Explained in [Content and packs](https://ifloom.dev/docs/reference/content#pack). Content from outside the game's code, such as a mod, unlocked supporter content or a JSON export. It goes over the game's content and the packs before it, replacing what they declare by id. ```ts fragment type Pack = { id: string schema: number plugins?: Record strings?: Record prose?: Record words?: Record variants?: Record data?: Record> kinds?: KindDef[] entities?: EntityDef[] traits?: TraitTable player?: PlayerDef | undefined kv?: Record resets?: Record storylines?: StorylineDef[] actions?: ActionDef[] triggers?: TriggerDef[] inputs?: InputDef[] settings?: SettingDef[] stats?: StatDef[] scenes?: DataScene[] patches?: Patch[] introScene?: string minigames?: MinigameDef[] timers?: TimerDef[] audio?: Partial media?: GameMedia ui?: Ui saveable?: Blocked[] locks?: Lock[] phrases?: Phrases changes?: ChangesDef finished?: Condition carryOver?: CarryOver credits?: CreditGroup[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The pack's id, which saves record. A mod's is `mod:`. | | `schema` | `number` | | | The schema the pack was written against. `loadGame` upgrades an older one and refuses a newer one. | | `plugins` | `Record` | yes | | The version of each plugin's content the pack was written for, by plugin id (`{ shop: 13 }`), numbered as `Plugin.contentVersion` is. That plugin's own steps upgrade an older one as it loads. A plugin left out is read as written for the pack's `schema`, or for the plugin's own version if that is lower. | | `strings` | `Record` | yes | | The lines that replace the engine's and plugins' strings, by key. | | `prose` | `Record` | yes | | The prose keys' lines, by key. | | `words` | `Record` | yes | | The words table, other words for the fields a player reads, by key. A translation is one pack with this table and its own `prose`. Each key names one field, as `translatableFields` lists them (`action.wait.label`, `entity.character:ava.name`, `scene.cafe.counter.text.intro`). `loadGame` lays it over the merged content, a later pack's over an earlier one's, and reports a key that names no field. | | `variants` | `Record` | yes | | The variants lists' members by list name, in order. Content and packs append to a list. A member is a prose key, or `{ prose: key, weight }` to be drawn more or less often than the rest. | | `data` | `Record>` | yes | | The plugins' content, by plugin id and then list, such as `{ quests: { quests: [...] } }`. A pack's entry replaces the one with the same id, as its scenes do. | | `kinds` | [`KindDef[]`](#kinddef) | yes | | The pack's kinds. A later pack's kind replaces an earlier one with the same id. | | `entities` | [`EntityDef[]`](#entitydef) | yes | | The pack's entities at the start. A later pack's entity replaces an earlier one with the same kind and id. | | `traits` | [`TraitTable`](#traittable) | yes | | The pack's traits, by trait id and then entity, over what each entity declares itself, such as `{ 'laundry/washable': { 'clothing:scarf': { temp: 30 } } }`. A later pack's row replaces an earlier one's. | | `player` | `PlayerDef \| undefined` | yes | | The pack's player. It replaces the content's `player` whole. | | `kv` | `Record` | yes | | The pack's starting kv store, by key. A later pack's value replaces an earlier one's. | | `resets` | `Record` | yes | | The pack's keys reset each turn, by key. A later pack's value replaces an earlier one's. | | `storylines` | [`StorylineDef[]`](#storylinedef) | yes | | The pack's storylines, merged by id over the content's. | | `actions` | [`ActionDef[]`](#actiondef) | yes | | The pack's actions, by id. A later pack's action replaces an earlier one with the same id. | | `triggers` | [`TriggerDef[]`](#triggerdef) | yes | | The pack's triggers, merged by id over the content's. | | `inputs` | [`InputDef[]`](#inputdef) | yes | | The pack's inputs, merged by id over the content's. | | `settings` | [`SettingDef[]`](#settingdef) | yes | | The pack's settings. A later pack's setting replaces an earlier one with the same id. | | `stats` | [`StatDef[]`](#statdef) | yes | | The pack's stats. A later pack's stat replaces an earlier one with the same id. | | `scenes` | [`DataScene[]`](#datascene) | yes | | The pack's scenes. A later pack's scene replaces an earlier one with the same id. | | `patches` | [`Patch[]`](#patch) | yes | | The pack's patches to the choices of scenes declared before it. | | `introScene` | `string` | yes | | The scene open on the first frame. A later pack's replaces an earlier one's. | | `minigames` | [`MinigameDef[]`](#minigamedef) | yes | | The pack's minigames. A later pack's minigame replaces an earlier one with the same id. | | `timers` | [`TimerDef[]`](#timerdef) | yes | | The pack's timers. A later pack's timer replaces an earlier one with the same id. | | `audio` | `Partial<`[`GameAudio`](#gameaudio)`>` | yes | | The pack's tracks, channels and defaults, over the content's. A later pack's track or channel replaces an earlier one with the same id, and its `mute`, `sound` and `default` entries win too. | | `media` | [`GameMedia`](#gamemedia) | yes | | The pack's pools of pictures and videos. A later pack's pool replaces an earlier one with the same id, files and all. | | `ui` | [`Ui`](#ui)`<`[`GameUi`](#gameui)`>` | yes | | The pack's ui hints for the whole game, merged hint by hint. A later pack's hint replaces an earlier one's, and the rest stay. | | `saveable` | [`Blocked[]`](#blocked) | yes | | The pack's reasons to refuse saving, added after the content's. An entry with the `id` of an earlier one replaces it. | | `locks` | [`Lock[]`](https://ifloom.dev/docs/api/engine-plugin#lock) | yes | | The pack's locks, added after the content's. A lock with the `id` of an earlier one replaces it. | | `phrases` | [`Phrases`](#phrases) | yes | | The pack's phrases, words that change with the state, printed in a line as `{{name}}`. Each is a plain string or a list of `{ when?, text }` rows tried in order, and an object is a group. A later pack's phrase replaces an earlier one with the same full name, and a pack can add phrases to a group. | | `changes` | [`ChangesDef`](#changesdef) | yes | | The pack's tracked stats, by id, such as `{ stats: ['coins', 'trust'] }`. The engine adds every file's and pack's lists together. | | `finished` | [`Condition`](#condition) | yes | | The pack's condition for the game being finished. It replaces the content's, and the runner records the first time it holds in the profile's `core:finished`. | | `carryOver` | [`CarryOver`](#carryover) | yes | | The pack's rules for a New Game+. They replace the content's `carryOver` whole. | | `credits` | [`CreditGroup[]`](#creditgroup) | yes | | The pack's credits, in groups. A group whose id is already declared gets these credits after its own. Its `title` or `description` replaces the earlier one, and a new id adds a group after the others. | ## panel [#panel] Function. Explained in [Effects](https://ifloom.dev/docs/reference/effects#panel). Returns a `{ panel }` block, a panel opened at this place in the flow with `args` as its `with`. The flow waits until the player closes it. ```ts shape import { panel } from '@ifloom/engine' function panel(name: string, args?: PluginArgs, extras?: BlockExtras): Block ``` Uses: [`PluginArgs`](https://ifloom.dev/docs/api/engine-plugin#pluginargs), [`BlockExtras`](#blockextras), [`Block`](#block). ## parseRef [#parseref] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#parseref). Returns an entity reference such as `'staff:ana'` split into its kind and id, or undefined when the string isn't one. ```ts shape import { parseRef } from '@ifloom/engine' function parseRef(ref: string): { kind: string; id: string } | undefined ``` ## Patch [#patch] Type. Explained in [Content and packs](https://ifloom.dev/docs/reference/content#patch). A patch a pack declares in `patches`, a change to one choice of a scene an earlier pack or the content declared. It adds, drops or replaces the choice. `addChoice` puts the choice before the choice `before` names, or last when `before` is left out or not found. `dropChoice` names the choice to drop, and `replaceChoice` takes the place of the choice with its id. ```ts shape import type { Patch } from '@ifloom/engine' type Patch = { scene: string; addChoice: DataScene['choices'][number]; before?: string } | { scene: string; dropChoice: string } | { scene: string; replaceChoice: DataScene['choices'][number] } ``` Uses: [`DataScene`](#datascene). ## Phrase [#phrase] Type. Explained in [Phrases](https://ifloom.dev/docs/reference/phrases#phrase-phraserow-and-phrasewithargs). A phrase the game declares in `phrases`, words for the middle of a sentence that change with the state. It's a list of rows tried in order, a plain string, or rows with their arguments. ```ts shape import type { Phrase } from '@ifloom/engine' type Phrase = string | PhraseRow[] | PhraseWithArgs ``` Uses: [`PhraseRow`](#phraserow), [`PhraseWithArgs`](#phrasewithargs). ## PhraseRow [#phraserow] Type. Explained in [Phrases](https://ifloom.dev/docs/reference/phrases#phrase-phraserow-and-phrasewithargs). A row of a phrase, its words shown while `when` holds. A row with no `when` always holds, and the view fills the tokens in its words. ```ts shape import type { PhraseRow } from '@ifloom/engine' type PhraseRow = { when?: Condition text: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `when` | [`Condition`](#condition) | yes | | The row's condition. The row's words show while it holds, and always when it's left out. | | `text` | `string` | | | The row's words, with tokens the view fills. | ## Phrases [#phrases] Type. Explained in [Phrases](https://ifloom.dev/docs/reference/phrases#phrases). The phrases the game declares in `phrases`, by name. Each entry is a phrase or a group of more phrases, nested as deep as you like. `{ outfit: { verdict: [...] }, weather: 'grey' }` declares `outfit.verdict` and `weather`. ```ts shape import type { Phrases } from '@ifloom/engine' type Phrases = { [key: string]: Phrase | Phrases } ``` ## PhraseWithArgs [#phrasewithargs] Type. Explained in [Phrases](https://ifloom.dev/docs/reference/phrases#phrase-phraserow-and-phrasewithargs). A phrase that takes arguments, with their names in `args` and its rows. A token passes each argument as `name=value`. In a row's `when`, a string that is exactly `$` becomes the value the token passed, as an entity reference when it names one. In a row's `text`, `$` becomes that entity's name, or the value as passed. ```ts shape import type { PhraseWithArgs } from '@ifloom/engine' type PhraseWithArgs = { args: string[] rows: PhraseRow[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `args` | `string[]` | | | The names of the arguments the phrase takes. | | `rows` | [`PhraseRow[]`](#phraserow) | | | The phrase's rows, tried in order. | ## PictureDef [#picturedef] Type. Explained in [Media](https://ifloom.dev/docs/reference/media#picturedef). A picture a scene or a location declares in its `picture`, layers with hotspots on them. ```ts shape import type { PictureDef } from '@ifloom/engine' type PictureDef = { layers: PictureLayer[] hotspots?: HotspotDef[] aspect?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `layers` | [`PictureLayer[]`](#picturelayer) | | | The picture's layers, bottom first. | | `hotspots` | [`HotspotDef[]`](#hotspotdef) | yes | | The picture's hotspots, each a button the UI renders over the picture. | | `aspect` | `string` | yes | | The picture's width over height, in CSS form, such as `'16/9'`. The UI's own if left out. | ## PictureLayer [#picturelayer] Type. Explained in [Media](https://ifloom.dev/docs/reference/media#picturelayer). A layer of a picture, a file or a pool's pick, shown while `when` holds. Give `src` or `pool`, not both. ```ts shape import type { PictureLayer } from '@ifloom/engine' type PictureLayer = { id?: string src?: string pool?: string tags?: string[] when?: Condition video?: boolean controls?: boolean once?: boolean sound?: boolean poster?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | yes | | The layer's id, which a hotspot's `layer` names. | | `src` | `string` | yes | | The layer's file, in the game's `art/` folder or a URL. | | `pool` | `string` | yes | | The pool in `media.pools` the layer's file is drawn from. The save keeps the pick. | | `tags` | `string[]` | yes | | The tags the pool's pick should have, most important first. | | `when` | [`Condition`](#condition) | yes | | The layer's condition. The layer shows only while it holds. | | `video` | `boolean` | yes | | The layer's video mark, true to show it as a video. A `.mp4` or `.webm` file is a video anyway. | | `controls` | `boolean` | yes | | The controls flag, which shows the player's controls, so the video waits to be started instead of playing by itself. | | `once` | `boolean` | yes | | The once flag, which plays the video once instead of looping. | | `sound` | `boolean` | yes | | The sound flag, which plays the video with sound instead of muted. | | `poster` | `string` | yes | | The still shown before the video plays, as a path like any picture's. | ## PictureLayerView [#picturelayerview] Type. Explained in [Media](https://ifloom.dev/docs/reference/media#picturelayerview). A picture layer as the player sees it, in a `PictureView`'s `layers`. ```ts shape import type { PictureLayerView } from '@ifloom/engine' type PictureLayerView = { id: string | null src: string video?: VideoView } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string \| null` | | | The layer's id, or null. | | `src` | `string` | | | The layer's file, through `artSrc`, with a pool's pick resolved. | | `video` | [`VideoView`](#videoview) | yes | | The layer's playback settings when it's a video. Left out for a still picture. | ## PictureView [#pictureview] Type. Explained in [Media](https://ifloom.dev/docs/reference/media#pictureview). A picture as the player sees it, in `view.scene.picture` or a location's `picture`. It lists the layers shown now, bottom first, and the hotspots on them. ```ts shape import type { PictureView } from '@ifloom/engine' type PictureView = { aspect: string | null layers: PictureLayerView[] hotspots: HotspotView[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `aspect` | `string \| null` | | | The picture's width over height, such as `'16/9'`. Null when the picture doesn't set it. | | `layers` | [`PictureLayerView[]`](#picturelayerview) | | | The layers whose `when` holds, bottom first. | | `hotspots` | [`HotspotView[]`](#hotspotview) | | | The hotspots whose `when` holds and whose layer shows. | ## Played [#played] Type. Explained in [Entities](https://ifloom.dev/docs/reference/entities#someone-and-played). The one the player is playing, a protagonist or `'player'`. ```ts shape import type { Played } from '@ifloom/engine' type Played = EntityRef | typeof PLAYER ``` Uses: [`EntityRef`](#entityref). ## PLAYER [#player] Const. Explained in [Entities](https://ifloom.dev/docs/reference/entities#player-and-you). The id of the player themselves, whoever they are playing. ```ts shape import { PLAYER } from '@ifloom/engine' const PLAYER: 'player' ``` ## PlaylistDef [#playlistdef] Type. Explained in [Audio](https://ifloom.dev/docs/reference/audio#playlistdef). A playlist the game declares in `audio.tracks`, background tracks played one after another. Its order is `'loop'` if left out. ```ts shape import type { PlaylistDef } from '@ifloom/engine' type PlaylistDef = { playlist: (string | { track: string; weight?: number })[] order?: 'inOrder' | 'loop' | 'shuffle' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `playlist` | `(string \| { track: string; weight?: number })[]` | | | The playlist's track ids, each on a background channel. In a shuffled playlist a track can carry a weight, `{ track: 'rain', weight: 3 }`, which makes it likely to come earlier. A plain id has weight 1. | | `order` | `'inOrder' \| 'loop' \| 'shuffle'` | yes | | The playlist's order. `'inOrder'` plays the list once, `'loop'` plays it over and over, and `'shuffle'` plays it over and over in an order drawn from the save's seed. `'loop'` if left out. With weights, the shuffle draws the first track by weight, then the next from those left, and so on, so a heavier track tends to play sooner. | ## PluginCall [#plugincall] Type. Explained in [Calls by name](https://ifloom.dev/docs/reference/custom#plugincall). A plugin's or the game's condition, effect or command in the short form, with its full name as the only key. The value is its arguments as an object, or `true` for none. `{ 'quests/done': { quest: 'bakery' } }` and `{ 'calendar/weekend': true }` are calls. Any other value, such as a list, a string or a number, is a problem the content checker reports, and the engine asks the call with no arguments. ```ts shape import type { PluginCall } from '@ifloom/engine' type PluginCall = { [key: `${string}/${string}`]: true | PluginArgs } ``` ## pluginQuery [#pluginquery] Function. Explained in [Queries and partners](https://ifloom.dev/docs/reference/plugin-queries#pluginquery). Returns a plugin's query by full name, ready to ask, or undefined when the game doesn't have it. As with `context.query`, a name declared in `QueryRegistry` takes its arguments and answers its type. Any other name takes any arguments, with the answer's type given. ```ts shape import { pluginQuery, type Game } from '@ifloom/engine' function pluginQuery(game: Game | undefined, name: K): ((state: GameState, ...args: QueryArgs) => QueryAnswer) | undefined function pluginQuery(game: Game | undefined, name: string): ((state: GameState, args?: PluginArgs) => T) | undefined ``` Uses: [`QueryRegistry`](#queryregistry), [`Game`](#game), [`GameState`](#gamestate), [`QueryArgs`](https://ifloom.dev/docs/api/engine-plugin#queryargs), [`QueryAnswer`](https://ifloom.dev/docs/api/engine-plugin#queryanswer), [`PluginArgs`](https://ifloom.dev/docs/api/engine-plugin#pluginargs). ## point [#point] Function. Explained in [Effects](https://ifloom.dev/docs/reference/effects#point). Returns a point, a place in the flow a choice's `jump(id)` goes to, anywhere in a scene's body, a section or a choice's `then`. ```ts shape import { point } from '@ifloom/engine' function point(id: string): Block ``` Uses: [`Block`](#block). ## PoolFile [#poolfile] Type. Explained in [Media](https://ifloom.dev/docs/reference/media#poolfile). A file in a pool in `media.pools`, with its path, its tags and its weight against the other files that fit. The weight is 1 if left out. ```ts shape import type { PoolFile } from '@ifloom/engine' type PoolFile = { src: string tags?: string[] weight?: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `src` | `string` | | | The file's path, in the game's `art/` folder or a URL. | | `tags` | `string[]` | yes | | The file's tags, which a request's tags match. | | `weight` | `number` | yes | | The file's weight in a draw, against the other files that fit. 1 if left out. | ## Price [#price] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#price). The cost of a choice or action, shown on its button before the player presses it. It lists costs only, since a payout printed on a choice tells the player which one is right. ```ts shape import type { Price } from '@ifloom/engine' type Price = { stats?: { id: string; amount: number; text: string }[] notes?: string[] text: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `stats` | `{ id: string; amount: number; text: string }[]` | yes | | The stats the price spends, in the order the button lists them, each with its amount and its words in `text`. | | `notes` | `string[]` | yes | | The plugins' words for what else it costs, such as "until evening". | | `text` | `string` | | | The whole price as one line for the player, such as `2 coins · until evening`. It joins each stat's `text`, then the notes, with the `priceSeparator` string. | ## Probe [#probe] Type. Explained in [Checking content](https://ifloom.dev/docs/reference/checks#probe). A state the content checker renders every scene against, named for the problems it finds. Make one with `probe`, by playing. ```ts shape import type { Probe } from '@ifloom/engine' type Probe = { name: string state: GameState } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | | | The probe's name, which the problems it finds carry, such as `'evening, after the café'`. | | `state` | [`GameState`](#gamestate) | | | The state to render every scene against. | ## Problem [#problem] Type. Explained in [Checking content](https://ifloom.dev/docs/reference/checks#problem). A fault the content checker finds in a game's content, with the pack it came from and the place in it. ```ts shape import type { Problem } from '@ifloom/engine' type Problem = { pack: string where: string what: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `pack` | `string` | | | The name or id of the content or pack the problem came from. It is `game` for a hand-built game. | | `where` | `string` | | | The place in the content the problem is, such as `scene cafe.counter` or `finished`. | | `what` | `string` | | | The fault, such as `unknown storyline "tides"`. | ## Profile [#profile] Type. Explained in [The profile](https://ifloom.dev/docs/reference/profile#profile). The player's record that outlives a save, such as settings, whether they have finished the game, and plugins' records like achievements. It is one JSON object of namespaces, kept at `.profile` in a save driver. The engine uses two namespaces, `core:settings` (each setting's stored value, by id) and `core:finished` (`{ at }`, when the game was first finished). A UI uses `ui:` names, such as the React UI's gate, `ui:gate`. A plugin uses its own bare id, which can't hold a `:`, so the prefixes are reserved. ```ts shape import type { Profile } from '@ifloom/engine' type Profile = { get: (namespace: string) => Promise set: (namespace: string, value: unknown) => Promise update: (namespace: string, change: (current: T | undefined) => T | undefined) => Promise subscribe: (listener: (namespace: string, value: unknown) => void) => () => void } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `get` | `(namespace: string) => Promise` | | | Returns the value a namespace holds, or undefined if it holds none. | | `set` | `(namespace: string, value: unknown) => Promise` | | | Stores a value in a namespace. Undefined clears it. | | `update` | `(namespace: string, change: (current: T \| undefined) => T \| undefined) =>…` | | | Changes a namespace from the value it holds now, with no other write in between, and returns the value it holds afterwards. Return undefined, or the same value, from `change` to leave it. | | `subscribe` | `(listener: (namespace: string, value: unknown) => void) => () => void` | | | Calls a listener with the namespace and new value of every write, and returns a function that stops it. | ## profile [#profile-1] Function. Explained in [The profile](https://ifloom.dev/docs/reference/profile#profile-1). Returns the `Profile` of a game, kept by a driver. Reads and writes run one at a time, in order. It reads only the game's `id`, so a profile can be opened before the game is built, as in `profile({ id: 'small-town' }, driver)`. ```ts shape import { profile, type Game } from '@ifloom/engine' function profile(game: Pick, driver: SaveDriver): Profile ``` Uses: [`Game`](#game), [`SaveDriver`](#savedriver), [`Profile`](#profile). ## proseBeats [#prosebeats] Function. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#prosebeats). Returns the prose key's line rendered as beats, the way a scene's body is rendered. Returns null when the game has no line by that key. The engine fills its tokens for this save, cuts it into paragraphs and spoken lines, names each speaker from their entity and puts its inline markup (bold, italics, UI pieces) in `spans`. A UI calls it to show a line away from the scene, such as in a dialog an inline piece opens. ```ts shape import { proseBeats, type Game } from '@ifloom/engine' function proseBeats(state: GameState, game: Game, key: string): SceneBeat[] | null ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`SceneBeat`](#scenebeat). ## ProseStore [#prosestore] Type. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#prosestore). The store of prose keys and variants lists that scenes read. `loadGame` makes it from the content's `prose`. ```ts shape import type { ProseStore } from '@ifloom/engine' type ProseStore = { line: (key: string, state?: GameState) => string | undefined variants: (name: string) => string[] weight?: (name: string, key: string) => number keys?: () => string[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `line` | `(key: string, state?:` [`GameState`](#gamestate)`) => string \| undefined` | | | The store's function that returns a prose key's line, with its tokens filled for `state`. | | `variants` | `(name: string) => string[]` | | | The store's function that returns a variants list's members by its name, in declaration order. | | `weight` | `(name: string, key: string) => number` | yes | | The store's function that returns a member's weight in a variants list. Every member weighs 1 if left out. | | `keys` | `() => string[]` | yes | | The store's function that lists every prose key, so the content checker can read all the prose's markup. The checker reads only the keys content names if left out. | ## protagonist [#protagonist] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#protagonist-and-resolveyou). Returns whom `'you'` stands for now, the protagonist the `you` effect chose or else `'player'`. ```ts shape import { protagonist } from '@ifloom/engine' function protagonist(state: GameState): Played ``` Uses: [`GameState`](#gamestate), [`Played`](#played). ## Query [#query] Type. Explained in [Queries and partners](https://ifloom.dev/docs/reference/plugin-queries#query). A function that asks a plugin or the game a query by full name. It returns undefined when the game has no such query. A name declared in `QueryRegistry` takes its declared arguments and returns its declared answer. Any other name takes any arguments, and you give the answer's type, as in `query('loyalty/stampsLeft')`. ```ts shape import type { Query } from '@ifloom/engine' type Query = { (name: K, ...args: QueryArgs): QueryAnswer | undefined; (name: string, args?: PluginArgs): T | undefined } ``` Uses: [`QueryRegistry`](#queryregistry), [`QueryArgs`](https://ifloom.dev/docs/api/engine-plugin#queryargs), [`QueryAnswer`](https://ifloom.dev/docs/api/engine-plugin#queryanswer), [`PluginArgs`](https://ifloom.dev/docs/api/engine-plugin#pluginargs). ## QueryRegistry [#queryregistry] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#conditionregistry-effectregistry-commandregistry-queryregistry-and-viewregistry). The registry of queries plugins and the game answer, by full name, each typed as a function from its arguments to its answer (`'loyalty/stampsLeft': () => number`). `context.query` and `pluginQuery` read it. A plugin declares its own queries here. Code that doesn't import the answering plugin gives the answer's type, `query('loyalty/stampsLeft')`. ```ts shape import type { QueryRegistry } from '@ifloom/engine' type QueryRegistry = { // … } ``` Plugins add fields of their own to it, which their pages list. ## Range [#range] Type. Explained in [Common types](https://ifloom.dev/docs/reference/common#range). The bounds a condition compares a number with, so `{ gte: 3 }` holds for 3 or more. Each bound is an `Amount`, such as `{ gte: { stat: 'rent' } }`. ```ts shape import type { Range } from '@ifloom/engine' type Range = { gte?: Amount gt?: Amount lte?: Amount lt?: Amount } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `gte` | [`Amount`](#amount) | yes | | The range's lower bound, which the number must reach or pass. | | `gt` | [`Amount`](#amount) | yes | | The range's lower bound, which the number must pass. | | `lte` | [`Amount`](#amount) | yes | | The range's upper bound, which the number must not pass. | | `lt` | [`Amount`](#amount) | yes | | The range's upper bound, which the number must stay below. | ## RawPack [#rawpack] Type. Explained in [Plugin migrations](https://ifloom.dev/docs/reference/plugin-migrations#rawpack). A pack as it arrived, in the shape of the schema it records, which may be older than `SCHEMA`. ```ts shape import type { RawPack } from '@ifloom/engine' type RawPack = { schema: number } ``` It also takes any other key: `[key: string]: unknown`. | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `schema` | `number` | | | The content schema the pack was written for. | ## Reason [#reason] Type. Explained in [Actions](https://ifloom.dev/docs/reference/actions#reason). The words a player reads when something is refused, written in place (`'Closed.'`) or as a strings key (`{ string: 'shop/closed' }`). Read one with `reasonOf`. A key lets a game reword a reason once for every place that uses it. ```ts shape import type { Reason } from '@ifloom/engine' type Reason = string | { string: string } ``` ## reasonOf [#reasonof] Function. Explained in [Strings](https://ifloom.dev/docs/reference/strings#reasonof). Returns a refusal's words for a `Reason`. A string is returned as written, and `{ string: 'shop/closed' }` is read with `stringOf`. ```ts shape import { reasonOf, type Game } from '@ifloom/engine' function reasonOf(game: Game | undefined, reason: string | { string: string }): string ``` Uses: [`Game`](#game). ## receiversOf [#receiversof] Function. Returns the game's plugins that keep things, in the order `receive` asks them. ```ts fragment function receiversOf(game: Game | undefined): readonly Receiving[] ``` Uses: [`Game`](#game). ## receiveThing [#receivething] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#receivething-releasething-and-ownedcount). Returns the state with `count` of a thing given to `to`, by the first receiver that claims it. The one `via` names takes it whether it claims it or not. The state comes back unchanged when none takes it. ```ts shape import { receiveThing, type Game } from '@ifloom/engine' function receiveThing(state: GameState, game: Game, ref: EntityRef, count: number, to?: string, via?: string): GameState ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`EntityRef`](#entityref). ## releaseThing [#releasething] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#receivething-releasething-and-ownedcount). Returns the state with up to `count` of a thing taken from `from`, asking each receiver in order until it's done. ```ts shape import { releaseThing, type Game } from '@ifloom/engine' function releaseThing(state: GameState, game: Game, ref: EntityRef, count: number, from?: string, via?: string): GameState ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`EntityRef`](#entityref). ## RenderedChoice [#renderedchoice] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#renderedchoice). A choice or action ready to render as a button, in `view.scene.choices`, `view.actions` or a plugin's view. A UI sends its `command` when the player presses it. ```ts shape import type { RenderedChoice } from '@ifloom/engine' type RenderedChoice = { id: string label: string price?: Price disabled?: string tags?: string[] irreversible?: string ui?: Ui warning?: string command: Command } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The choice's or action's id. | | `label` | `string` | | | The button's label, with tokens filled. | | `price` | [`Price`](#price) | yes | | The button's price for this state, with its words in `text`. Left out when it's free. | | `disabled` | `string` | yes | | The reason the player can't press the button now, in the player's words. Left out when they can. | | `tags` | `string[]` | yes | | The choice's or action's tags, for a UI to style or filter it by. | | `irreversible` | `string` | yes | | The warning that the choice or action can't be undone, for a UI to show on its button. | | `ui` | [`Ui`](#ui)`<`[`ChoiceUi`](#choiceui)`>` | yes | | The choice's or action's `ui` hints, unchanged from content. Left out with none, and typed by `ChoiceUi`. | | `warning` | `string` | yes | | The reason a plugin's guard gives for refusing the button softly, such as running past dawn. The player can press it, but the reducer refuses it, so a UI shows the warning instead. | | `command` | [`Command`](#command) | | | The command a UI sends when the player presses the button, as `runner.apply(choice.command)`. | ## replay [#replay] Function. Explained in [The runner](https://ifloom.dev/docs/reference/runner#replay). Returns the state a `CommandLog` ends in, played back against a game. A log that can't be read, such as one from a newer engine, gives the reason. The log's start comes in through `loadState`. The engine's command steps and each plugin's `commandMigrations` carry its commands forward from the versions the log records, so a log from an older engine, plugin or game still plays. A command that is refused is skipped, as it was when it was played. ```ts shape import { replay, type Game } from '@ifloom/engine' function replay(game: Game, log: CommandLog): Result ``` Uses: [`Game`](#game), [`CommandLog`](#commandlog), [`Result`](#result), [`GameState`](#gamestate). ## resolveYou [#resolveyou] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#protagonist-and-resolveyou). Returns whom an id stands for now, so `'you'` becomes the protagonist or the player. Any other id is returned unchanged. ```ts shape import { resolveYou } from '@ifloom/engine' function resolveYou(state: GameState, who: string): string ``` Uses: [`GameState`](#gamestate). ## Result [#result] Type. Explained in [Common types](https://ifloom.dev/docs/reference/common#result). The answer of a call that can fail in a way its caller should expect, such as a save that won't read. A function that returns a `Result` never throws for those failures. `ok` tells success from failure. On success `value` holds the answer. On failure `reason` says why, in words a player can read, and `cause` holds the error behind it when one was thrown (a save driver's, say), for a log. ```ts shape import type { Result } from '@ifloom/engine' type Result = { ok: true; value: T; reason?: never; cause?: never } | { ok: false; reason: string; cause?: unknown; value?: never } ``` ## Roll [#roll] Type. Explained in [Dice rolls](https://ifloom.dev/docs/reference/rolls#roll). A roll the `roll` effect made, with the face each die showed, the total and the outcome against a target. `view.rolls` lists the last command's. ```ts shape import type { Roll } from '@ifloom/engine' type Roll = { key: string dice: string faces: number[] plus: number total: number against?: number passed?: boolean critical?: 'max' | 'min' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `key` | `string` | | | The kv key the roll stored its total under. | | `dice` | `string` | | | The dice thrown, in notation without the added number, such as `'2d6'`. | | `faces` | `number[]` | | | The face each die showed, in order. | | `plus` | `number` | | | The number added to the faces, the notation's own `+1` and the effect's `plus` together. 0 when nothing was added. | | `total` | `number` | | | The roll's total, the faces added up plus `plus`. | | `against` | `number` | yes | | The target the total had to reach. Left out when the effect gave none. | | `passed` | `boolean` | yes | | The roll's outcome, true when the total reached `against`. Left out when there's no target. | | `critical` | `'max' \| 'min'` | yes | | The roll's critical mark, `'max'` when every die showed its highest face and `'min'` when every die showed 1. | ## RollsState [#rollsstate] Type. Explained in [Dice rolls](https://ifloom.dev/docs/reference/rolls#rollsstate). The rolls a save keeps, with the count of rolls made, the last command's rolls and the latest roll under each key. ```ts shape import type { RollsState } from '@ifloom/engine' type RollsState = { made: number last: Roll[] latest: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `made` | `number` | | | The number of rolls this save has made. It's part of each new roll's seed. | | `last` | [`Roll[]`](#roll) | | | The rolls the last command made, in order. | | `latest` | `Record` | | | The latest roll under each key, which the `roll` condition reads. | ## Runner [#runner] Type. Explained in [The runner](https://ifloom.dev/docs/reference/runner#runner). The object a UI drives a game through, returned by `createRunner` or by `browserRunner` from `@ifloom/browser`. A call that can fail in a way a UI should expect answers with a `Result` and never throws. A refused command, an empty slot and a setting with no profile to keep it are such failures. ```ts shape import type { Runner, Game } from '@ifloom/engine' type Runner = { readonly game: Game readonly state: GameState view: () => View apply: (ref: CommandRef) => Result undo: () => boolean redo: () => boolean log: () => CommandLog played: () => number readonly saves: Saves | undefined readonly offers: { undo: boolean; backlog: boolean } save: (slot: string, name?: string | undefined) => Promise> restore: (loaded: LoadedSave) => void load: (slot: string) => Promise> settled: () => Promise readonly profile: Profile | undefined setSetting: (id: string, to: KvValue) => Result newGame: (start?: StartOptions | undefined) => Promise snapshot: () => RunnerSnapshot subscribe: (listener: (snapshot: RunnerSnapshot) => void) => () => void setHelper: (id: K, value: (K extends 'unlocks' ? HelperRegistry[K] : unknown) | undefined) => void } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `game` | [`Game`](#game) | | | The game this runner plays. | | `state` | [`GameState`](#gamestate) | | | The state in play. | | `view` | `() =>` [`View`](#view) | | | Returns the view of the state in play. It returns the same object for the same state, so a UI, the audio player and the backlog can all read it. Each plugin's view reads that plugin's profile namespace. When a namespace changes, the runner builds that plugin's view again into a new view object and tells listeners, though the state is the same. | | `apply` | `(ref:` [`CommandRef`](#commandref)`) =>` [`Result`](#result)`<`[`GameState`](#gamestate)`>` | | | Runs a command and returns the next state. A refused command leaves the state as it was and returns the reason. The runner logs a `tick` like any command, but undo steps over it, it adds nothing to the backlog, and it autosaves only when it changes the scene or the turn. A `newGame`, sent on its own or by a choice, starts a new game as `newGame()` does, with the profile's play settings as last read. | | `undo` | `() => boolean` | | | Steps back one command. Returns false when there is nothing to undo. | | `redo` | `() => boolean` | | | Steps forward one command after an undo. Returns false when there is nothing to redo. | | `log` | `() =>` [`CommandLog`](#commandlog) | | | Returns the `CommandLog` of this game, its start state and every command since, for `replay`. | | `played` | `() => number` | | | Returns the time played, in milliseconds. It counts on from the time a loaded save recorded. | | `saves` | [`Saves`](#saves) `\| undefined` | | | The save store this runner writes to, for a menu that reads, exports or imports saves. It is undefined without `saves`. Its writes and removals show in the snapshot's `saves`. Like the store, it never rejects. When the driver fails, each call answers why and tells `onSaveError`. | | `offers` | `{ undo: boolean; backlog: boolean }` | | | The features a menu should offer, `undo` true when history is on and `backlog` true when the backlog is on. | | `save` | `(slot: string, name?: string \| undefined) => Promise<`[`Result`](#result)`<`[`SaveMeta`](#savemeta)`>>` | | | Saves the state in play to a slot and returns the save's `SaveMeta`. It fails with the reason when there are no `saves`, the game's `saveable` refuses saving now, or the driver fails. `view().saving` says beforehand whether a save would be refused. | | `restore` | `(loaded:` [`LoadedSave`](#loadedsave)`) => void` | | | Puts a save in play that did not come from a slot, such as one the player imported from a file (`saves.importText`). It starts a fresh history, backlog and log, as `load` does. | | `load` | `(slot: string) => Promise<`[`Result`](#result)`<`[`LoadedSave`](#loadedsave)`>>` | | | Loads a slot into play and returns the save. The runner starts a fresh history, backlog and log from it, and the time played it recorded. It fails with the reason when there are no `saves`, the slot is empty, this game can't read the save, or the driver fails. A driver's failure is told to `onSaveError` too. | | `settled` | `() => Promise` | | | Returns a promise that settles once every autosave and profile write so far is written. It also waits for the first listing of the saves and the first read of the profile. | | `profile` | [`Profile`](#profile) `\| undefined` | | | The profile this runner writes settings and `finished` to, which a UI can use for namespaces of its own. It is undefined without `profile`. It never rejects. A read the driver fails answers undefined, and a write it fails is dropped, each told to `onSaveError`. | | `setSetting` | `(id: string, to:` [`KvValue`](#kvvalue)`) =>` [`Result`](#result)`<`[`KvValue`](#kvvalue)`>` | | | Changes a setting of either kind and returns the value set. A value its declaration refuses, or a `ui` setting without a profile, fails with the reason. The runner sends a `play` setting as the `setting` command, so it changes the game in play, and the profile keeps it for the next new game. It writes a `ui` setting to the profile only. Listeners are told either way. | | `newGame` | `(start?:` [`StartOptions`](#startoptions) `\| undefined) => Promise<`[`GameState`](#gamestate)`>` | | | Starts a new game in place and returns its first state. The history, backlog, log and time played start fresh. Play settings not given are the player's, from the profile, or from the game in play without one. The seed is random unless given. For New Game+, pass `carry: runner.state`. | | `snapshot` | `() =>` [`RunnerSnapshot`](#runnersnapshot) | | | Returns the `RunnerSnapshot`, one value with all a UI renders. The same object comes back until any part of it changes. | | `subscribe` | `(listener: (snapshot:` [`RunnerSnapshot`](#runnersnapshot)`) => void) => () => void` | | | Calls a listener with each new snapshot and returns a function that stops it. A new snapshot comes with a change of state, of a setting, of the profile a view reads, of the saves, or of a helper's report. | | `setHelper` | `(id: K, value: (K extends 'unlocks' ?` [`HelperRegistry`](#helperregistry)`[K] : unknown) \|…` | | | Sets a helper's report under its id in the snapshot's `helpers`, and tells listeners when it changes. Undefined removes the report. `startUnlocks` reports this way whether it is checking a code. | ## RunnerOptions [#runneroptions] Type. Explained in [The runner](https://ifloom.dev/docs/reference/runner#runneroptions). Settings for `createRunner`. Undo, the backlog, saving, autosave and the profile are each off when left out. ```ts shape import type { RunnerOptions } from '@ifloom/engine' type RunnerOptions = { saves?: Saves history?: HistoryOptions | boolean backlog?: BacklogOptions | boolean autosave?: AutosaveOptions now?: () => number onSaveError?: (error: unknown) => void profile?: Profile } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `saves` | [`Saves`](#saves) | yes | | The save store that `save`, `load` and autosave write to. Without it, `save` and `load` refuse and autosave does nothing. | | `history` | [`HistoryOptions`](#historyoptions) `\| boolean` | yes | | The undo and redo settings, `true` for 50 steps back or a `HistoryOptions`. Undo is off if left out. | | `backlog` | [`BacklogOptions`](#backlogoptions) `\| boolean` | yes | | The backlog settings, `true` for 200 entries or a `BacklogOptions`. The backlog is off if left out. | | `autosave` | [`AutosaveOptions`](#autosaveoptions) | yes | | The autosave policy, which writes a slot of its own (`'auto'`) as the game goes on. It needs `saves`, and autosave is off if left out. | | `now` | `() => number` | yes | | The clock that times play, in milliseconds. `Date.now` if left out, and tests pass their own. | | `onSaveError` | `(error: unknown) => void` | yes | | The function the runner tells each error a save driver or the profile throws. Without it, the runner drops the error. It hears about an autosave, `save`, `load`, any call through `runner.saves` or `runner.profile`, the first listing of the saves and a profile write. The writes queued after a failed one still run. | | `profile` | [`Profile`](#profile) | yes | | The profile that keeps what outlives a save, such as settings, `finished` and plugins' namespaces. Without one, the runner writes nothing there and refuses to change a `ui` setting. | ## RunnerSnapshot [#runnersnapshot] Type. Explained in [The runner](https://ifloom.dev/docs/reference/runner#runnersnapshot). One value with all a UI renders from the runner, including the view, the settings, the backlog and the saves. It's a new object whenever a part changes, and the same object until then. `runner.snapshot()` returns it, and `runner.subscribe` passes each new one to its listeners. A UI that keeps it whole (Vue's `shallowRef`, React's `useSyncExternalStore`, a Svelte store) renders again exactly when something changed. ```ts shape import type { RunnerSnapshot } from '@ifloom/engine' type RunnerSnapshot = { readonly state: GameState readonly view: View readonly settings: Readonly> readonly backlog: readonly BacklogEntry[] readonly canUndo: boolean readonly canRedo: boolean readonly saves: readonly SaveListing[] readonly helpers: HelpersIn readonly pressed: RenderedChoice | null readonly fresh: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `state` | [`GameState`](#gamestate) | | | The state in play, the same as `runner.state`. | | `view` | [`View`](#view) | | | The view of the state in play, the same as `runner.view()`. | | `settings` | `Readonly>` | | | The value of each setting the game declares, by setting id. A stored value that no longer fits its setting reads as the default. A `play` setting's value comes from the game in play. A `ui` setting's value comes from the profile, or is its default without a profile or until the profile has been read (`settled`). | | `backlog` | `readonly` [`BacklogEntry[]`](#backlogentry) | | | The backlog's entries, oldest first. It is empty unless the backlog is on. | | `canUndo` | `boolean` | | | True when `undo` has a step to go back to. | | `canRedo` | `boolean` | | | True when `redo` has a step to go forward to. | | `saves` | `readonly` [`SaveListing[]`](#savelisting) | | | The saves in the runner's `saves`, newest first, then any that can't be read. It is empty without `saves`. The runner lists them once when it starts (`settled` waits for it). It keeps the list up to date as it saves and as `runner.saves` writes and removes. | | `helpers` | [`HelpersIn`](#helpersin) | | | The reports of the helpers started beside the runner, by helper id, such as `unlocks`. A helper sets its report with `setHelper`. | | `pressed` | [`RenderedChoice`](#renderedchoice) `\| null` | | | The choice or action that led to the screen on show, as it was offered. A UI reads its `ui` hints to play the transition it asks for. The runner sets it when a command it runs changes the screen (`view.scene.key`), from the choices, inline actions and actions of the view the command was sent from, and keeps it while the screen stays. It is null after a tick, a command no choice or action offered, an undo, a redo, a load or a new game. | | `fresh` | `boolean` | | | True when the state on show came from a command the runner just ran, and false after an undo, a redo, a load or a new game. A UI animates what the player just did, such as the dice of `view.rolls`, only while it's true. | ## RunningTimer [#runningtimer] Type. Explained in [Timers](https://ifloom.dev/docs/reference/timers#runningtimer). A running timer a save keeps, with the milliseconds left and its whole length. The engine reads its effects from content when it runs out. ```ts shape import type { RunningTimer } from '@ifloom/engine' type RunningTimer = { left: number total: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `left` | `number` | | | The milliseconds the timer has left. At 0 it runs out on the next tick. | | `total` | `number` | | | The timer's whole length in milliseconds, the length it started with, raised when time added goes past it. | ## SAVE_VERSION [#save_version] Const. Explained in [Saves](https://ifloom.dev/docs/reference/saves#save_version). The save format's version. Only a change to the shape of a field saves already have bumps it, with a step in `STEPS` that reshapes older saves. An added field doesn't bump it. The field declares a load default in `FIELDS` or in its feature's `state`, and an older save gets that default when it loads. ```ts shape import { SAVE_VERSION } from '@ifloom/engine' const SAVE_VERSION: 1 ``` ## SaveDriver [#savedriver] Type. Explained in [Saves](https://ifloom.dev/docs/reference/saves#savedriver). A store of text by key that the save store and the profile write to. Every driver is asynchronous, even over synchronous storage, so a game can swap one for another. The save store talks to a driver and nothing else, so a game chooses where its saves are kept. `@ifloom/browser` has drivers for localStorage and IndexedDB, `memoryDriver` keeps them in memory, and a game can write its own, such as a desktop wrapper's file system or a sync service. ```ts shape import type { SaveDriver } from '@ifloom/engine' type SaveDriver = { name: string get: (key: string) => Promise set: (key: string, value: string) => Promise remove: (key: string) => Promise keys: (prefix: string) => Promise } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | | | The driver's name, such as "localStorage" or "indexedDB", for diagnostics and the debug panel. | | `get` | `(key: string) => Promise` | | | Returns the text stored under a key, or null if there's none. | | `set` | `(key: string, value: string) => Promise` | | | Stores text under a key, replacing what was there. | | `remove` | `(key: string) => Promise` | | | Deletes a key, and does nothing if it isn't there. | | `keys` | `(prefix: string) => Promise` | | | Returns every key that starts with a prefix. | ## SaveExtra [#saveextra] Type. Explained in [Saves](https://ifloom.dev/docs/reference/saves#saveextra). Settings for `Saves.write` besides the state. ```ts shape import type { SaveExtra } from '@ifloom/engine' type SaveExtra = { name?: string played?: number savedAt?: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | yes | | The player's name for the save. The plugins' `when` words, else the turn, if left out. | | `played` | `number` | yes | | The time played, in milliseconds. 0 if left out. | | `savedAt` | `number` | yes | | The time the save was written, in epoch milliseconds. Now if left out. | ## SaveFile [#savefile] Type. Explained in [Saves](https://ifloom.dev/docs/reference/saves#savefile). A save as a driver stores it, the state with its `SaveMeta`. `ifloom` is this envelope's format, 1, apart from the state's own `version` (`SAVE_VERSION`), which `loadState` carries forward. ```ts shape import type { SaveFile } from '@ifloom/engine' type SaveFile = { ifloom: 1 meta: SaveMeta state: GameState } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `ifloom` | `1` | | | The envelope's format, 1. | | `meta` | [`SaveMeta`](#savemeta) | | | The save's `SaveMeta`. | | `state` | [`GameState`](#gamestate) | | | The saved state, in the shape of the version that wrote it. | ## SaveListing [#savelisting] Type. Explained in [Saves](https://ifloom.dev/docs/reference/saves#savelisting). One entry of a game's saves from `list()`, a `SaveMeta` or a `BrokenSave`. Tell them apart with `'broken' in entry`. ```ts shape import type { SaveListing } from '@ifloom/engine' type SaveListing = SaveMeta | BrokenSave ``` Uses: [`SaveMeta`](#savemeta), [`BrokenSave`](#brokensave). ## SaveMeta [#savemeta] Type. Explained in [Saves](https://ifloom.dev/docs/reference/saves#savemeta). The facts a save records about itself, for a load page. `list()` and `write` return it. ```ts shape import type { SaveMeta } from '@ifloom/engine' type SaveMeta = { game: string slot: string name: string savedAt: number played: number turn: number when: string | null playerName: string | null packs: string[] plugins: Record gameVersion: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `game` | `string` | | | The id of the game the save belongs to. Reading or importing another game's save is refused. | | `slot` | `string` | | | The save's slot, such as `'1'`, `'auto'` or a name of the game's own. | | `name` | `string` | | | The save's name, the player's, else the plugins' `when` words, else the turn. | | `savedAt` | `number` | | | The time the save was written, in epoch milliseconds. | | `played` | `number` | | | The time played when the save was written, in milliseconds, as the runner counted it. | | `turn` | `number` | | | The number of turns that had passed when the save was written. | | `when` | `string \| null` | | | The time and place in the game in the plugins' words, such as "Day 3 · Wednesday morning · The café", or null when no plugin gives one. | | `playerName` | `string \| null` | | | The player's name for the save's game, such as the name the player typed, or null. It comes from the first `saveName` that answers, the game's `rules.saveName` first, then each plugin's. | | `packs` | `string[]` | | | The ids of the packs the game was loaded with. A mod among them that is missing on load is reported in `missingPacks`. | | `plugins` | `Record` | | | The version of each plugin the game was built with, by plugin id. | | `gameVersion` | `number` | | | The game's own version (`game.version`) the save was made with. 1 for a game that declares none. | ## Saves [#saves] Type. Explained in [Saves](https://ifloom.dev/docs/reference/saves#saves). One game's save store, returned by `saves`. No call rejects, and a driver's failure answers with a reason a player can read and the driver's error as its `cause`. ```ts shape import type { Saves } from '@ifloom/engine' type Saves = { readonly driver: SaveDriver write: (slot: string, state: GameState, extra?: SaveExtra | undefined) => Promise> read: (slot: string) => Promise> list: () => Promise> remove: (slot: string) => Promise> exportSlot: (slot: string) => Promise> importText: (text: string) => Result } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `driver` | [`SaveDriver`](#savedriver) | | | The driver that keeps the saves. | | `write` | `(slot: string, state:` [`GameState`](#gamestate)`, extra?:` [`SaveExtra`](#saveextra) `\| undefined) => Promise<`[`Result`](#result)`<…` | | | Writes a state to a slot and returns the save's `SaveMeta`. It fails with the `notSaved` string if the driver fails. | | `read` | `(slot: string) => Promise<`[`Result`](#result)`<`[`LoadedSave`](#loadedsave) `\| null>>` | | | Returns the save in a slot, carried forward and checked against this game, or null when the slot is empty. A failure gives the reason the save can't be read, or the `notLoaded` string if the driver fails. | | `list` | `() => Promise<`[`Result`](#result)`<`[`SaveListing[]`](#savelisting)`>>` | | | Returns the game's saves, newest first, then any that can't be read as `BrokenSave`s, by slot. It fails with the `notListed` string if the driver fails. Tell the two apart with `'broken' in entry`. A broken save can still be removed. | | `remove` | `(slot: string) => Promise<`[`Result`](#result)`>` | | | Deletes the save in a slot, and does nothing if the slot is empty. It fails with the `notRemoved` string if the driver fails. | | `exportSlot` | `(slot: string) => Promise<`[`Result`](#result)`>` | | | Returns a slot's save as text a player can keep as a file, or null if the slot is empty. It fails with the `notExported` string if the driver fails. | | `importText` | `(text: string) =>` [`Result`](#result)`<`[`LoadedSave`](#loadedsave)`>` | | | Returns the save in text from a file the player chose, checked against this game. A text that isn't this game's save fails with the reason. | ## saves [#saves-1] Function. Explained in [Saves](https://ifloom.dev/docs/reference/saves#saves-1). Returns the `Saves` store of a game, kept by a driver. The game chooses its slots' names, such as `'auto'`, `'quick'` or `'1'`. Each key starts with the game's id, because every game opened from disk shares one storage origin in Chromium, and itch.io serves many games from shared domains. The format's version is inside the save (`loadState`), never in the key, so a new version never orphans an old save. ```ts shape import { saves, type Game } from '@ifloom/engine' function saves(game: Game, driver: SaveDriver): Saves ``` Uses: [`Game`](#game), [`SaveDriver`](#savedriver), [`Saves`](#saves). ## SavingView [#savingview] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#savingview). The player's leave to save as the player sees it, in `view.saving`. A UI greys out or hides its Save button from it. ```ts shape import type { SavingView } from '@ifloom/engine' type SavingView = { allowed: boolean reason: string | null visible: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `allowed` | `boolean` | | | The leave to save, false while one of the game's `saveable` entries holds. | | `reason` | `string \| null` | | | The reason of the first `saveable` entry that holds. Null when saving is allowed. | | `visible` | `boolean` | | | The Save button's visibility, false while the entry that holds has `hide`. A UI then leaves Save off the screen rather than greying it out. | ## say [#say] Function. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#say). Returns a `{ say }` block, a spoken line under the id of who says it. Its beat is a `say` beat with that speaker and their name. `who` names the speaker as `@id: "…"` does in prose, an entity by reference or bare id (`'ava'` is `character:ava`), `'you'` for whoever the player is playing, or `'player'`. ```ts shape import { say } from '@ifloom/engine' function say(who: string, words: string, extras?: BlockExtras & { id?: string; voice?: string }): Block ``` Uses: [`BlockExtras`](#blockextras), [`Block`](#block). ## SceneBeat [#scenebeat] Type. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#scenebeat). One piece of a rendered body, in `view.scene.beats`, told apart by its `type`. Any beat can carry `ui`, the ui hints of the block it starts. ```ts shape import type { SceneBeat } from '@ifloom/engine' type SceneBeat = ({ type: 'text'; text: string; spans?: InlineSpan[] } | { type: 'say'; who: 'character' | 'player'; speaker?: EntityRef; name?: string; image?: string; text: string; voice?: string; spans?: InlineSpan[] } | { type: 'image'; src: string; alt?: string; size: BeatSize } | { type: 'video'; src: string; poster?: string; alt?: string; size: BeatSize; autoplay: boolean; loop: boolean; muted: boolean; controls: boolean } | { type: 'sound'; track: string } | { type: 'chose'; label: string }) & { ui?: Ui; section?: Ui } ``` Uses: [`InlineSpan`](#inlinespan), [`EntityRef`](#entityref), [`BeatSize`](#beatsize), [`Ui`](#ui), [`BlockUi`](#blockui). ## SceneMedia [#scenemedia] Type. Explained in [Scenes](https://ifloom.dev/docs/reference/scenes#scenemedia). A picture or a video in a scene's body, written as a `{ media }` block. Give a file as `src`, or have a pool draw one with `pool` and `tags`. ```ts shape import type { SceneMedia } from '@ifloom/engine' type SceneMedia = { src?: string pool?: string tags?: string[] alt?: string size?: 'inline' | 'wide' at?: 'lead' | 'end' video?: boolean controls?: boolean once?: boolean sound?: boolean poster?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `src` | `string` | yes | | The media's file, a path in the game's `art/` folder or a URL. | | `pool` | `string` | yes | | The pool in `game.media.pools` that draws the file. | | `tags` | `string[]` | yes | | The tags the pool's pick should have, most important first. See `poolCandidates`. | | `alt` | `string` | yes | | The media's alternative text, for a screen reader. | | `size` | `'inline' \| 'wide'` | yes | | The media's size, `'inline'` or `'wide'`. `'inline'` if left out. | | `at` | `'lead' \| 'end'` | yes | | The media's position. `lead` opens the scene, as an establishing picture does, and `end` follows the body. A block with none sits where it is in the body, in order with the prose. | | `video` | `boolean` | yes | | The video mark, which renders the file as a video. A `.mp4` or `.webm` file is a video without it. | | `controls` | `boolean` | yes | | The controls flag, which shows the player's controls, so the video waits to be started instead of playing by itself. | | `once` | `boolean` | yes | | The once flag, which plays the video once instead of looping. | | `sound` | `boolean` | yes | | The sound flag, which plays the video with sound instead of muted. | | `poster` | `string` | yes | | The still shown before the video plays, as a path like any picture's. | ## sceneOf [#sceneof] Function. Explained in [The game](https://ifloom.dev/docs/reference/game#sceneof). Returns the scene with this id from the game's content, or undefined when there is none. ```ts shape import { sceneOf, type Game } from '@ifloom/engine' function sceneOf(game: Game, id: string): DataScene | undefined ``` Uses: [`Game`](#game), [`DataScene`](#datascene). ## ScenePanel [#scenepanel] Type. Explained in [Panels](https://ifloom.dev/docs/reference/panels#scenepanel). A panel a scene declares in its `panel`, held open for as long as the scene is open. `with` is empty if left out. ```ts shape import type { ScenePanel } from '@ifloom/engine' type ScenePanel = { panel: string with?: PluginArgs } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `panel` | `string` | | | The panel's name, which the UI renders it by. | | `with` | [`PluginArgs`](https://ifloom.dev/docs/api/engine-plugin#pluginargs) | yes | | The panel's arguments, such as `{ vendor: 'cafe' }`. Empty if left out. | ## SceneUi [#sceneui] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#sceneui-choiceui-blockui-entityui-statui-and-gameui). The ui hints a scene or a room scene takes in its `ui`, for the UI that renders it. The engine declares none, and a UI package augments this interface with its own. ```ts shape import type { SceneUi } from '@ifloom/engine' type SceneUi = { // … } ``` Plugins add fields of their own to it, which their pages list. ## SCHEMA [#schema] Const. Explained in [Content and packs](https://ifloom.dev/docs/reference/content#schema). The content schema this engine reads. `PACK_STEPS` upgrade a pack of an older schema, and a newer one is refused. ```ts shape import { SCHEMA } from '@ifloom/engine' const SCHEMA: 1 ``` ## Screen [#screen] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#screen). One state rendered once by `screen`, with what each choice would apply, the pool picks and the audio tracks. ```ts shape import type { Screen } from '@ifloom/engine' type Screen = { scene: ScreenScene choices: ScreenChoice[] actions: ScreenChoice[] picture: PictureView | null plugins: Record picks: Record audio: AudioView & { tracks: Record } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `scene` | [`ScreenScene`](#screenscene) | | | The open scene as rendered, or the room when none is open. While a minigame is played, the minigame's key, title and words replace theirs, without their `ui`. `view.minigame` holds the running minigame's state. | | `choices` | [`ScreenChoice[]`](#screenchoice) | | | The open scene's visible choices, each with its effects, availability and price. It is empty for the room and while a minigame is played. | | `actions` | [`ScreenChoice[]`](#screenchoice) | | | The room's actions while no scene is open and no lock stops everything. The `actions` providers' come first (the game's rules', then each plugin's), then the game's own `actions`. | | `picture` | [`PictureView`](#pictureview) `\| null` | | | The open scene's layered picture and its hotspots, or null. | | `plugins` | `Record` | | | The plugins' views, by plugin id. | | `picks` | `Record` | | | The pool picks this screen made that the save doesn't hold yet, by pick key. The reducer records them. | | `audio` | [`AudioView`](#audioview) `& { tracks: Record }` | | | The audio that should be playing, as in `view.audio`, with `tracks` added. `tracks` gives the track each background channel resolved to (null for silence), and the reducer records them as started. | ## screen [#screen-1] Function. Explained in [The view](https://ifloom.dev/docs/reference/view#screen-1). Returns the `Screen` for a state, the open scene or the room rendered once. Use it when you need what `view` leaves out, such as each choice's effects. The screen holds the choices, actions, picture, plugins' views, pool picks and audio of that one render. Every choice's availability and effects come from that one render of the scene. `view` formats a screen for a UI. ```ts shape import { screen, type Game } from '@ifloom/engine' function screen(state: GameState, game: Game, options?: ViewOptions): Screen ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`ViewOptions`](#viewoptions), [`Screen`](#screen). ## ScreenChoice [#screenchoice] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#screenchoice). A choice or action on a `Screen`, with the effects pressing its button would apply. The view leaves the effects out. ```ts shape import type { ScreenChoice } from '@ifloom/engine' type ScreenChoice = { id: string label: string price?: Price disabled?: string tags?: string[] irreversible?: string ui?: Ui warning?: string command: Command effects: Effect[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The choice's or action's id. | | `label` | `string` | | | The button's label, with tokens filled. | | `price` | [`Price`](#price) | yes | | The button's price for this state, with its words in `text`. Left out when it's free. | | `disabled` | `string` | yes | | The reason the player can't press the button now, in the player's words. Left out when they can. | | `tags` | `string[]` | yes | | The choice's or action's tags, for a UI to style or filter it by. | | `irreversible` | `string` | yes | | The warning that the choice or action can't be undone, for a UI to show on its button. | | `ui` | [`Ui`](#ui)`<`[`ChoiceUi`](#choiceui)`>` | yes | | The choice's or action's `ui` hints, unchanged from content. Left out with none, and typed by `ChoiceUi`. | | `warning` | `string` | yes | | The reason a plugin's guard gives for refusing the button softly, such as running past dawn. The player can press it, but the reducer refuses it, so a UI shows the warning instead. | | `command` | [`Command`](#command) | | | The command a UI sends when the player presses the button, as `runner.apply(choice.command)`. | | `effects` | [`Effect[]`](#effect) | | | The effects pressing the button would apply, such as a choice's effects or an action's cost and effects. | ## ScreenScene [#screenscene] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#screenscene). The scene on a `Screen`, or the room when none is open, without its choices and picture. ```ts shape import type { ScreenScene } from '@ifloom/engine' type ScreenScene = { id: string | null key: string title: string body: string beats: SceneBeat[] fresh: number tags: string[] speaker: SpeakerView | null image: string | null ui?: Ui } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string \| null` | | | The open scene's id, or null for the room. | | `key` | `string` | | | The screen's key, which changes when the screen does and only then. It is `scene:` while a scene is open, `minigame:` while a minigame is played, `room:` for a plugin's room scene and `room` without one. | | `title` | `string` | | | The screen's title, the scene's or the room's. | | `body` | `string` | | | The body as markup text. A UI renders `beats`, which are this text parsed. | | `beats` | [`SceneBeat[]`](#scenebeat) | | | The body parsed into beats, such as paragraphs, speech, pictures and past choices, ready to render. | | `fresh` | `number` | | | The index of the first beat the flow's last step added, from its `chose` beat on, so a UI can animate only those. It's 0 for the room and before the visit's first step. | | `tags` | `string[]` | | | The scene's tags, for a UI to style it by. | | `speaker` | [`SpeakerView`](#speakerview) `\| null` | | | The scene's `speaker`, read from their entity. Null without one, or when it names no entity. | | `image` | `string \| null` | | | The speaker's picture to show with the scene, or null without one. | | `ui` | [`Ui`](#ui)`<`[`SceneUi`](#sceneui)`>` | yes | | The scene's `ui` hints, or the room scene's when no scene is open, unchanged from content. Left out with none, and typed by `SceneUi`. | ## Select [#select] Type. Explained in [Entities](https://ifloom.dev/docs/reference/entities#select). A selection of entities that a `count` or an `each` reads. Every entity in the game when it sets nothing. It narrows to those `of` a kind, those with a tag or a trait, and those `where` holds for, with `'$'` as each one. Things someone has are `where: { owned: '$' }`. ```ts shape import type { Select } from '@ifloom/engine' type Select = { of?: string tag?: string trait?: string where?: Condition } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `of` | `string` | yes | | The kind the entities are of. | | `tag` | `string` | yes | | The tag the entities have, their kind's or their own. | | `trait` | `string` | yes | | The id of a trait the entities carry. | | `where` | [`Condition`](#condition) | yes | | The condition each entity must meet, with `'$'` as that entity. | ## SettingDef [#settingdef] Type. Explained in [Settings](https://ifloom.dev/docs/reference/settings#settingdef). A setting the game declares in `settings`, which the player changes on a settings page. A `play` setting is saved with the state, and a `ui` setting is kept only in the profile. Its `type` sets the rest of its fields. A `toggle` has a true/false `default`. A `choice` has `options`, each a `value` with its `label`, and one value as its `default`. A `range` has `min`, `max`, an optional `step` and a number as its `default`. ```ts shape import type { SettingDef } from '@ifloom/engine' type SettingDef = { id: string; label: string; affects?: 'play' | 'ui' } & ({ type: 'toggle'; default: boolean } | { type: 'choice'; options: { value: string; label: string }[]; default: string } | { type: 'range'; min: number; max: number; step?: number; default: number }) ``` ## SettingView [#settingview] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#settingview). A setting as the player sees it on a settings page, in `view.settings`. ```ts shape import type { SettingView } from '@ifloom/engine' type SettingView = { id: string label: string type: 'toggle' | 'choice' | 'range' affects: 'play' | 'ui' options?: { value: string; label: string }[] min?: number max?: number step?: number default: KvValue value: KvValue | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The setting's id. | | `label` | `string` | | | The setting's label. | | `type` | `'toggle' \| 'choice' \| 'range'` | | | The setting's type, a `toggle` (on or off), a `choice` among `options`, or a `range` from `min` to `max`. | | `affects` | `'play' \| 'ui'` | | | The setting's reach. The save keeps a `play` setting, which changes the game, and the profile keeps a `ui` setting, which changes only how the game is shown. | | `options` | `{ value: string; label: string }[]` | yes | | The options of a `choice` setting, each a value with its label. | | `min` | `number` | yes | | The lowest value of a `range` setting. | | `max` | `number` | yes | | The highest value of a `range` setting. | | `step` | `number` | yes | | The step of a `range` setting. Left out when the setting gives none, which means 1. | | `default` | [`KvValue`](#kvvalue) | | | The setting's default, its value until the player changes it. | | `value` | [`KvValue`](#kvvalue) `\| null` | | | The value of a `play` setting in this game. Null for a `ui` setting, which the UI reads from the profile. | ## Someone [#someone] Type. Explained in [Entities](https://ifloom.dev/docs/reference/entities#someone-and-played). Someone, `'player'`, a unique entity (`'character:ava'`) or `'you'`. `'you'` is whoever the player is playing now, the player unless a `you` effect switched to a protagonist. It's who a `receive` gives a thing to. ```ts shape import type { Someone } from '@ifloom/engine' type Someone = EntityRef | typeof PLAYER | typeof YOU ``` Uses: [`EntityRef`](#entityref). ## SpeakerView [#speakerview] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#speakerview). A speaker or sender as the player sees them, in `view.scene.speaker` and in plugins' views. ```ts shape import type { SpeakerView } from '@ifloom/engine' type SpeakerView = { id: string ref: EntityRef name: string image: string | null ui?: Ui } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The speaker's id in the content, a bare id (`'ava'`) or a reference (`'character:ava'`). | | `ref` | [`EntityRef`](#entityref) | | | The speaker's entity. | | `name` | `string` | | | The speaker's name, read from their entity with its tokens filled. | | `image` | `string \| null` | | | The speaker's picture, from their entity through `artSrc`, or null when the entity has none. | | `ui` | [`Ui`](#ui)`<`[`EntityUi`](#entityui)`>` | yes | | The speaker's entity's ui hints (see `EntityUi`). Left out when the entity has none. | ## startingState [#startingstate] Function. Explained in [Commands](https://ifloom.dev/docs/reference/commands#startingstate). Returns the state of a new game, with every field at its start value. With `carry`, the New Game+'s carried values go over it. Features then work out the fields that read the whole state, such as the audio the opening screen starts playing. ```ts shape import { startingState, type Game } from '@ifloom/engine' function startingState(game: Game, options?: StartOptions): GameState ``` Uses: [`Game`](#game), [`StartOptions`](#startoptions), [`GameState`](#gamestate). ## StartOptions [#startoptions] Type. Explained in [Commands](https://ifloom.dev/docs/reference/commands#startoptions). Settings for `startingState`. A new game left without them gets a seed hashed from the game's id. ```ts shape import type { StartOptions } from '@ifloom/engine' type StartOptions = { seed?: number kv?: Record settings?: Record carry?: GameState } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `seed` | `number` | yes | | The new game's random seed. Hashed from the game's id if left out, so tests draw the same. | | `kv` | `Record` | yes | | The kv keys written before the first scene, such as a name from a title page or a difficulty. | | `settings` | `Record` | yes | | The player's stored values for the game's `play` settings, such as the profile's `core:settings`, which `browserRunner` passes. A missing or invalid value starts at its default, and an undeclared id is ignored. | | `carry` | [`GameState`](#gamestate) | yes | | The state a finished game ended on, for a New Game+. The engine copies the stats, kv keys and things the game's `carryOver` lists from it. | ## StatDef [#statdef] Type. Explained in [Stats](https://ifloom.dev/docs/reference/stats#statdef). A stat the game declares in `stats`, a number it keeps for the player or for each entity of a kind. The engine has no stats of its own. Charisma, money, energy and a reputation are stats. ```ts shape import type { StatDef } from '@ifloom/engine' type StatDef = { id: string of?: string label: string start?: number min?: Amount max?: Amount visible?: Condition listed?: boolean spendable?: boolean lacking?: StatWords format?: StatWords derive?: Formula levels?: StatLevels round?: StatRound ui?: Ui } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The stat's id. | | `of` | `string` | yes | | The kind of entity the stat is kept on, such as `'staff'` for every member of staff. The player's stat if left out. | | `label` | `string` | | | The stat's label, such as "Charisma" or "Money". | | `start` | `number` | yes | | The stat's value in a new game. 0 if left out. | | `min` | [`Amount`](#amount) | yes | | The stat's lowest value. 0 if left out, and an `Amount`, so a floor can move with the game (`{ stat: 'debtLimit' }`). | | `max` | [`Amount`](#amount) | yes | | The stat's highest value. 100 if left out, and an `Amount`, so a ceiling can move with the game. It can read another stat (`{ stat: 'fitness' }`) or a value by name (`{ value: 'game/energyMax' }`, with `with` for its arguments). A ceiling that reads the stat itself reads 100. | | `visible` | [`Condition`](#condition) | yes | | The stat's condition. The player can see the stat only while it holds, and always if left out. | | `listed` | `boolean` | yes | | The stat's listed mark, false to leave it out of `view.stats` for a game that shows it its own way, as a gauge or a purse. True if left out. | | `spendable` | `boolean` | yes | | The stat's spendable mark, true for a stat spent on things, such as money, energy or time. A choice's or action's price is made of spendable stats. | | `lacking` | [`StatWords`](#statwords) | yes | | The refusal when a cost needs more than the player has, with `{n}` for the amount. Without it the engine says "Not enough" and the label. It's one line (`'Not enough on you.'`, `'Need {n} energy.'`) or one for 1 and one for any other amount, as `format` takes. | | `format` | [`StatWords`](#statwords) | yes | | The stat's value written for the player, with `{n}` for the number, such as `'£{n}'` or `'{n} energy'`. The bare number if left out. For words that change with the number, give one for 1 and one for any other, `{ one: '{n} coin', other: '{n} coins' }`. | | `derive` | [`Formula`](#formula) | yes | | The formula the stat is worked out from instead of being kept, such as `{ sum: ['strength', 'agility'] }`. A derived stat is read like any stat and never written, and the loader reports a `stat` effect on one. | | `levels` | [`StatLevels`](#statlevels) | yes | | The levels the stat passes as it grows. None if left out. | | `round` | [`StatRound`](#statround) | yes | | The stat's rounding when it's read, `'floor'`, `'round'` or `'ceil'` to a whole number, or `'none'`. `'none'` if left out. It applies last, after `derive` and any plugin's modifiers, and the value is then held to the range. The kept value underneath is never rounded. | | `ui` | [`Ui`](#ui)`<`[`StatUi`](#statui)`>` | yes | | The stat's ui hints, carried to its view as written. | ## StatKey [#statkey] Type. Explained in [Common types](https://ifloom.dev/docs/reference/common#statkey). A stat's id. The game declares each stat with a `StatDef`. ```ts shape import type { StatKey } from '@ifloom/engine' type StatKey = string ``` ## statLevel [#statlevel] Function. Explained in [Stats](https://ifloom.dev/docs/reference/stats#statlevel). Returns the level a stat with `levels` has reached, with the value the next level starts at and the progress towards it. Returns undefined for a stat with no levels. `next` is null at the top level. `progress` runs from 0 at this level's start to 1 at the next one's, and is 1 at the top. ```ts shape import { statLevel, type Game } from '@ifloom/engine' function statLevel(state: GameState, game: Game, id: string, of?: string): { level: number; next: number | null; progress: number } | undefined ``` Uses: [`GameState`](#gamestate), [`Game`](#game). ## StatLevels [#statlevels] Type. Explained in [Stats](https://ifloom.dev/docs/reference/stats#statlevels). The levels a stat declares in its `levels`, thresholds it passes as it grows. It can raise a notice when the player's stat passes one. ```ts shape import type { StatLevels } from '@ifloom/engine' type StatLevels = { at: number[] names?: string[] notice?: string hidden?: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `at` | `number[]` | | | The value each level starts at, lowest first. A value below the first is level 0. | | `names` | `string[]` | yes | | The levels' names, one for each level from level 0 (below the first threshold) up, so one more than `at`, such as `['Couch potato', 'Jogger', 'Runner']` for `at: [10, 25]`. The view gives the stat's level its name. | | `notice` | `string` | yes | | The notice raised, tagged `level`, when a command takes the player's stat up a level, such as `'{label} is now level {level}.'`. The engine fills `{label}`, `{level}` and `{name}`, the level's name, and raises no notice if left out. The view fills its tokens as it does any notice's. | | `hidden` | `boolean` | yes | | The levels' hidden mark, true to keep them from the player. The view then gives the stat no `level`, and `{ level }` conditions still read them. Use it for a hidden rating, such as how much a character trusts you. | ## statOf [#statof] Function. Explained in [Stats](https://ifloom.dev/docs/reference/stats#statof). Returns the stat the game declares with this id. Undefined when there's none. ```ts shape import { statOf, type Game } from '@ifloom/engine' function statOf(game: Game, id: string): StatDef | undefined ``` Uses: [`Game`](#game), [`StatDef`](#statdef). ## StatRound [#statround] Type. Explained in [Stats](https://ifloom.dev/docs/reference/stats#statround). The rounding a stat declares in its `round`, applied when the stat is read. ```ts shape import type { StatRound } from '@ifloom/engine' type StatRound = 'none' | 'floor' | 'round' | 'ceil' ``` ## Stats [#stats] Type. Explained in [Entities, things and traits](https://ifloom.dev/docs/explanation/entities-and-traits#stats-the-kv-store-and-storylines). The current values of the stats the save keeps, by stat id. ```ts shape import type { Stats } from '@ifloom/engine' type Stats = { [key: string]: number } ``` ## StatUi [#statui] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#sceneui-choiceui-blockui-entityui-statui-and-gameui). The ui hints a stat takes in its `ui`. The engine declares none, and a UI package augments this interface with its own. ```ts shape import type { StatUi } from '@ifloom/engine' type StatUi = { // … } ``` Plugins add fields of their own to it, which their pages list. ## statValue [#statvalue] Function. Explained in [Stats](https://ifloom.dev/docs/reference/stats#statvalue). Returns a stat's value, the player's or, with `of`, an entity's (`'staff:ana'`). An entity that isn't there reads 0. A derived stat is worked out from its formula and held to its range. A kept stat the save doesn't have yet reads as its `start`. ```ts shape import { statValue, type Game } from '@ifloom/engine' function statValue(state: GameState, game: Game, id: string, of?: string): number ``` Uses: [`GameState`](#gamestate), [`Game`](#game). ## StatView [#statview] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#statview). A stat as the player sees it, in `view.stats` and `view.statsById`, with its value, its range, the value written out and its hints. ```ts shape import type { StatView } from '@ifloom/engine' type StatView = { key: StatKey label: string value: number min: number max: number text: string level?: { level: number; name: string | null; next: number | null; progress: number } ui?: Ui } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `key` | [`StatKey`](#statkey) | | | The stat's id. | | `label` | `string` | | | The stat's label. | | `value` | `number` | | | The stat's value as play reads it, kept or derived, with the plugins' modifiers, rounded and held to its range. | | `min` | `number` | | | The stat's lowest value now. | | `max` | `number` | | | The stat's highest value now. | | `text` | `string` | | | The stat's value written with its `format`, such as `'12 coins'` or `'80%'`. The bare number with no format. | | `level` | `{ level: number; name: string \| null; next: number \| null; progress: number }` | yes | | The stat's place in its `levels`, with its level and that level's name, null without `levels.names`. It also has the value the next level starts at (null at the top) and the progress towards it, from 0 to 1. It's left out for a stat with no levels or hidden ones. | | `ui` | [`Ui`](#ui)`<`[`StatUi`](#statui)`>` | yes | | The stat's ui hints, kept as written. Left out if it has none. | ## StatWords [#statwords] Type. Explained in [Stats](https://ifloom.dev/docs/reference/stats#statwords). A stat's words for a number, with `{n}` for it. It's one line for every number, or `one` for exactly 1 and `other` for the rest. ```ts shape import type { StatWords } from '@ifloom/engine' type StatWords = string | { one: string; other: string } ``` ## StoryletFields [#storyletfields] Type. Explained in [Storylets](https://ifloom.dev/docs/reference/storylets#storyletfields). The fields that make a scene a storylet, a scene the `{ scene: { from } }` effect draws at random from a named set. They name the sets, the scene's weight and when it can be drawn. ```ts shape import type { StoryletFields } from '@ifloom/engine' type StoryletFields = { drawnFrom?: string[] weight?: number when?: Condition } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `drawnFrom` | `string[]` | yes | | The sets the scene can be drawn from, by name, such as `['cafe']`. A `{ scene: { from: 'cafe' } }` effect draws one of the scenes that name `'cafe'` here. It's separate from `tags`, which only style the scene. | | `weight` | `number` | yes | | The scene's weight in a draw, against the other scenes it could be drawn with. 1 if left out, and it needs `drawnFrom`. | | `when` | [`Condition`](#condition) | yes | | The storylet's condition. The scene can be drawn only while it holds, but a `scene` command or effect that names the scene opens it regardless. | ## StorylineDef [#storylinedef] Type. Explained in [Storylines](https://ifloom.dev/docs/reference/storylines#storylinedef). A storyline the game declares in `storylines`, a thread of the story with its own kv keys. A storyline can close until a later turn. ```ts shape import type { StorylineDef } from '@ifloom/engine' type StorylineDef = { id: string name: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The storyline's id, read as `storyline:` in a kv effect's `of`. | | `name` | `string` | | | The storyline's name, as the player reads it. | ## storylineOpen [#storylineopen] Function. Explained in [Storylines](https://ifloom.dev/docs/reference/storylines#storylineopen). Returns true when the storyline is open. A storyline closed until a turn opens again once that turn comes. ```ts shape import { storylineOpen } from '@ifloom/engine' function storylineOpen(state: GameState, id: string): boolean ``` Uses: [`GameState`](#gamestate). ## StorylineState [#storylinestate] Type. Explained in [Storylines](https://ifloom.dev/docs/reference/storylines#storylinestate). The state a save keeps for one storyline. The engine reads its definition from content. ```ts shape import type { StorylineState } from '@ifloom/engine' type StorylineState = { closedUntil: number | null kv: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `closedUntil` | `number \| null` | | | The storyline's turn to open again, or null while it is open. | | `kv` | `Record` | | | The storyline's own kv keys, read and written with `of: 'storyline:'`. | ## StringKey [#stringkey] Type. Explained in [Strings](https://ifloom.dev/docs/reference/strings#stringkey-and-strings). A key of the engine's own lines in `STRINGS`. ```ts shape import type { StringKey } from '@ifloom/engine' type StringKey = keyof typeof STRINGS ``` ## stringOf [#stringof] Function. Explained in [Strings](https://ifloom.dev/docs/reference/strings#stringof). Returns the line for a key with each `{name}` token filled from `vars`. Returns the key itself when no table has it, so a missing line shows. The engine looks in the game's strings, then the plugin's defaults for a `/` key, then its own. A token with no value in `vars` stays as written. ```ts shape import { stringOf, type Game } from '@ifloom/engine' function stringOf(game: Game | undefined, key: StringKey | (string & {}), vars?: Record): string ``` Uses: [`Game`](#game), [`StringKey`](#stringkey). ## STRINGS [#strings] Const. Explained in [Strings](https://ifloom.dev/docs/reference/strings#strings). The engine's own lines for the player, in English, by key. A game replaces any of them in its content's or a pack's `strings`, so a translation can ship as a mod. The engine fills each `{name}` token from the values it has when it shows the line. Plugins declare their own defaults under their id (`quests/notDoing`), and a game replaces those the same way. ```ts shape import { STRINGS } from '@ifloom/engine' const STRINGS: { finishFirst: 'Finish this first.' notSupported: 'This game does not do that.' noSuchAction: 'There is no such thing to do.' notEnough: 'Not enough {stat}.' noSuchScene: 'There is no such scene.' nothingToChoose: 'There is nothing to choose.' notOnOffer: 'That is not on offer.' noSuchThing: 'There is no such thing.' badArgument: 'That can’t be done: "{arg}" must be {kind}.' noSuchInput: 'There is no such thing to fill in.' notNow: 'Not now.' enterSomething: 'Enter something first.' enterNumber: 'Enter a number.' tooLong: 'Keep it to {n} characters.' between: 'Between {min} and {max}.' atLeast: 'At least {min}.' atMost: 'At most {max}.' notAnOption: 'That is not one of the options.' noMinigame: 'Nothing is being played.' noPanel: 'Nothing is open.' notLive: 'That does nothing now.' noTimer: 'Nothing is counting down.' tickLength: 'A tick is a number of milliseconds above 0.' noSuchSetting: 'There is no such setting.' notAGameSetting: 'That setting does not change the game.' noProfile: 'This game keeps no settings between plays.' onOrOff: 'Choose on or off.' inSteps: 'In steps of {step}.' lookAround: 'Look around' priceSeparator: ' · ' 'minigame.up': 'Up' 'minigame.down': 'Down' 'minigame.left': 'Left' 'minigame.right': 'Right' 'minigame.space': 'Space' you: 'You' momentPassed: 'The moment has passed.' done: 'Already done.' notASave: 'That is not a save file.' otherGame: 'That save belongs to another game ({game}).' saveTooOld: 'That save is from a version this game cannot read.' pluginNewer: 'That save was made with a newer version of {plugin}.' gameNewer: 'That save was made with a newer version of this game.' pluginUnreadable: 'That save\'s {plugin} is from a version this game cannot read.' noSaves: 'This game keeps no saves.' emptySlot: 'Nothing is saved there.' notSaved: 'The game could not be saved.' notLoaded: 'The game could not be loaded.' notListed: 'The saves could not be read.' notRemoved: 'The save could not be deleted.' notExported: 'The save could not be exported.' turnLabel: 'Turn {turn}' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `finishFirst` | `'Finish this first.'` | | | The refusal of a command that can't run while a scene or minigame is open. | | `notSupported` | `'This game does not do that.'` | | | The refusal of a command no feature, plugin or rule of the game handles. | | `noSuchAction` | `'There is no such thing to do.'` | | | The refusal of an action or a game command the game doesn't declare. | | `notEnough` | `'Not enough {stat}.'` | | | The refusal of a choice or action the player can't pay for, with `{stat}` the stat's label. | | `noSuchScene` | `'There is no such scene.'` | | | The refusal of entering a scene the game doesn't declare. | | `nothingToChoose` | `'There is nothing to choose.'` | | | The refusal of a choice while no scene is open. | | `notOnOffer` | `'That is not on offer.'` | | | The refusal of a choice or action that isn't offered now. | | `noSuchThing` | `'There is no such thing.'` | | | The refusal of a command that names an entity the game doesn't have. | | `badArgument` | `'That can’t be done: "{arg}" must be {kind}.'` | | | The refusal of a plugin command whose argument `{arg}` isn't a `{kind}`. | | `noSuchInput` | `'There is no such thing to fill in.'` | | | The refusal of the `input` command for an input the game doesn't declare. | | `notNow` | `'Not now.'` | | | The refusal of the `input` command while the input's `when` doesn't hold. | | `enterSomething` | `'Enter something first.'` | | | The refusal of an empty value for a text input. | | `enterNumber` | `'Enter a number.'` | | | The refusal of a value that isn't a number for a number input or a number setting. | | `tooLong` | `'Keep it to {n} characters.'` | | | The refusal of a text value longer than `{n}` characters. | | `between` | `'Between {min} and {max}.'` | | | The refusal of a number outside an input's or a range setting's `{min}` and `{max}`. | | `atLeast` | `'At least {min}.'` | | | The refusal of a number below the input's `{min}`. | | `atMost` | `'At most {max}.'` | | | The refusal of a number above the input's `{max}`. | | `notAnOption` | `'That is not one of the options.'` | | | The refusal of a value that isn't one of an input's or a setting's options. | | `noMinigame` | `'Nothing is being played.'` | | | The refusal of a minigame command while no minigame runs. | | `noPanel` | `'Nothing is open.'` | | | The refusal of `closePanel` while no panel is open. | | `notLive` | `'That does nothing now.'` | | | The refusal of a minigame input that does nothing in the minigame's current state. | | `noTimer` | `'Nothing is counting down.'` | | | The refusal of the `tick` command while no timer or minigame clock runs. | | `tickLength` | `'A tick is a number of milliseconds above 0.'` | | | The refusal of a `tick` whose `ms` isn't a number above 0. | | `noSuchSetting` | `'There is no such setting.'` | | | The refusal of a setting the game doesn't declare. | | `notAGameSetting` | `'That setting does not change the game.'` | | | The refusal of a `ui` setting sent as a command, since only a `play` setting changes the state. | | `noProfile` | `'This game keeps no settings between plays.'` | | | The refusal of a setting change when the runner keeps no profile. | | `onOrOff` | `'Choose on or off.'` | | | The refusal of a value other than true or false for a toggle setting. | | `inSteps` | `'In steps of {step}.'` | | | The refusal of a range setting's value that isn't a whole number of `{step}`s. | | `lookAround` | `'Look around'` | | | The label of the button that leaves a scene the game no longer declares. | | `priceSeparator` | `' · '` | | | The separator between the parts of a price on a button, such as `2 coins · until evening`. | | `minigame.up` | `'Up'` | | | The label of a minigame input's button, keyed `minigame.`. An input with no line shows its own name with a capital. A game labels its own inputs the same way, as in `'minigame.jump': 'Jump'`. | | `minigame.down` | `'Down'` | | | The label of the minigame input `down`. | | `minigame.left` | `'Left'` | | | The label of the minigame input `left`. | | `minigame.right` | `'Right'` | | | The label of the minigame input `right`. | | `minigame.space` | `'Space'` | | | The label of the minigame input `space`. | | `you` | `'You'` | | | The name the player's spoken lines (`@you: "Hi."`) show when no `saveName` gives one. A game in another language sets its own. | | `momentPassed` | `'The moment has passed.'` | | | The text shown for an open scene the game no longer declares, such as after a mod is removed. | | `done` | `'Already done.'` | | | The reason on a choice or action with `once`, after the player has taken it that game or turn. | | `notASave` | `'That is not a save file.'` | | | The refusal of an imported file or a state that isn't a save. | | `otherGame` | `'That save belongs to another game ({game}).'` | | | The refusal of a save made by another game, with `{game}` that game's id. | | `saveTooOld` | `'That save is from a version this game cannot read.'` | | | The refusal of a save from an engine version too old for the engine's steps to carry forward. | | `pluginNewer` | `'That save was made with a newer version of {plugin}.'` | | | The refusal of a save made with a newer version of the plugin `{plugin}`. | | `gameNewer` | `'That save was made with a newer version of this game.'` | | | The refusal of a save made with a newer version of the game. | | `pluginUnreadable` | `'That save\'s {plugin} is from a version this game cannot read.'` | | | The refusal of a save whose state for the plugin `{plugin}` its migrations can't carry forward. | | `noSaves` | `'This game keeps no saves.'` | | | The refusal of a save or load when the runner keeps no saves. | | `emptySlot` | `'Nothing is saved there.'` | | | The refusal of loading a slot that holds no save. | | `notSaved` | `'The game could not be saved.'` | | | The reason a save failed to write. | | `notLoaded` | `'The game could not be loaded.'` | | | The reason a save failed to read. | | `notListed` | `'The saves could not be read.'` | | | The reason the saves failed to list. | | `notRemoved` | `'The save could not be deleted.'` | | | The reason a save failed to delete. | | `notExported` | `'The save could not be exported.'` | | | The reason a save failed to export. | | `turnLabel` | `'Turn {turn}'` | | | The save's name when no plugin's `saveName` gives one. | ## Strings [#strings-1] Type. Explained in [Strings](https://ifloom.dev/docs/reference/strings#stringkey-and-strings). A table of lines a game, pack or plugin gives by key. A key is an engine key or a plugin's `/`. ```ts shape import type { Strings } from '@ifloom/engine' type Strings = { you?: string done?: string finishFirst?: string notSupported?: string noSuchAction?: string notEnough?: string noSuchScene?: string nothingToChoose?: string notOnOffer?: string noSuchThing?: string badArgument?: string noSuchInput?: string notNow?: string enterSomething?: string enterNumber?: string tooLong?: string between?: string atLeast?: string atMost?: string notAnOption?: string noMinigame?: string noPanel?: string notLive?: string noTimer?: string tickLength?: string noSuchSetting?: string notAGameSetting?: string noProfile?: string onOrOff?: string inSteps?: string lookAround?: string priceSeparator?: string 'minigame.up'?: string 'minigame.down'?: string 'minigame.left'?: string 'minigame.right'?: string 'minigame.space'?: string momentPassed?: string notASave?: string otherGame?: string saveTooOld?: string pluginNewer?: string gameNewer?: string pluginUnreadable?: string noSaves?: string emptySlot?: string notSaved?: string notLoaded?: string notListed?: string notRemoved?: string notExported?: string turnLabel?: string // … } ``` It also takes any other key: `[key: string]: string`. Its fields are the keys of `Partial> & Record`, so they grow when a game or a plugin adds to those. ## text [#text] Function. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#text). Returns a `{ text }` block of words in place, one paragraph or several. A blank line between lines starts a new paragraph. It strips the indentation every line shares and the blank lines at either end, so the words can sit indented in your code. The words are read as prose is, so `@ava: "…"` is a spoken line, `[[img:…]]` a picture and `{{key}}` a token. An `id` keys the block in a translation's words table as `scene..text.`, and a hash of its words keys it without one. ```ts shape import { text } from '@ifloom/engine' function text(words: string, extras?: BlockExtras & { id?: string }): Block ``` Uses: [`BlockExtras`](#blockextras), [`Block`](#block). ## TextLine [#textline] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#textline). A line of words a player reads, a prose line or words in place. A UI checks the `[[ui:…]]` pieces in it. ```ts shape import type { TextLine } from '@ifloom/engine' type TextLine = { where: string text: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `where` | `string` | | | The place the line is, written as a `Problem`'s `where` is. | | `text` | `string` | | | The line's words, markup and all. | ## TimerDef [#timerdef] Type. Explained in [Timers](https://ifloom.dev/docs/reference/timers#timerdef). A timer the game declares in `timers`, a named countdown in real time. The `timer` effect starts it, and its `effects` run when it runs out. ```ts shape import type { TimerDef } from '@ifloom/engine' type TimerDef = { id: string label?: string ms: number effects?: EffectRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The timer's id, which the `timer` effect and condition name. | | `label` | `string` | yes | | The timer's label, such as `'The phone'`. None if left out. | | `ms` | `number` | | | The timer's length when started, in milliseconds. | | `effects` | [`EffectRef[]`](#effectref) | yes | | The timer's effects, which run when it runs out. Stopping it with `to: null` runs none of them. | ## TimerView [#timerview] Type. Explained in [Timers](https://ifloom.dev/docs/reference/timers#timerview). A running timer as the player sees it, in `view.timers`. The view never lists its effects. ```ts shape import type { TimerView } from '@ifloom/engine' type TimerView = { id: string label: string | null left: number total: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The timer's id. | | `label` | `string \| null` | | | The timer's `label`, or null. | | `left` | `number` | | | The milliseconds the timer has left. | | `total` | `number` | | | The timer's whole length in milliseconds, for a bar. `left / total` is the share left. | ## Times [#times] Type. Explained in [Game state](https://ifloom.dev/docs/reference/state#times). A count of times something happened, with the turns of the first and the last. `GameState.seen` keeps one per scene and `GameState.chosen` one per choice. ```ts shape import type { Times } from '@ifloom/engine' type Times = { n: number first: number last: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `n` | `number` | | | The number of times it happened. | | `first` | `number` | | | The turn it first happened on. | | `last` | `number` | | | The turn it last happened on. | ## TrackDef [#trackdef] Type. Explained in [Audio](https://ifloom.dev/docs/reference/audio#trackdef). A track the game declares in `audio.tracks`, a sound file it ships. It plays on the `'sfx'` channel unless `channel` says otherwise. ```ts shape import type { TrackDef } from '@ifloom/engine' type TrackDef = { src: string channel?: string loop?: boolean volume?: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `src` | `string` | | | The track's file, under the game's `audio/` folder, such as `'audio/cafe.ogg'`. `audioSrc` turns it into a path. | | `channel` | `string` | yes | | The channel the track plays on. `'sfx'` if left out. A `sound` effect and `[[sound:id]]` play it there, and a background channel takes only a track whose channel is a background one. | | `loop` | `boolean` | yes | | The track's loop mark, true to repeat it while it's on a background channel. True if left out. | | `volume` | `number` | yes | | The track's own volume, from 0 to 1. 1 if left out. | ## TraitData [#traitdata] Type. Explained in [Entities](https://ifloom.dev/docs/reference/entities#traitregistry-and-traitdata). The data trait `K` takes, as `TraitRegistry` declares it, or `unknown` for an undeclared id. ```ts shape import type { TraitData } from '@ifloom/engine' type TraitData = K extends keyof TraitRegistry ? TraitRegistry[K] : unknown ``` Uses: [`TraitRegistry`](#traitregistry). ## traitOf [#traitof] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#traitof). Returns the data of one trait on one entity in play, typed by `TraitRegistry`, or undefined when it lacks the trait. A declared entity reads as `declaredTrait` does. An entity made in play reads the trait data it was made with, laid over its `like`'s, or else over its kind's default. ```ts shape import { traitOf, type Game } from '@ifloom/engine' function traitOf(state: GameState, game: Game, ref: string, id: K): TraitData | undefined ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`TraitData`](#traitdata). ## TraitRegistry [#traitregistry] Type. Explained in [Entities](https://ifloom.dev/docs/reference/entities#traitregistry-and-traitdata). The registry of the traits plugins declare, by trait id, with the data each takes. A plugin augments it to type `declaredTrait` and the `traits` field of entities, kinds and `traits` tables. ```ts fragment declare module '@ifloom/engine' { interface TraitRegistry { 'laundry/washable': { temp: number; gentle?: boolean } } } ``` ```ts shape import type { TraitRegistry } from '@ifloom/engine' type TraitRegistry = { // … } ``` Plugins add fields of their own to it, which their pages list. ## TraitSource [#traitsource] Type. Explained in [Entities](https://ifloom.dev/docs/reference/entities#traitsource). The parts of a game its traits are worked out from, its kinds, its entities and its `traits` table. ```ts shape import type { TraitSource } from '@ifloom/engine' type TraitSource = { kinds?: KindDef[] entities?: EntityDef[] traits?: TraitTable } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `kinds` | [`KindDef[]`](#kinddef) | yes | | The game's kinds, the sorts of entity it keeps, each with its own stats. | | `entities` | [`EntityDef[]`](#entitydef) | yes | | The game's entities at the start. Play can create more. | | `traits` | [`TraitTable`](#traittable) | yes | | The game's traits, by trait id and then entity. In content given to `loadGame` they're rows over what entities declare. On the game `loadGame` returns, they're every entity's traits, worked out. Read them with `declaredTrait`. | ## TraitTable [#traittable] Type. Explained in [Entities](https://ifloom.dev/docs/reference/entities#traittable). A table of trait data by trait id and then entity, such as `{ 'laundry/washable': { 'clothing:scarf': { temp: 30 } } }`. In content, its rows give entities a trait over the entity's own. On a loaded game, it holds every entity's traits, worked out. ```ts shape import type { TraitTable } from '@ifloom/engine' type TraitTable = { [key: string]: Record<`${string}:${string}`, unknown> // … } ``` Plugins add fields of their own to it, which their pages list. ## translatableFields [#translatablefields] Function. Explained in [The words table](https://ifloom.dev/docs/reference/words#translatablefields). Returns every field of the game's content a player reads and a translation can reword, each once, by its words-table key. Load the game without its translation packs to list the words to translate. A `{ text }` block with no `id` is keyed by a hash of its words, so its key changes when its words do. ```ts fragment const table = Object.fromEntries(translatableFields(game).map((field) => [field.key, field.text])) ``` ```ts shape import { translatableFields, type Game } from '@ifloom/engine' function translatableFields(game: Game): WordField[] ``` Uses: [`Game`](#game), [`WordField`](#wordfield). ## TriggerDef [#triggerdef] Type. Explained in [Triggers](https://ifloom.dev/docs/reference/triggers#triggerdef). A trigger the game declares in `triggers`, effects that run by themselves. They run the first time `when` holds after a command. Use one for a text that arrives the turn after a meeting, a notice when a debt comes due, or a scene that interrupts. ```ts shape import type { TriggerDef } from '@ifloom/engine' type TriggerDef = { id: string when: Condition effects: EffectRef[] once?: { per: 'game' | 'turn' } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The trigger's id, which `state.fired` records. | | `when` | [`Condition`](#condition) | | | The trigger's condition. The trigger fires the first time it holds after a command. | | `effects` | [`EffectRef[]`](#effectref) | | | The trigger's effects, which run when it fires. | | `once` | `{ per: 'game' \| 'turn' }` | yes | | The trigger's limit, once in the whole game (`{ per: 'game' }`) or at most once a turn (`{ per: 'turn' }`). `{ per: 'game' }` if left out. | ## Ui [#ui] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#ui). A `ui` field of ui hints, typed by the hints a UI package declared for that target. It also takes undeclared hints, which the engine carries all the same. ```ts shape import type { Ui } from '@ifloom/engine' type Ui = { [key: string]: unknown } ``` ## UiField [#uifield] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#uifield). A `ui` field in a game's content, with the thing it's written on and the place it is. ```ts shape import type { UiField } from '@ifloom/engine' type UiField = { on: UiTarget id?: string where: string ui: unknown } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `on` | [`UiTarget`](#uitarget) | | | The sort of thing the field is written on, such as a scene, a choice or a stat. | | `id` | `string` | yes | | The id of the thing the field is written on, where it has one. | | `where` | `string` | | | The place the field is, written as a `Problem`'s `where` is. | | `ui` | `unknown` | | | The field's hints, unchanged from content. | ## UiInContent [#uiincontent] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#uiincontent). The `ui` fields and lines of words `uiInContent` finds, in the order the content checker walks them. ```ts shape import type { UiInContent } from '@ifloom/engine' type UiInContent = { fields: UiField[] lines: TextLine[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `fields` | [`UiField[]`](#uifield) | | | The `ui` fields in the content. | | `lines` | [`TextLine[]`](#textline) | | | The lines of words that could hold a UI piece. | ## uiInContent [#uiincontent-1] Function. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#uiincontent-1). Returns the `UiInContent` of a game, every `ui` field and every line that could hold a UI piece. A UI package's checker reads it to check its own hints. The content checker's own walk finds them, in scenes, the blocks and decisions of their flows, choices, actions, stats, kinds, entities, the game's own and plugins' content, such as a location's room and body. ```ts shape import { uiInContent, type Game } from '@ifloom/engine' function uiInContent(game: Game): UiInContent ``` Uses: [`Game`](#game), [`UiInContent`](#uiincontent). ## UiTarget [#uitarget] Type. Explained in [Presentation hints](https://ifloom.dev/docs/reference/ui-hints#uitarget). The target a `ui` field is written on, which a UI package's checker reads. It's a scene or room scene (`scene`), a choice or action (`choice`), a block or section (`block`), a stat, a kind or entity (`entity`), or the game. ```ts shape import type { UiTarget } from '@ifloom/engine' type UiTarget = 'scene' | 'choice' | 'block' | 'stat' | 'entity' | 'game' ``` ## upgradePack [#upgradepack] Function. Explained in [Content and packs](https://ifloom.dev/docs/reference/content#upgradepack). Returns the pack upgraded to `SCHEMA` and to each plugin's content version. Returns a failed `Result` when the pack was written for a newer engine or plugin, or for a schema older than any step. Pass the game's plugins (`game.plugins`, or the base's), so each one's content is carried forward too. The engine's step from each schema runs after every plugin step keyed by that schema or below. Each plugin's later steps run after. A pack that records no version for a plugin is read as written for the plugin's current version. The result records every plugin's version in `plugins`, and a pack with nothing to upgrade comes back unchanged. `loadGame` passes `context` (see `PackContext`). ```ts shape import { upgradePack } from '@ifloom/engine' function upgradePack(pack: { schema: number; plugins?: Record }, plugins: readonly Plugin[], context?: PackContext): Result ``` Uses: [`Plugin`](https://ifloom.dev/docs/api/engine-plugin#plugin), [`PackContext`](https://ifloom.dev/docs/api/engine-plugin#packcontext), [`Result`](#result), [`Pack`](#pack). ## ValueRef [#valueref] Type. Explained in [Calls by name](https://ifloom.dev/docs/reference/custom#valueref). A reference to a value by full name, with the arguments it is asked with. It sets a stat's ceiling, an app's badge or an achievement's progress, as in `{ value: 'messages/unread', with: { channel: 'texts' } }`. ```ts shape import type { ValueRef } from '@ifloom/engine' type ValueRef = { value: string with?: PluginArgs } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `value` | `string` | | | The value's full name, a plugin's (`messages/unread`) or the game's (`game/…`). | | `with` | [`PluginArgs`](https://ifloom.dev/docs/api/engine-plugin#pluginargs) | yes | | The arguments the value is asked with. None if left out. | ## VariantMember [#variantmember] Type. Explained in [Prose and markup](https://ifloom.dev/docs/reference/prose#variantmember). A member of a variants list, a prose key or a prose key with a weight. A plain key has weight 1, so `{ prose: 'cafe.order/late', weight: 3 }` is drawn three times as often. ```ts shape import type { VariantMember } from '@ifloom/engine' type VariantMember = string | { prose: string; weight?: number } ``` ## VideoFlags [#videoflags] Type. Explained in [Media](https://ifloom.dev/docs/reference/media#videoflags). The flags a video's markup or `{ media }` block can set, each changing one default. ```ts shape import type { VideoFlags } from '@ifloom/engine' type VideoFlags = { controls?: boolean once?: boolean sound?: boolean poster?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `controls` | `boolean` | yes | | The controls flag, which shows the player's controls, so the video waits to be started instead of playing by itself. | | `once` | `boolean` | yes | | The once flag, which plays the video once instead of looping. | | `sound` | `boolean` | yes | | The sound flag, which plays the video with sound instead of muted. | | `poster` | `string` | yes | | The still shown before the video plays, as a path like any picture's. | ## VideoView [#videoview] Type. Explained in [Media](https://ifloom.dev/docs/reference/media#videoview). A video's playback settings as the player sees them, worked out from its `VideoFlags`. ```ts shape import type { VideoView } from '@ifloom/engine' type VideoView = { autoplay: boolean loop: boolean muted: boolean controls: boolean poster?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `autoplay` | `boolean` | | | The video's autoplay mark, which starts it as soon as it is shown. True unless it shows controls. | | `loop` | `boolean` | | | The video's loop mark, which plays it again when it ends. True unless its flags ask to play once. | | `muted` | `boolean` | | | The video's muted mark. True unless its flags ask for sound. | | `controls` | `boolean` | | | The video's controls mark, which shows the player's play, pause and volume controls. | | `poster` | `string` | yes | | The still shown before the video plays, through `artSrc`. | ## View [#view] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#view). One state as a UI renders it, returned by `view`. It holds the core's fields and each feature's. ```ts shape import type { View } from '@ifloom/engine' type View = { title: string when: string | null scene: { id: string | null; key: string; title: string; body: string; beats: SceneBeat[]; fresh: number; tags: string[]; speaker: SpeakerView | null; image: string | null; picture: PictureView | null; choices: RenderedChoice[]; ui?: Ui } actions: RenderedChoice[] plugins: ViewsIn entities: EntitiesView[] turn: number notices: NoticesView inputs: InputView[] settings: SettingView[] stats: StatView[] statsById: Record minigame: MinigameView | null timers: TimerView[] audio: AudioView panel: OpenPanel | null saving: SavingView rolls: Roll[] changes: ChangeView[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `title` | `string` | | | The game's title. | | `when` | `string \| null` | | | The time in the game in the plugins' words, such as "Day 3 · Wednesday morning", or null when no plugin gives one. | | `scene` | `{ id: string \| null; key: string; title: string; body: string; beats:` [`SceneBeat[]`](#scenebeat)`; fresh:…` | | | The open scene as the player sees it, or the room when none is open, or the minigame while one is played. | | `actions` | [`RenderedChoice[]`](#renderedchoice) | | | The actions on offer besides the scene's choices, ready to render. The `actions` providers' come first, such as wait, sleep and travel, then the game's own `actions`. | | `plugins` | [`ViewsIn`](#viewsin) | | | The plugins' views, by plugin id. Each plugin that declares its view in `ViewRegistry` has it typed. | | `entities` | [`EntitiesView[]`](#entitiesview) | | | Each listed kind with its listed, visible entities, in the order the kinds are declared. A kind whose `listed` is false is left out, and a listed kind with no entities shows empty. | | `turn` | `number` | | | The number of turns that have passed, 0 on the first. | | `notices` | [`NoticesView`](#noticesview) | | | The notices the player hasn't dismissed, with a count for each tag. | | `inputs` | [`InputView[]`](#inputview) | | | The inputs on offer now, in the order the game declares them, each with its value. | | `settings` | [`SettingView[]`](#settingview) | | | Every setting the game declares, in order, for a settings page. | | `stats` | [`StatView[]`](#statview) | | | The player's listed stats the player can see now, in the order the game declares them. | | `statsById` | `Record` | | | Every one of the player's stats, by id, listed and visible or not. | | `minigame` | [`MinigameView`](#minigameview) `\| null` | | | The minigame being played, or null. | | `timers` | [`TimerView[]`](#timerview) | | | The running timers, in the order they started. | | `audio` | [`AudioView`](#audioview) | | | The audio each channel should play and the sounds that are due. Empty when the game has no audio. | | `panel` | [`OpenPanel`](#openpanel) `\| null` | | | The panel open over the story. It's the one the `panel` effect opened, else the open scene's own, else null. | | `saving` | [`SavingView`](#savingview) | | | The player's leave to save now, with the reason when it's refused. | | `rolls` | [`Roll[]`](#roll) | | | The rolls the last command made, in order. Empty when it made none. | | `changes` | [`ChangeView[]`](#changeview) | | | The stats the last command moved that the player can see, the player's first, each with the words that say what moved. | ## view [#view-1] Function. Explained in [The view](https://ifloom.dev/docs/reference/view#view-1). Returns the `View` of a state, the value a UI renders. Without `options.profile`, no plugin's view reads the profile. The scene, its choices, the room's actions, the plugins' views and the audio come from `screen`, which renders the open scene once, and the rest comes from the state. `view` only formats, so each choice's effects and the pool picks stay on the screen. ```ts shape import { view, type Game } from '@ifloom/engine' function view(state: GameState, game: Game, options?: ViewOptions): View ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`ViewOptions`](#viewoptions), [`View`](#view). ## ViewOptions [#viewoptions] Type. Explained in [The view](https://ifloom.dev/docs/reference/view#viewoptions). Settings for `screen` and `view` besides the state. Without `profile`, no plugin's view reads the profile. ```ts shape import type { ViewOptions } from '@ifloom/engine' type ViewOptions = { profile?: Readonly> } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `profile` | `Readonly>` | yes | | The player's profile, by namespace. Each plugin's view reads its own namespace as `context.profile`, and the runner passes this. | ## ViewRegistry [#viewregistry] Type. Explained in [Declaring a plugin's calls](https://ifloom.dev/docs/reference/plugin-calls#conditionregistry-effectregistry-commandregistry-queryregistry-and-viewregistry). The registry of each plugin's view by plugin id (`shop: ShopView`), which types `view.plugins`. The game's own `rules.view` is under `game`. ```ts shape import type { ViewRegistry } from '@ifloom/engine' type ViewRegistry = { // … } ``` Plugins add fields of their own to it, which their pages list. ## ViewsIn [#viewsin] Type. Explained in [A plugin's view, scene and actions](https://ifloom.dev/docs/reference/plugin-views#viewsin). The plugins' views by plugin id, in `view.plugins`. Each plugin that declares its view in `ViewRegistry` is typed. ```ts shape import type { ViewsIn } from '@ifloom/engine' type ViewsIn = { [key: string]: unknown // … } ``` Plugins add fields of their own to it, which their pages list. ## weighted [#weighted] Function. Explained in [Randomness](https://ifloom.dev/docs/reference/random#weighted). Returns one entry of `items`, drawn from `parts` by each entry's weight. Returns undefined when no entry can be drawn. An entry of weight 3 comes up three times as often as one of weight 1. A weight left out counts as 1. An entry whose weight is 0 or less, or not a number, is never drawn. ```ts shape import { weighted } from '@ifloom/engine' function weighted(items: readonly T[], weightOf: (item: T) => number | undefined, ...parts: (string | number)[]): T | undefined ``` ## when [#when] Function. Explained in [Flowing scenes](https://ifloom.dev/docs/reference/flows#when). Returns a section of blocks shown only while `condition` holds. A section can hold any block a body can. ```ts shape import { when } from '@ifloom/engine' function when(condition: Condition, blocks: Block[], extras?: Omit): Block ``` Uses: [`Condition`](#condition), [`Block`](#block), [`BlockExtras`](#blockextras). ## whyNot [#whynot] Function. Explained in [Actions](https://ifloom.dev/docs/reference/actions#whynot). Returns the reason the player can't send this command now, or undefined when they can. The reducer refuses a command with this reason, and the view greys out its button with the same words. So a button and the rule behind it can't disagree, and every refusal is a sentence the player can read. The engine checks in the order the player would notice: the core's refusals such as a lock first, then the plugins' guards, then the command's own needs. ```ts shape import { whyNot, type Game } from '@ifloom/engine' function whyNot(state: GameState, game: Game, command: CommandRef): string | undefined ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`CommandRef`](#commandref). ## withTrait [#withtrait] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#withtrait). Returns every entity in the game that has a trait, as references. Declared ones not removed come first in content order, then those made in play with their kind's, their `like`'s or their own trait. ```ts shape import { withTrait, type Game } from '@ifloom/engine' function withTrait(state: GameState, game: Game, id: string): EntityRef[] ``` Uses: [`GameState`](#gamestate), [`Game`](#game), [`EntityRef`](#entityref). ## WordField [#wordfield] Type. Explained in [The words table](https://ifloom.dev/docs/reference/words#wordfield). A field of the game's content a player reads and a translation can reword, as `translatableFields` lists it. ```ts shape import type { WordField } from '@ifloom/engine' type WordField = { key: string text: string where: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `key` | `string` | | | The field's key in a pack's words table, such as `action.wait.label`. | | `text` | `string` | | | The field's words from content, tokens and markup included. | | `where` | `string` | | | The field's place as a problem names it, such as `scene cafe.counter` or `quests coffee`. | ## WordPart [#wordpart] Type. Explained in [The words table](https://ifloom.dev/docs/reference/words#wordpart). One field's part in a `WordShape`, telling how the walk reads that field. ```ts shape import type { WordPart } from '@ifloom/engine' type WordPart = true | 'blocks' | 'effects' | 'button' | WordShape | readonly [ WordPart ] ``` Uses: [`WordShape`](#wordshape). ## WordShape [#wordshape] Type. Explained in [The words table](https://ifloom.dev/docs/reference/words#wordshape). A map of the fields of an entry that hold words a translation can replace. A plugin's `defineData` declares one for each `data` list, and a trait's `words` declares one for its data. Each field of the shape is one of these: - `true`: a field of words, or a record of them (a stat's `{ one, other }`); - `'blocks'`: a list of blocks, as a scene's body; - `'effects'`: a list of effects, for the words of the notices they raise; - `'button'`: a button, as an action is: its label, labels, blocked reasons, `once` reason, `irreversible` warning and effects; - a shape, for an object's own fields; - a shape in a list, `[shape]`, for a list of entries; - `{ '*': shape }`, for a record of entries, each named by its key. ```ts shape import type { WordShape } from '@ifloom/engine' type WordShape = { [key: string]: WordPart } ``` ## writeEntity [#writeentity] Function. Explained in [Entities](https://ifloom.dev/docs/reference/entities#writeentity). Returns the state with one entity's record replaced. A record for an entity not yet there is added after the rest of its kind. ```ts shape import { writeEntity } from '@ifloom/engine' function writeEntity(state: GameState, ref: string, next: EntityState): GameState ``` Uses: [`GameState`](#gamestate), [`EntityState`](#entitystate). ## YOU [#you] Const. Explained in [Entities](https://ifloom.dev/docs/reference/entities#player-and-you). The id of whoever the player is playing now, the protagonist the `you` effect last chose or else the player. ```ts shape import { YOU } from '@ifloom/engine' const YOU: 'you' ``` # API (https://ifloom.dev/docs/api) These pages list every export of every entry point, with its signature and, for an object type, each field with its type, whether it's optional, its default and its TSDoc. They're generated from the source by `npm run api-docs`, so they can't drift from it. The [Reference](https://ifloom.dev/docs/reference), [React UI](https://ifloom.dev/docs/reference/react), [Browser](https://ifloom.dev/docs/reference/browser), [CLI](https://ifloom.dev/docs/reference/cli) and [Plugins](https://ifloom.dev/docs/reference/plugins) sections explain when and how to use each one, and each export here links to its explanation. | Page | Entries | Exports | |---|---|---| | [@ifloom/engine](https://ifloom.dev/docs/api/engine) | `@ifloom/engine` | 282 | | [@ifloom/engine/plugin](https://ifloom.dev/docs/api/engine-plugin) | `@ifloom/engine/plugin` | 82 | | [@ifloom/engine/testing](https://ifloom.dev/docs/api/engine-testing) | `@ifloom/engine/testing` | 8 | | [@ifloom/react](https://ifloom.dev/docs/api/react) | `@ifloom/react` | 144 | | [@ifloom/react/kit](https://ifloom.dev/docs/api/react-kit) | `@ifloom/react/kit` | 56 | | [@ifloom/browser](https://ifloom.dev/docs/api/browser) | `@ifloom/browser` | 16 | | [@ifloom/audio](https://ifloom.dev/docs/api/audio) | `@ifloom/audio` | 4 | | [@ifloom/cli](https://ifloom.dev/docs/api/cli) | `@ifloom/cli` | 28 | | [@ifloom/cli/game](https://ifloom.dev/docs/api/cli-game) | `@ifloom/cli/game` | 9 | | [@ifloom/cli/vite](https://ifloom.dev/docs/api/cli-vite) | `@ifloom/cli/vite` | 2 | | [@ifloom/plugin-achievements](https://ifloom.dev/docs/api/plugin-achievements) | `@ifloom/plugin-achievements`, `@ifloom/plugin-achievements/react` | 14 | | [@ifloom/plugin-calendar](https://ifloom.dev/docs/api/plugin-calendar) | `@ifloom/plugin-calendar`, `@ifloom/plugin-calendar/react` | 8 | | [@ifloom/plugin-cast](https://ifloom.dev/docs/api/plugin-cast) | `@ifloom/plugin-cast`, `@ifloom/plugin-cast/react` | 18 | | [@ifloom/plugin-debug](https://ifloom.dev/docs/api/plugin-debug) | `@ifloom/plugin-debug`, `@ifloom/plugin-debug/react` | 7 | | [@ifloom/plugin-devices](https://ifloom.dev/docs/api/plugin-devices) | `@ifloom/plugin-devices`, `@ifloom/plugin-devices/react` | 23 | | [@ifloom/plugin-feed](https://ifloom.dev/docs/api/plugin-feed) | `@ifloom/plugin-feed`, `@ifloom/plugin-feed/react` | 16 | | [@ifloom/plugin-generators](https://ifloom.dev/docs/api/plugin-generators) | `@ifloom/plugin-generators` | 10 | | [@ifloom/plugin-inventory](https://ifloom.dev/docs/api/plugin-inventory) | `@ifloom/plugin-inventory`, `@ifloom/plugin-inventory/react` | 23 | | [@ifloom/plugin-jobs](https://ifloom.dev/docs/api/plugin-jobs) | `@ifloom/plugin-jobs`, `@ifloom/plugin-jobs/react` | 17 | | [@ifloom/plugin-messages](https://ifloom.dev/docs/api/plugin-messages) | `@ifloom/plugin-messages`, `@ifloom/plugin-messages/react` | 17 | | [@ifloom/plugin-places](https://ifloom.dev/docs/api/plugin-places) | `@ifloom/plugin-places`, `@ifloom/plugin-places/react` | 20 | | [@ifloom/plugin-quests](https://ifloom.dev/docs/api/plugin-quests) | `@ifloom/plugin-quests`, `@ifloom/plugin-quests/react` | 15 | | [@ifloom/plugin-shop](https://ifloom.dev/docs/api/plugin-shop) | `@ifloom/plugin-shop`, `@ifloom/plugin-shop/react` | 25 | | [@ifloom/plugin-statuses](https://ifloom.dev/docs/api/plugin-statuses) | `@ifloom/plugin-statuses`, `@ifloom/plugin-statuses/react` | 14 | | [@ifloom/plugin-unlocks](https://ifloom.dev/docs/api/plugin-unlocks) | `@ifloom/plugin-unlocks`, `@ifloom/plugin-unlocks/react` | 38 | | [@ifloom/plugin-wardrobe](https://ifloom.dev/docs/api/plugin-wardrobe) | `@ifloom/plugin-wardrobe`, `@ifloom/plugin-wardrobe/react` | 18 | # @ifloom/plugin-achievements (https://ifloom.dev/docs/api/plugin-achievements) Generated from the source of `@ifloom/plugin-achievements` and `@ifloom/plugin-achievements/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-achievements [#ifloomplugin-achievements] - Functions: [`achievements`](#achievements), [`achievementsOf`](#achievementsof) - Types: [`AchievementDef`](#achievementdef), [`AchievementEntry`](#achievemententry), [`AchievementsProfile`](#achievementsprofile), [`AchievementsState`](#achievementsstate), [`AchievementsView`](#achievementsview), [`ProgressDef`](#progressdef) ### AchievementDef [#achievementdef] Type. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#achievementdef). An achievement the game declares in `data.achievements.achievements`. The player earns it once, by its condition, its progress or an effect. ```ts shape import type { AchievementDef } from '@ifloom/plugin-achievements' type AchievementDef = { id: string name: string description?: string image?: string secret?: boolean when?: Condition progress?: ProgressDef } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The achievement's id, unique among the game's achievements. | | `name` | `string` | | | The achievement's name, such as "First loaf". | | `description` | `string` | yes | | The achievement's line in the list of achievements. | | `image` | `string` | yes | | The achievement's picture, a path in the game's `art/` folder. | | `secret` | `boolean` | yes | | Hides the achievement until it's earned, when true. The view shows it as `???`, with no description, picture or progress. | | `when` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | yes | | The achievement's condition, checked after every command. The player earns it the first time the condition holds. Leave it out to earn the achievement when `progress` reaches its target, or only with the `achievements/grant` effect. | | `progress` | [`ProgressDef`](#progressdef) | yes | | The achievement's count to reach, such as 4 of 10. Without `when`, reaching the target earns it. | ### AchievementEntry [#achievemententry] Type. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#achievemententry). An achievement as the player sees it, in `view.plugins.achievements.achievements`. A secret one not yet earned shows no name, description, picture or progress. ```ts shape import type { AchievementEntry } from '@ifloom/plugin-achievements' type AchievementEntry = { id: string name: string description: string image: string | null secret: boolean earned: boolean earnedOn: number | null progress: { value: number; target: number } | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The achievement's id. | | `name` | `string` | | | The achievement's name, or the `achievements/secret` string (`???`) while it's secret and not earned. | | `description` | `string` | | | The achievement's description, or `''` when it has none or while it's secret and not earned. | | `image` | `string \| null` | | | The achievement's picture's path, through `artSrc`. It's null when there is none, or while it's secret and not earned. | | `secret` | `boolean` | | | The achievement's `secret` flag from content, true even after it's earned. | | `earned` | `boolean` | | | True when this save earned the achievement, or any save the profile remembers did. | | `earnedOn` | `number \| null` | | | The turn this save earned the achievement. It's null when this save hasn't, even if another save has. | | `progress` | `{ value: number; target: number } \| null` | | | The achievement's progress, clamped to between 0 and its target. Once earned, it reads as full. It's null when the achievement has no `progress`, or while it's secret and not earned. | ### achievements [#achievements] Function. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#achievements). Returns the achievements plugin, for the game's `plugins`. Its helpers write its calls, such as `achievements.earned('first-loaf')`. Content declares the achievements in `data.achievements.achievements`. ```ts shape import { achievements } from '@ifloom/plugin-achievements' function achievements(): DefinedPlugin ``` Uses: [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`AchievementsState`](#achievementsstate), [`AchievementsView`](#achievementsview). | Helper | Signature | Description | |---|---|---| | `achievements.earned` | `(id: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `achievements/earned` condition, which holds when this save has earned the achievement. | | `achievements.grant` | `(id: string):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `achievements/grant` effect, which earns the achievement now unless it's already earned. | ### achievementsOf [#achievementsof] Function. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#achievementsof). Returns the game's achievements, `data.achievements.achievements` from its content and packs, in declared order. ```ts shape import { achievementsOf } from '@ifloom/plugin-achievements' function achievementsOf(game: Game): AchievementDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`AchievementDef`](#achievementdef). ### AchievementsProfile [#achievementsprofile] Type. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#achievementsprofile). The achievements the player's profile keeps under the plugin's id. The profile outlives saves, so it lists achievements earned in any save. ```ts shape import type { AchievementsProfile } from '@ifloom/plugin-achievements' type AchievementsProfile = { earned: string[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `earned` | `string[]` | | | The ids of every achievement earned in any save, in the order they were first earned. | ### AchievementsState [#achievementsstate] Type. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#achievementsstate). The achievements a save keeps for the player. The plugin reads definitions from content, so the save keeps only the earned ones. ```ts shape import type { AchievementsState } from '@ifloom/plugin-achievements' type AchievementsState = { earned: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `earned` | `Record` | | | The save's earned achievements, each id mapped to the turn it was earned. | ### AchievementsView [#achievementsview] Type. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#achievementsview). The achievements as the player sees them, in `view.plugins.achievements`. Earned counts take in the profile when the runner has one. ```ts shape import type { AchievementsView } from '@ifloom/plugin-achievements' type AchievementsView = { achievements: AchievementEntry[] earned: number total: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `achievements` | [`AchievementEntry[]`](#achievemententry) | | | The game's achievements, in the order the game declares them. | | `earned` | `number` | | | The number of achievements earned, in this save or any save the profile remembers. | | `total` | `number` | | | The number of achievements the game declares, secret ones included. | ### ProgressDef [#progressdef] Type. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#progressdef). A count towards an achievement, an achievement's `progress`. The player's progress is `value` out of `target`. `value` is an `Amount`, such as a stat's id, a kv key (`{ kv: 'coffees' }`) or a value by name (`{ value: 'quests/updates' }`). ```ts shape import type { ProgressDef } from '@ifloom/plugin-achievements' type ProgressDef = { value: Amount target: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `value` | [`Amount`](https://ifloom.dev/docs/api/engine#amount) | | | The count so far, an `Amount` the plugin works out after each command. | | `target` | `number` | | | The count that completes the achievement. It must be more than 0. | ## @ifloom/plugin-achievements/react [#ifloomplugin-achievementsreact] - Functions: [`useAchievements`](#useachievements) - Constants: [`AchievementList`](#achievementlist), [`ACHIEVEMENTS_WORDS`](#achievements_words), [`AchievementsButton`](#achievementsbutton), [`AchievementsPage`](#achievementspage), [`achievementsUi`](#achievementsui) ### AchievementList [#achievementlist] Const. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#achievementlist). Renders the list of achievements from `view.plugins.achievements`, marking earned ones. A preset styles its `achievements`, `achievement`, `achievement-title`, `achievement-progress` and related parts. An achievement earned in any save the profile remembers counts as earned. A secret one not yet earned shows as `???`, and one with a count to reach shows a progress bar. `title` replaces the heading, and `false` leaves it out. It renders nothing in a game without the plugin. ```ts shape import { AchievementList } from '@ifloom/plugin-achievements/react' const AchievementList: ComponentType<{ className?: string; title?: string | false; }> ``` ### ACHIEVEMENTS_WORDS [#achievements_words] Const. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#achievements_words). The achievements plugin's words in English, keyed by name. A game rewords any of them with `ui.` in its strings. ```ts shape import { ACHIEVEMENTS_WORDS } from '@ifloom/plugin-achievements/react' const ACHIEVEMENTS_WORDS: { achievementEarned: 'Earned' achievementProgress: '{value} of {target}' achievements: 'Achievements' achievementsCount: '{earned} of {total}' noAchievements: 'No achievements yet.' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `achievementEarned` | `'Earned'` | | | The badge on an achievement the player has earned. | | `achievementProgress` | `'{value} of {target}'` | | | The line under an achievement's progress bar, with `{value}` and `{target}`. | | `achievements` | `'Achievements'` | | | The title of the achievement list, its page, its dialog and the button that opens them. | | `achievementsCount` | `'{earned} of {total}'` | | | The count of achievements earned, with `{earned}` and `{total}`. | | `noAchievements` | `'No achievements yet.'` | | | The line the list shows while the game has no achievements to show. | ### AchievementsButton [#achievementsbutton] Const. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#achievementsbutton). Renders the button that opens the achievements, with the number earned. A preset styles its `achievements-button` part. With pages on and the achievements page present, the button goes to that page. Otherwise it opens the list in a dialog. It renders nothing in a game without the plugin. ```ts shape import { AchievementsButton } from '@ifloom/plugin-achievements/react' const AchievementsButton: ComponentType<{ className?: string; }> ``` ### AchievementsPage [#achievementspage] Const. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#achievementspage). Renders the achievements page, one of the pages around the game, with an `AchievementList` and a back button. A preset styles its `achievements-page` part. ```ts shape import { AchievementsPage } from '@ifloom/plugin-achievements/react' const AchievementsPage: ComponentType<{ className?: string; }> ``` ### achievementsUi [#achievementsui] Const. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#achievementsui). The achievements plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It adds the `AchievementsButton` to the sidebar, the `achievements` page and panel, and the plugin's words. The page appears only when pages are on, with a button on the title screen. To keep the list in a dialog with pages on, leave the page out with `{ ...achievementsUi, pages: undefined }`. ```ts shape import { achievementsUi } from '@ifloom/plugin-achievements/react' const achievementsUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### useAchievements [#useachievements] Function. Explained in [Achievements](https://ifloom.dev/docs/reference/plugins/achievements#useachievements). Returns the achievements plugin's view from the running game, or null in a game without the plugin. It re-renders when the view changes. A secret achievement not yet earned comes named `???`, with no description. `AchievementList` renders from it. ```ts shape import { useAchievements } from '@ifloom/plugin-achievements/react' function useAchievements(): AchievementsView | null ``` Uses: [`AchievementsView`](#achievementsview). # @ifloom/plugin-calendar (https://ifloom.dev/docs/api/plugin-calendar) Generated from the source of `@ifloom/plugin-calendar` and `@ifloom/plugin-calendar/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-calendar [#ifloomplugin-calendar] - Functions: [`calendar`](#calendar) - Types: [`CalendarOptions`](#calendaroptions), [`CalendarState`](#calendarstate), [`CalendarView`](#calendarview), [`PeriodDef`](#perioddef) ### calendar [#calendar] Function. Explained in [Calendar](https://ifloom.dev/docs/reference/plugins/calendar#calendar). Returns the calendar plugin, for the game's `plugins`. List it before other plugins, so their hooks see the new day when a turn ends. Its helpers write its calls, such as `calendar.sleep()` and `calendar.day({ gte: 3 })`. ```ts shape import { calendar } from '@ifloom/plugin-calendar' function calendar(options?: CalendarOptions): DefinedPlugin ``` Uses: [`CalendarOptions`](#calendaroptions), [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`CalendarState`](#calendarstate), [`CalendarView`](#calendarview). | Helper | Signature | Description | |---|---|---| | `calendar.sleep` | `():` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `calendar/sleep` command, which passes time to the waking period of the next day. | | `calendar.pass` | `(n?: number):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `calendar/pass` effect, which moves the clock on `n` periods (1 if left out). | | `calendar.period` | `(...ids: string[]):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `calendar/period` condition, which holds in any of the periods named. | | `calendar.weekday` | `(...days: number[]):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `calendar/weekday` condition, which holds on any of the days of the week named, counting from 0. | | `calendar.weekend` | `():` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `calendar/weekend` condition, which holds on a day in `CalendarOptions.weekend`. | | `calendar.day` | `(range:` [`Range`](https://ifloom.dev/docs/api/engine#range)`):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `calendar/day` condition, which holds while the day, counting from 0, is in the range. | ### CalendarOptions [#calendaroptions] Type. Explained in [Calendar](https://ifloom.dev/docs/reference/plugins/calendar#calendaroptions). Settings for `calendar()`. Every field is optional and has the default its comment gives. ```ts shape import type { CalendarOptions } from '@ifloom/plugin-calendar' type CalendarOptions = { periods?: (string | PeriodDef)[] week?: number weekend?: number[] turn?: 'period' | 'day' | 'week' | false start?: { day?: number; period?: string } sleep?: { from?: string[]; wake?: string } | false curfew?: Condition | false } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `periods` | `(string \|` [`PeriodDef`](#perioddef)`)[]` | yes | | The periods of a day, in order. Morning, afternoon, evening, night and late if left out. | | `week` | `number` | yes | | The number of days in a week. 7 if left out. | | `weekend` | `number[]` | yes | | The days of the week that are the weekend, counting from 0. The last two days of the week if left out. | | `turn` | `'period' \| 'day' \| 'week' \| false` | yes | | The length of a turn, one `'period'`, one `'day'` or one `'week'`. `'day'` if left out. Passing time ends a turn at each boundary it crosses, and a turn ended any other way moves the clock to the start of the next. With `false`, the clock and the turn run independently. | | `start` | `{ day?: number; period?: string }` | yes | | The day and period a new game starts at. Day 0 and the first period if left out. | | `sleep` | `{ from?: string[]; wake?: string } \| false` | yes | | The settings of the `calendar/sleep` command. `false` leaves the command out. `from` lists the periods the player can sleep from, the last three if left out. `wake` is the period the player wakes in the next day, the first if left out. | | `curfew` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) `\| false` | yes | | The curfew's condition. While it holds, the calendar warns against passing time over the end of the day, and the engine refuses that command so the player goes to bed instead. The curfew always binds if left out, and never with `false`. | ### CalendarState [#calendarstate] Type. Explained in [Calendar](https://ifloom.dev/docs/reference/plugins/calendar#calendarstate). The clock a save keeps for the calendar. The plugin reads the periods and the week from its options, so the save keeps only the day and period. ```ts shape import type { CalendarState } from '@ifloom/plugin-calendar' type CalendarState = { day: number period: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `day` | `number` | | | The day, counting from 0. | | `period` | `string` | | | The id of the period the clock is in. | ### CalendarView [#calendarview] Type. Explained in [Calendar](https://ifloom.dev/docs/reference/plugins/calendar#calendarview). The calendar as the player sees it, in `view.plugins.calendar`. Its `label` is the line a UI's clock shows. ```ts shape import type { CalendarView } from '@ifloom/plugin-calendar' type CalendarView = { day: number weekday: string weekdayIndex: number period: string periodLabel: string label: string curfew: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `day` | `number` | | | The day, counting from 1 as the player does. | | `weekday` | `string` | | | The weekday's name, such as `'Wednesday'`. In a week of other than 7 days, it reads "Day 3 of the week". | | `weekdayIndex` | `number` | | | The weekday's position in the week, counting from 0. | | `period` | `string` | | | The period's id, such as `'morning'`. | | `periodLabel` | `string` | | | The period's name as the player reads it, such as `'Morning'`. | | `label` | `string` | | | The calendar's whole line, such as "Day 3 · Wednesday morning", from the `calendar/label` string. | | `curfew` | `boolean` | | | True in the day's last period, with no scene open, while the curfew binds. A UI can offer bed then. | ### PeriodDef [#perioddef] Type. Explained in [Calendar](https://ifloom.dev/docs/reference/plugins/calendar#perioddef). A period of the day, one entry of `CalendarOptions.periods`. A bare string in `periods` is a period with only an id. ```ts shape import type { PeriodDef } from '@ifloom/plugin-calendar' type PeriodDef = { id: string label?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The period's id, such as `'morning'`. | | `label` | `string` | yes | | The period's name as the player reads it. The id if left out. | ## @ifloom/plugin-calendar/react [#ifloomplugin-calendarreact] - Functions: [`useCalendar`](#usecalendar) - Constants: [`CalendarClock`](#calendarclock), [`calendarUi`](#calendarui) ### CalendarClock [#calendarclock] Const. Explained in [Calendar](https://ifloom.dev/docs/reference/plugins/calendar#calendarclock). Renders the game's time, such as "Day 3 · Wednesday morning", from `view.when`. A preset styles its `clock` part. It carries `data-day`, `data-weekday` and `data-period` attributes, and `data-curfew` while the curfew binds. `calendarUi` renders it in place of the core `Clock`. ```ts shape import { CalendarClock } from '@ifloom/plugin-calendar/react' const CalendarClock: ComponentType<{ className?: string; }> ``` ### calendarUi [#calendarui] Const. Explained in [Calendar](https://ifloom.dev/docs/reference/plugins/calendar#calendarui). The calendar plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It replaces the core `Clock` with `CalendarClock`, in the sidebar and in the top bar on a phone. ```ts shape import { calendarUi } from '@ifloom/plugin-calendar/react' const calendarUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### useCalendar [#usecalendar] Function. Explained in [Calendar](https://ifloom.dev/docs/reference/plugins/calendar#usecalendar). Returns the calendar plugin's view from the running game, or null in a game without the plugin. It re-renders when the view changes. The view has the day, the weekday, the period and the curfew. `CalendarClock` renders from it. ```ts shape import { useCalendar } from '@ifloom/plugin-calendar/react' function useCalendar(): CalendarView | null ``` Uses: [`CalendarView`](#calendarview). # @ifloom/plugin-cast (https://ifloom.dev/docs/api/plugin-cast) Generated from the source of `@ifloom/plugin-cast` and `@ifloom/plugin-cast/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-cast [#ifloomplugin-cast] - Functions: [`cast`](#cast), [`peopleOf`](#peopleof), [`personOf`](#personof) - Constants: [`AWAY`](#away) - Types: [`CastContact`](#castcontact), [`CastOptions`](#castoptions), [`CastView`](#castview), [`Person`](#person), [`PersonDef`](#persondef), [`PersonView`](#personview), [`SenderView`](#senderview), [`TalkOption`](#talkoption) ### AWAY [#away] Const. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#away). The location id a person is at when they are at no location, `'away'`. A person without `home` is here when no schedule entry holds. ```ts shape import { AWAY } from '@ifloom/plugin-cast' const AWAY: 'away' ``` ### cast [#cast] Function. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#cast). Returns the cast plugin, for the game's `plugins`. It cooperates with places, which says where the player is, and with the calendar, which a schedule can ask. Its helpers write people and calls, such as `cast.person({ ... })`, `cast.talk('ava')` and `cast.call('ava')`. ```ts shape import { cast } from '@ifloom/plugin-cast' function cast(options?: CastOptions): DefinedPlugin ``` Uses: [`CastOptions`](#castoptions), [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`CastView`](#castview). | Helper | Signature | Description | |---|---|---| | `cast.person` | `(def:` [`PersonDef`](#persondef)`):` [`EntityDef`](https://ifloom.dev/docs/api/engine#entitydef) | Returns an entity of the kind `character` (or `of`) carrying the `cast/person` trait, for content's `entities`. It takes a `PersonDef`, the entity's fields and the trait's side by side. | | `cast.character` | `(who: string, kind?: string):` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | Returns the entity reference of a person, such as `'character:ava'` for `cast.character('ava')`. Pass `kind` for a cast of another kind. | | `cast.talk` | `(who: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `cast/talk` command, which opens the person's talk scene while they are here. | | `cast.call` | `(who: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `cast/call` command, which opens the person's call scene from anywhere. | | `cast.here` | `(...who: string[]):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `cast/here` condition, which holds while any of the people named is at the player's location. | | `cast.at` | `(who: string, ...places: string[]):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `cast/at` condition, which holds while the person is at any of the locations named. | | `cast.met` | `(...who: string[]):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `cast/met` condition, which holds once the player has met any of the people named. | ### CastContact [#castcontact] Type. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#castcontact-and-senderview). A character the player can call, as the `cast/contacts` query answers. ```ts shape import type { CastContact } from '@ifloom/plugin-cast' type CastContact = { id: string name: string description: string | null image: string | null portrait: string | null command: CommandRef disabled: string | undefined } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The character's id, as the cast names them, such as `'ava'`. | | `name` | `string` | | | The character's name. | | `description` | `string \| null` | | | The character's description, a line about them, or null. | | `image` | `string \| null` | | | The character's picture, through `artSrc`, or null. | | `portrait` | `string \| null` | | | The character's face for a small avatar, or null. | | `command` | [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | | | The cast's `cast/call` command for the character, in the short form. | | `disabled` | `string \| undefined` | | | The reason the call can't go through now, or undefined when it can. | ### CastOptions [#castoptions] Type. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#castoptions). Settings for `cast()`. Every field is optional and has the default its comment gives. ```ts shape import type { CastOptions } from '@ifloom/plugin-cast' type CastOptions = { kind?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `kind` | `string` | yes | | The kind the plugin brings for its people, which a bare id names (`'ava'` is `'character:ava'`). `character` if left out. | ### CastView [#castview] Type. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#castview). The cast as the player sees it, in `view.plugins.cast`. ```ts shape import type { CastView } from '@ifloom/plugin-cast' type CastView = { present: PersonView[] people: PersonView[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `present` | [`PersonView[]`](#personview) | | | The people at the location the player is at. Empty while a scene is open or a lock that denies everything is on. | | `people` | [`PersonView[]`](#personview) | | | The people the player has met, in the order of `peopleOf`. | ### peopleOf [#peopleof] Function. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#peopleof). Returns the entity references of every person in the game now, the entities carrying the `cast/person` trait. Content's people come first in declared order, then those made in play. ```ts shape import { peopleOf } from '@ifloom/plugin-cast' function peopleOf(state: GameState, game: Game): EntityRef[] ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref). ### Person [#person] Type. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#person). The data the `cast/person` trait holds, which makes an entity a person the player can meet, find and talk to. `cast.person({ ... })` writes it beside the entity's own fields. ```ts shape import type { Person } from '@ifloom/plugin-cast' type Person = { fullName?: string pronouns?: Record home?: string schedule?: { location: string; when?: Condition }[] talk?: string | TalkOption[] call?: { scene?: string; when?: Condition; busy?: string } storyline?: string met?: Condition portrait?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `fullName` | `string` | yes | | The person's full name, with prose tokens filled in. The entity's name if left out. | | `pronouns` | `Record` | yes | | The person's pronouns for prose, such as `{ they: 'she', them: 'her' }`. The engine gives them no meaning. | | `home` | `string` | yes | | The id of the location the person is at when no schedule entry holds. `AWAY`, which is no location, if left out. | | `schedule` | `{ location: string; when?:` [`Condition`](https://ifloom.dev/docs/api/engine#condition) `}[]` | yes | | The person's schedule, each entry a location and its condition. The first entry whose `when` holds places them, with `'$'` as the person. | | `talk` | `string \|` [`TalkOption[]`](#talkoption) | yes | | The scene that talking to the person opens, or several options of which the first whose `when` holds opens. The person can't be talked to if left out. | | `call` | `{ scene?: string; when?:` [`Condition`](https://ifloom.dev/docs/api/engine#condition)`; busy?: string }` | yes | | The settings for calling the person from anywhere. The person can't be called if left out. `scene` is the scene a call opens, the talk scene if left out. `when` is the condition for picking up, and `busy` is the reason shown while it doesn't hold. | | `storyline` | `string` | yes | | The person's storyline. While it is closed, the person won't talk or pick up. | | `met` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | yes | | The condition for the player having met the person. Having seen one of their talk or call scenes if left out. | | `portrait` | `string` | yes | | The person's face for avatars, a path in the game's `art/` folder. The entity's `image` if left out. A UI shows it where it renders the person small, such as in a thread, a post or a contact. | ### PersonDef [#persondef] Type. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#persondef). A person the game declares in `entities` with `cast.person({ ... })`. It holds an entity's fields and the `cast/person` trait's side by side. The entity's `description` is the line under the person's name, such as "Runs the café", and its `image` is their picture. ```ts shape import type { PersonDef } from '@ifloom/plugin-cast' type PersonDef = { fullName?: string pronouns?: Record home?: string schedule?: { location: string; when?: Condition }[] talk?: string | TalkOption[] call?: { scene?: string; when?: Condition; busy?: string } storyline?: string met?: Condition portrait?: string of?: string // … } ``` Plugins add fields of their own to it, which their pages list. | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `fullName` | `string` | yes | | The person's full name, with prose tokens filled in. The entity's name if left out. | | `pronouns` | `Record` | yes | | The person's pronouns for prose, such as `{ they: 'she', them: 'her' }`. The engine gives them no meaning. | | `home` | `string` | yes | | The id of the location the person is at when no schedule entry holds. `AWAY`, which is no location, if left out. | | `schedule` | `{ location: string; when?:` [`Condition`](https://ifloom.dev/docs/api/engine#condition) `}[]` | yes | | The person's schedule, each entry a location and its condition. The first entry whose `when` holds places them, with `'$'` as the person. | | `talk` | `string \|` [`TalkOption[]`](#talkoption) | yes | | The scene that talking to the person opens, or several options of which the first whose `when` holds opens. The person can't be talked to if left out. | | `call` | `{ scene?: string; when?:` [`Condition`](https://ifloom.dev/docs/api/engine#condition)`; busy?: string }` | yes | | The settings for calling the person from anywhere. The person can't be called if left out. `scene` is the scene a call opens, the talk scene if left out. `when` is the condition for picking up, and `busy` is the reason shown while it doesn't hold. | | `storyline` | `string` | yes | | The person's storyline. While it is closed, the person won't talk or pick up. | | `met` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | yes | | The condition for the player having met the person. Having seen one of their talk or call scenes if left out. | | `portrait` | `string` | yes | | The person's face for avatars, a path in the game's `art/` folder. The entity's `image` if left out. A UI shows it where it renders the person small, such as in a thread, a post or a contact. | | `of` | `string` | yes | | The person's kind. The cast's own kind (`character`, or the `kind` option) if left out. | ### personOf [#personof] Function. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#personof). Returns the `cast/person` trait of the entity `ref`, or undefined when it isn't a person. It reads through an entity made in play `like` another. ```ts shape import { personOf } from '@ifloom/plugin-cast' function personOf(state: GameState, game: Game, ref: EntityRef): Person | undefined ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref), [`Person`](#person). ### PersonView [#personview] Type. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#personview). A person as the player sees them, in `view.plugins.cast`. Names and descriptions have their prose tokens filled in. ```ts shape import type { PersonView } from '@ifloom/plugin-cast' type PersonView = { id: string ref: EntityRef name: string fullName: string description: string | null ui?: Ui image: string | null portrait: string | null here: boolean closed: boolean met: boolean actions: RenderedChoice[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The person's id, as `cast.talk('ava')` names them. It's the whole reference for a person of a kind other than the cast's. | | `ref` | [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | | | The person's entity reference, such as `'character:ava'`. | | `name` | `string` | | | The person's name from their entity. | | `fullName` | `string` | | | The person's full name, or their name when they have none. | | `description` | `string \| null` | | | The person's entity `description`, such as "Runs the café", or null when there is none. | | `ui` | [`Ui`](https://ifloom.dev/docs/api/engine#ui)`<`[`EntityUi`](https://ifloom.dev/docs/api/engine#entityui)`>` | yes | | The person's entity presentation hints, such as the React UI's `hue`. Left out when there are none. | | `image` | `string \| null` | | | The person's picture's path, through `artSrc`. It's the entity's `image`, else `/`. The type allows null, as every plugin's picture does, though the cast always gives a path. | | `portrait` | `string \| null` | | | The person's face for avatars, through `artSrc`. It's the trait's `portrait`, else their `image`. | | `here` | `boolean` | | | True when the person's schedule puts them at the location the player is at (`places/here`). | | `closed` | `boolean` | | | True while the person's storyline is closed. | | `met` | `boolean` | | | True when the player has met the person, by their `met` condition, else by having seen one of their talk or call scenes. | | `actions` | [`RenderedChoice[]`](https://ifloom.dev/docs/api/engine#renderedchoice) | | | The person's talk action, refused with its reason when it can't run. Empty when the person has no `talk`. | ### SenderView [#senderview] Type. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#castcontact-and-senderview). The sender of a message or a post, as the `cast/sender` query answers. ```ts shape import type { SenderView } from '@ifloom/plugin-cast' type SenderView = { name: string image: string | null portrait: string | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | | | The sender's name. | | `image` | `string \| null` | | | The sender's picture, or null. | | `portrait` | `string \| null` | | | The sender's face for a small avatar, a person's `portrait`, or null. | ### TalkOption [#talkoption] Type. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#talkoption). A way a conversation with a person can open, one entry of a person's `talk`. The first entry whose `when` holds opens. ```ts shape import type { TalkOption } from '@ifloom/plugin-cast' type TalkOption = { scene: string when?: Condition label?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `scene` | `string` | | | The id of the scene the conversation opens. | | `when` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | yes | | The option's condition, with `'$'` as the person. The option always holds if left out. | | `label` | `string` | yes | | The talk button's label for this option. The `cast/talk` string ("Talk") if left out. | ## @ifloom/plugin-cast/react [#ifloomplugin-castreact] - Components: [`PeopleSection`](#peoplesection) - Functions: [`usePeople`](#usepeople) - Constants: [`CAST_WORDS`](#cast_words), [`castUi`](#castui), [`PeopleHere`](#peoplehere), [`Relationships`](#relationships) ### CAST_WORDS [#cast_words] Const. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#cast_words). The cast plugin's words in English, keyed by name. A game rewords any of them with `ui.` in its strings. ```ts shape import { CAST_WORDS } from '@ifloom/plugin-cast/react' const CAST_WORDS: { readonly people: 'People'; } ``` ### castUi [#castui] Const. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#castui). The cast plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It adds `PeopleSection` to the sidebar, `PeopleHere` to the story after the room's actions, the `people` panel and the plugin's words. ```ts shape import { castUi } from '@ifloom/plugin-cast/react' const castUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### PeopleHere [#peoplehere] Const. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#peoplehere). Renders the people at the player's location from `view.plugins.cast.present`, each with their actions. A preset styles its `people`, `person`, `person-portrait`, `person-name`, `person-desc` and `person-actions` parts. It renders nothing in a game without the plugin, or while nobody is here. ```ts shape import { PeopleHere } from '@ifloom/plugin-cast/react' const PeopleHere: ComponentType<{ className?: string; }> ``` ### PeopleSection [#peoplesection] Component. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#peoplesection). Renders the default layout's People section, a button that opens `Relationships` in a dialog. Its title is the `people` word. ```ts shape import { PeopleSection } from '@ifloom/plugin-cast/react' function PeopleSection(): JSX.Element ``` ### Relationships [#relationships] Const. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#relationships). Renders everyone the player has met from `view.plugins.cast.people`, each with the stats the view lists on their entity, such as friendship. A preset styles its `relationships`, `relationship`, `relationship-header` and `relationship-stats` parts. It renders nothing in a game without the plugin, or before the player has met anyone. ```ts shape import { Relationships } from '@ifloom/plugin-cast/react' const Relationships: ComponentType<{ className?: string; }> ``` ### usePeople [#usepeople] Function. Explained in [Cast](https://ifloom.dev/docs/reference/plugins/cast#usepeople). Returns the cast plugin's view from the running game, or null in a game without the plugin. It re-renders when the view changes. The view lists the people here in `present`, each with their actions, and everyone met in `people`. `PeopleHere` and `Relationships` render from it. ```ts shape import { usePeople } from '@ifloom/plugin-cast/react' function usePeople(): CastView | null ``` Uses: [`CastView`](#castview). # @ifloom/plugin-debug (https://ifloom.dev/docs/api/plugin-debug) Generated from the source of `@ifloom/plugin-debug` and `@ifloom/plugin-debug/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-debug [#ifloomplugin-debug] - Functions: [`debug`](#debug) - Types: [`DebugView`](#debugview) ### debug [#debug] Function. Explained in [Debug](https://ifloom.dev/docs/reference/plugins/debug#debug). Returns the debug plugin, for the game's `plugins` in development builds only. Its commands ignore locks, need no exit and pay no cost, and a release build leaves the plugin out. Its helpers write its commands, such as `debug.stat('coins', 10)`. It cooperates with the calendar and places, which `debug/time` and `debug/go` need. ```ts shape import { debug } from '@ifloom/plugin-debug' function debug(): DefinedPlugin ``` Uses: [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`DebugView`](#debugview). | Helper | Signature | Description | |---|---|---| | `debug.stat` | `(stat: string, to: number, of?: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `debug/stat` command, which sets the stat to `to`, clamped to its range. With `of`, it sets the entity's stat. | | `debug.kv` | `(key: string, to:` [`KvValue`](https://ifloom.dev/docs/api/engine#kvvalue)`):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `debug/kv` command, which sets the kv key to `to`. | | `debug.held` | `(entity: string, to: number, at?: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `debug/held` command, which sets how many of the thing someone (`at`) has, through the plugins that keep things. | | `debug.scene` | `(scene?: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `debug/scene` command, which opens the scene, or closes the open scene when none is named. | | `debug.time` | `(time: { day?: number; period?: string }):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `debug/time` command, which sets the calendar's day and period without ending a turn. It's refused without the calendar. | | `debug.turn` | `(turn: number):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `debug/turn` command, which sets the turn count without running any turn's rules. | | `debug.go` | `(location: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `debug/go` command, which moves the player to the location with no exit needed. It's refused without places. | ### DebugView [#debugview] Type. Explained in [Debug](https://ifloom.dev/docs/reference/plugins/debug#debugview). The debug readout as the developer sees it, in `view.plugins.debug`. It lists the locks that are on, the triggers that have fired and the seed. ```ts shape import type { DebugView } from '@ifloom/plugin-debug' type DebugView = { locks: { reason: string; deny: string[] }[] fired: Record seed: number receivers: string[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `locks` | `{ reason: string; deny: string[] }[]` | | | The game's locks whose `when` holds now, each with its reason and the commands it denies. | | `fired` | `Record` | | | The triggers that have fired, each id mapped to the turn it last fired on. | | `seed` | `number` | | | The save's seed, which every random draw is hashed from. | | `receivers` | `string[]` | | | The ids of the game's plugins that keep things, which `debug/held` sets counts through. Empty in a game that keeps none. | ## @ifloom/plugin-debug/react [#ifloomplugin-debugreact] - Functions: [`useDebug`](#usedebug) - Constants: [`DEBUG_WORDS`](#debug_words), [`DebugCard`](#debugcard), [`debugUi`](#debugui) - Types: [`DebugControls`](#debugcontrols) ### DEBUG_WORDS [#debug_words] Const. Explained in [Debug](https://ifloom.dev/docs/reference/plugins/debug#debug_words). The debug plugin's words in English, keyed by name. A game rewords any of them with `ui.` in its strings. ```ts shape import { DEBUG_WORDS } from '@ifloom/plugin-debug/react' const DEBUG_WORDS: { closeScene: 'Close the scene' debug: 'Debug' debugGo: 'Go' debugHeld: 'Held' debugKv: 'kv key' debugLog: 'Log' debugScene: 'Scene' debugSet: 'Set' debugStat: 'Stat' debugStatOf: 'Stat of' debugState: 'State' debugTime: 'Time' debugTurn: 'Turn' debugWhy: 'Why not' greyedOut: 'Greyed out' locksOn: 'Locks on' noneOn: 'None.' nothingGreyed: 'Nothing.' seed: 'seed {seed}' set: 'Set' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `closeScene` | `'Close the scene'` | | | The label of the button that closes the open scene. | | `debug` | `'Debug'` | | | The title of the debug card. | | `debugGo` | `'Go'` | | | The label of the form that moves the player to a location, shown only with the places plugin. | | `debugHeld` | `'Held'` | | | The label of the form that sets how many of an entity the player holds. | | `debugKv` | `'kv key'` | | | The label of the form that sets a kv key. | | `debugLog` | `'Log'` | | | The label of the tab with the command log. | | `debugScene` | `'Scene'` | | | The label of the form that opens a scene. | | `debugSet` | `'Set'` | | | The label of the tab with the forms that set the state. | | `debugStat` | `'Stat'` | | | The label of the form that sets a stat. | | `debugStatOf` | `'Stat of'` | | | The label of the form that sets an entity's stat. | | `debugState` | `'State'` | | | The label of the tab that shows the state. | | `debugTime` | `'Time'` | | | The label of the form that sets the time. | | `debugTurn` | `'Turn'` | | | The label of the form that sets the turn. | | `debugWhy` | `'Why not'` | | | The label of the tab that lists the locks and each disabled button's reason. | | `greyedOut` | `'Greyed out'` | | | The heading over the list of disabled buttons and their reasons. | | `locksOn` | `'Locks on'` | | | The heading over the list of locks that are on. | | `noneOn` | `'None.'` | | | The line the locks list shows while no lock is on. | | `nothingGreyed` | `'Nothing.'` | | | The line the disabled list shows while every button can be used. | | `seed` | `'seed {seed}'` | | | The note that shows the save's seed, with `{seed}`. | | `set` | `'Set'` | | | The label of each form's submit button. | ### DebugCard [#debugcard] Const. Explained in [Debug](https://ifloom.dev/docs/reference/plugins/debug#debugcard). Renders the debug card from `view.plugins.debug`, with forms for the debug commands, the locks, the disabled buttons' reasons, the state, the log and undo and redo. A preset styles its `debug` and `debug-*` parts. It renders nothing in a game built without the plugin. ```ts shape import { DebugCard } from '@ifloom/plugin-debug/react' const DebugCard: ComponentType<{ className?: string; }> ``` ### DebugControls [#debugcontrols] Type. Explained in [Debug](https://ifloom.dev/docs/reference/plugins/debug#debugcontrols). The debug plugin's view with the refused buttons, the state, the command log and undo and redo, as `useDebug` returns it. Send the plugin's helpers with `useGame().send`, such as `send(debug.stat('coins', 50))`. ```ts shape import type { DebugControls } from '@ifloom/plugin-debug/react' type DebugControls = { locks: { reason: string; deny: string[] }[] fired: Record seed: number receivers: string[] greyed: RenderedChoice[] state: GameState log: Command[] canUndo: boolean canRedo: boolean undo: () => void redo: () => void } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `locks` | `{ reason: string; deny: string[] }[]` | | | The game's locks whose `when` holds now, each with its reason and the commands it denies. | | `fired` | `Record` | | | The triggers that have fired, each id mapped to the turn it last fired on. | | `seed` | `number` | | | The save's seed, which every random draw is hashed from. | | `receivers` | `string[]` | | | The ids of the game's plugins that keep things, which `debug/held` sets counts through. Empty in a game that keeps none. | | `greyed` | [`RenderedChoice[]`](https://ifloom.dev/docs/api/engine#renderedchoice) | | | The disabled buttons on screen, from the actions, the scene's choices and the cast's people here. | | `state` | [`GameState`](https://ifloom.dev/docs/api/engine#gamestate) | | | The runner's whole game state. | | `log` | [`Command[]`](https://ifloom.dev/docs/api/engine#command) | | | The commands the runner has run since the start, in order. | | `canUndo` | `boolean` | | | True when the runner has a state to go back to. | | `canRedo` | `boolean` | | | True when the runner has an undone state to go forward to. | | `undo` | `() => void` | | | Goes back a state, as `runner.undo()` does. | | `redo` | `() => void` | | | Goes forward a state, as `runner.redo()` does. | ### debugUi [#debugui] Const. Explained in [Debug](https://ifloom.dev/docs/reference/plugins/debug#debugui). The debug plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It adds the `DebugCard` to the end of the story, and the plugin's words. It renders nothing in a build without the plugin, so a game can list it in every build. ```ts shape import { debugUi } from '@ifloom/plugin-debug/react' const debugUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### useDebug [#usedebug] Function. Explained in [Debug](https://ifloom.dev/docs/reference/plugins/debug#usedebug). Returns the debug plugin's view with the runner's state, log and undo controls from the running game, or null in a game without the plugin. It re-renders when the snapshot changes. `DebugCard` renders from it. ```ts shape import { useDebug } from '@ifloom/plugin-debug/react' function useDebug(): DebugControls | null ``` Uses: [`DebugControls`](#debugcontrols). # @ifloom/plugin-devices (https://ifloom.dev/docs/api/plugin-devices) Generated from the source of `@ifloom/plugin-devices` and `@ifloom/plugin-devices/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-devices [#ifloomplugin-devices] - Functions: [`appsOf`](#appsof), [`devices`](#devices), [`devicesOf`](#devicesof) - Types: [`AppDef`](#appdef), [`AppView`](#appview), [`DeviceDef`](#devicedef), [`DevicesState`](#devicesstate), [`DevicesView`](#devicesview), [`DeviceView`](#deviceview), [`Section`](#section), [`SectionView`](#sectionview) ### AppDef [#appdef] Type. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#appdef). An app the game declares in `data.devices.apps`. Opening it changes no location and passes no time. ```ts shape import type { AppDef, Section } from '@ifloom/plugin-devices' type AppDef = { id: string name: string icon: string on: string when?: Condition blocked?: Blocked[] badge?: Amount | { when: Condition } sections: Section[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The app's id, unique among the game's apps. | | `name` | `string` | | | The app's name. | | `icon` | `string` | | | The app's icon, a name a UI maps to a picture. | | `on` | `string` | | | The id of the device the app is on. | | `when` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | yes | | The app's install condition. The app stays off the home screen until it holds. | | `blocked` | [`Blocked[]`](https://ifloom.dev/docs/api/engine#blocked) | yes | | The app's refusals. The first entry whose `when` holds disables the app with its reason, or leaves it off the home screen with `hide`. | | `badge` | [`Amount`](https://ifloom.dev/docs/api/engine#amount) `\| { when:` [`Condition`](https://ifloom.dev/docs/api/engine#condition) `}` | yes | | The app's badge, a count or a dot. A count is an `Amount`, such as a value asked with its arguments (`{ value: 'messages/unread', with: { channel: 'texts' } }`), a stat or a kv key's number. `{ when }` shows a dot while the condition holds. | | `sections` | [`Section[]`](#section) | | | The app's sections, top to bottom. Each is a `Section`. | ### appsOf [#appsof] Function. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#appsof). Returns the game's apps on every device, `data.devices.apps` from its content and packs, in declared order. ```ts shape import { appsOf } from '@ifloom/plugin-devices' function appsOf(game: Game): AppDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`AppDef`](#appdef). ### AppView [#appview] Type. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#appview). An app as the player sees it, in a `DeviceView`'s `apps` and `open`. ```ts shape import type { AppView } from '@ifloom/plugin-devices' type AppView = { id: string name: string icon: string badge: number | boolean disabled?: string command: Command sections: SectionView[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The app's id. | | `name` | `string` | | | The app's name. | | `icon` | `string` | | | The app's icon, a name a UI maps to a picture. | | `badge` | `number \| boolean` | | | The app's badge, a count, a dot (`true`), or nothing (`0` or `false`). | | `disabled` | `string` | yes | | The reason the app can't open now, from its `blocked` or a lock on `devices/open`. Left out when it can open. | | `command` | [`Command`](https://ifloom.dev/docs/api/engine#command) | | | The `devices/open` command that opens the app. | | `sections` | [`SectionView[]`](#sectionview) | | | The app's sections. They're filled in only for the open app, and empty otherwise. | ### DeviceDef [#devicedef] Type. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#devicedef). A device the game declares in `data.devices.devices`, such as a phone or a laptop. Its apps name it in their `on`. ```ts shape import type { DeviceDef } from '@ifloom/plugin-devices' type DeviceDef = { id: string name: string frame?: string sidebar?: boolean wallpaper?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The device's id, unique among the game's devices. | | `name` | `string` | | | The device's name. | | `frame` | `string` | yes | | The device's frame, a name such as `'phone'` or `'laptop'` that a UI renders it in. The device's id if left out. | | `sidebar` | `boolean` | yes | | Offers the device from the sidebar, when true. | | `wallpaper` | `string` | yes | | The picture behind the device's home screen. | ### devices [#devices] Function. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#devices). Returns the devices plugin, for the game's `plugins`. It cooperates with the cast, whose people a `contacts` section lists. Content declares devices and apps in `data.devices.devices` and `data.devices.apps`, and the helpers write its calls, such as `devices.open('camera')`. ```ts shape import { devices, type DevicesState } from '@ifloom/plugin-devices' function devices(): DefinedPlugin ``` Uses: [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`DevicesView`](#devicesview). | Helper | Signature | Description | |---|---|---| | `devices.open` | `(app: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `devices/open` command, which opens the app and shows its device. It passes no time. | | `devices.home` | `(device: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `devices/home` command, which shows the device on its home screen, from put away or from an app. | | `devices.close` | `(device: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `devices/close` command, which puts the device away. | | `devices.appOpen` | `(app: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `devices/open` condition, which holds while the app is open on a device that's shown. | ### devicesOf [#devicesof] Function. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#devicesof). Returns the game's devices, `data.devices.devices` from its content and packs, in declared order. ```ts shape import { devicesOf } from '@ifloom/plugin-devices' function devicesOf(game: Game): DeviceDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`DeviceDef`](#devicedef). ### DevicesState [#devicesstate] Type. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#devicesstate). The devices a save keeps out, each mapped to its open app, or null on its home screen. A device left out of `shown` is put away. The plugin reads definitions from content. ```ts shape import type { DevicesState } from '@ifloom/plugin-devices' type DevicesState = { shown: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `shown` | `Record` | | | The devices out, each id mapped to the open app's id, or null on the home screen. | ### DevicesView [#devicesview] Type. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#devicesview). The devices as the player sees them, in `view.plugins.devices`. ```ts shape import type { DevicesView } from '@ifloom/plugin-devices' type DevicesView = { devices: DeviceView[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `devices` | [`DeviceView[]`](#deviceview) | | | The game's devices, in declared order, whether shown or not. | ### DeviceView [#deviceview] Type. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#deviceview). A device as the player sees it, in `view.plugins.devices.devices`. ```ts shape import type { DeviceView } from '@ifloom/plugin-devices' type DeviceView = { id: string name: string frame: string sidebar: boolean wallpaper: string | null badge: number apps: AppView[] shown: boolean open: AppView | null home: RenderedChoice close: RenderedChoice | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The device's id. | | `name` | `string` | | | The device's name. | | `frame` | `string` | | | The device's frame, such as `'phone'` or `'laptop'`. The device's id when it gives none. | | `sidebar` | `boolean` | | | True when the sidebar offers the device. | | `wallpaper` | `string \| null` | | | The device's `wallpaper` as written, or null when it has none. | | `badge` | `number` | | | The device's badge, the sum of its apps' counts plus one for each dot. The sidebar button shows it. | | `apps` | [`AppView[]`](#appview) | | | The device's installed apps, in declared order. A `hide` entry that holds leaves an app out. | | `shown` | `boolean` | | | True while the device is out, on its home screen or an app. A UI renders a device only while it's shown. | | `open` | [`AppView`](#appview) `\| null` | | | The app open on the device while it's shown, or null on its home screen or while put away. | | `home` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) | | | The button that shows the device's home screen, from put away or from an app. Its label is the `devices/home` string, "Home". | | `close` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that puts the device away, labelled with the `devices/close` string, "Close". Null while the device isn't shown. | ### Section [#section] Type. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#section). A section of an app, one entry of an app's `sections`. Each form is told apart by its key. ```ts shape import type { Section } from '@ifloom/plugin-devices' type Section = { blocks: Block[] } | { actions: ActionDef[] } | { things: { of: string; where?: Condition } } | { contacts: true } | { plugin: string; with?: Record } | { panel: string; with?: Record } ``` Uses: [`Block`](https://ifloom.dev/docs/api/engine#block), [`ActionDef`](https://ifloom.dev/docs/api/engine#actiondef), [`Condition`](https://ifloom.dev/docs/api/engine#condition). ### SectionView [#sectionview] Type. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#sectionview). An app's section as the player sees it, in an `AppView`'s `sections`. Each form is told apart by its `type`. ```ts shape import type { SectionView } from '@ifloom/plugin-devices' type SectionView = { type: 'prose'; text: string; beats: SceneBeat[] } | { type: 'actions'; actions: RenderedChoice[] } | { type: 'list'; entries: { id: string; title: string; text: string; image: string | null; actions: RenderedChoice[] }[] } | { type: 'plugin'; plugin: string; with: Record } | { type: 'panel'; panel: string; with: Record } ``` Uses: [`SceneBeat`](https://ifloom.dev/docs/api/engine#scenebeat), [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice). ## @ifloom/plugin-devices/react [#ifloomplugin-devicesreact] - Functions: [`useDevice`](#usedevice), [`useDevices`](#usedevices), [`useOpenApp`](#useopenapp) - Constants: [`AppSection`](#appsection), [`DeviceButtons`](#devicebuttons), [`DeviceDialog`](#devicedialog), [`DeviceScreen`](#devicescreen), [`DeviceStrip`](#devicestrip), [`devicesUi`](#devicesui) - Types: [`DevicesState`](#devicesstate-1), [`DeviceState`](#devicestate), [`OpenAppState`](#openappstate) ### AppSection [#appsection] Const. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#appsection). Renders one section of an open app by its `type`. A preset styles its `app-prose`, `app-entries`, `app-entry` and related parts. A `plugin` section renders with the section component that plugin's UI registers, and a `panel` section with the game's panel of that name. Either renders nothing when no UI supplies one. ```ts shape import { AppSection } from '@ifloom/plugin-devices/react' const AppSection: ComponentType<{ section: SectionView; }> ``` Uses: [`SectionView`](#sectionview). ### DeviceButtons [#devicebuttons] Const. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#devicebuttons). Renders a button for each device with `sidebar` set, from `view.plugins.devices`, each with its badge. A preset styles its `devices`, `device-button` and `device-badge` parts. A button brings its device out on its home screen, and the `DeviceDialog` shows it. ```ts shape import { DeviceButtons } from '@ifloom/plugin-devices/react' const DeviceButtons: ComponentType ``` ### DeviceDialog [#devicedialog] Const. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#devicedialog). Renders the device that's out in a dialog, with its frame in `data-frame` for a preset to style a phone or a laptop. With `deviceId`, it renders only that device. Closing the dialog puts the device away and calls `onClose`. `devicesUi` renders one for the whole game. ```ts shape import { DeviceDialog } from '@ifloom/plugin-devices/react' const DeviceDialog: ComponentType<{ deviceId?: string | null; onClose?: (() => void); }> ``` ### DeviceScreen [#devicescreen] Const. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#devicescreen). Renders a device's screen, its home screen of apps or the open app with a back button. A preset styles its `device-screen`, `app-launcher`, `app-button`, `app-icon`, `app-badge`, `app` and `app-header` parts. ```ts shape import { DeviceScreen } from '@ifloom/plugin-devices/react' const DeviceScreen: ComponentType<{ device: DeviceView; }> ``` Uses: [`DeviceView`](#deviceview). ### DevicesState [#devicesstate-1] Type. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#devicesstate). The devices in `view.plugins.devices.devices`, as `useDevices` returns them. The list is empty in a game without the plugin. ```ts shape import type { DevicesState } from '@ifloom/plugin-devices/react' type DevicesState = DeviceView[] ``` Uses: [`DeviceView`](#deviceview). ### DeviceState [#devicestate] Type. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#devicestate). The device that's out and the controls to bring a device out or put it away, as `useDevice` returns them. The state comes from the save, so every UI agrees. ```ts shape import type { DeviceState } from '@ifloom/plugin-devices/react' type DeviceState = { openId: string | null device: DeviceView | null open: (id: string) => void close: () => void } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `openId` | `string \| null` | | | The id of the device that's out, the first if more than one is, or null when none is. | | `device` | [`DeviceView`](#deviceview) `\| null` | | | The device that's out, or null when none is. | | `open` | `(id: string) => void` | | | Brings the device out on its home screen by sending its `home` button's command. | | `close` | `() => void` | | | Puts the device that's out away by sending its `close` button's command. | ### DeviceStrip [#devicestrip] Const. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#devicestrip). Renders a button in the `NoticeStrip` for each app with a badge that can open, with its count or a dot. A preset styles its `notice-strip-item` and `badge` parts. A button opens its app, which brings the device out. `devicesUi` places it in the layout's `strip`. ```ts shape import { DeviceStrip } from '@ifloom/plugin-devices/react' const DeviceStrip: ComponentType ``` ### devicesUi [#devicesui] Const. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#devicesui). The devices plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It adds the `DeviceButtons` to the sidebar, the `DeviceStrip` to the notice strip and one `DeviceDialog` for the device that's out. The UI of the plugin an app's `plugin` section names renders that section, so list `messagesUi` and `feedUi` too. ```ts shape import { devicesUi } from '@ifloom/plugin-devices/react' const devicesUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### OpenAppState [#openappstate] Type. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#openappstate). The app being rendered and its device, as `useOpenApp` returns them. ```ts shape import type { OpenAppState } from '@ifloom/plugin-devices/react' type OpenAppState = { device: DeviceView app: AppView } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `device` | [`DeviceView`](#deviceview) | | | The device the app is open on. | | `app` | [`AppView`](#appview) | | | The open app, with all its sections. | ### useDevice [#usedevice] Function. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#usedevice). Returns the device that's out and the controls to open and close devices, from the running game. It re-renders when the view changes. ```ts shape import { useDevice } from '@ifloom/plugin-devices/react' function useDevice(): DeviceState ``` Uses: [`DeviceState`](#devicestate). ### useDevices [#usedevices] Function. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#usedevices). Returns the devices from the running game, or an empty list in a game without the plugin. It re-renders when the view changes. ```ts shape import { useDevices, type DevicesState } from '@ifloom/plugin-devices/react' function useDevices(): DevicesState ``` ### useOpenApp [#useopenapp] Function. Explained in [Devices](https://ifloom.dev/docs/reference/plugins/devices#useopenapp). Returns the open app a section renders in, with its device, or null outside an open app. It re-renders when the open app changes. A `{ panel }` section's component gets only its `with` as `data`, so it reads the app's other sections here, such as an `actions` section's buttons to render on a card of its own. ```ts shape import { useOpenApp } from '@ifloom/plugin-devices/react' function useOpenApp(): OpenAppState | null ``` Uses: [`OpenAppState`](#openappstate). # @ifloom/plugin-feed (https://ifloom.dev/docs/api/plugin-feed) Generated from the source of `@ifloom/plugin-feed` and `@ifloom/plugin-feed/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-feed [#ifloomplugin-feed] - Functions: [`feed`](#feed), [`feedsOf`](#feedsof), [`postsOf`](#postsof) - Types: [`Comment`](#comment), [`FeedDef`](#feeddef), [`FeedState`](#feedstate), [`FeedsView`](#feedsview), [`FeedView`](#feedview), [`OwnPost`](#ownpost), [`PostDef`](#postdef), [`PostView`](#postview) ### Comment [#comment] Type. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#comment). A comment on a post, one entry of a post's comments in `FeedState`. ```ts shape import type { Comment } from '@ifloom/plugin-feed' type Comment = { from: string text: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `from` | `string` | | | The commenter, a character's id or a name. | | `text` | `string` | | | The comment's words, as written. The view fills in their prose tokens. | ### feed [#feed] Function. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#feed). Returns the feed plugin, for the game's `plugins`. It cooperates with the cast, which gives posters their names and faces. Content declares feeds and posts in `data.feed.feeds` and `data.feed.posts`, and the helpers write its calls, such as `feed.react('post-1', { likes: 2 })`. ```ts shape import { feed } from '@ifloom/plugin-feed' function feed(): DefinedPlugin ``` Uses: [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`FeedState`](#feedstate), [`FeedsView`](#feedsview). | Helper | Signature | Description | |---|---|---| | `feed.post` | `(feedId: string, id: string, post?: { text?: string; image?: string; video?: string; likes?: number }):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `feed/post` effect, which posts the player's post `id` to the feed, with its words in place, picture, video and likes. A post id already used is left as it is. | | `feed.react` | `(post: string, reaction: { likes?: number; from?: string; text?: string }):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `feed/react` effect, which adds likes, a comment from `from`, or both, to a post that has appeared. | | `feed.seen` | `(feedId?: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `feed/seen` command, which marks the feed seen, or every feed when none is named. | | `feed.posted` | `(gte?: number, feedId?: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `feed/posted` condition, which holds once the player has made at least `gte` posts, to the feed or to any. | ### FeedDef [#feeddef] Type. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#feeddef). A feed the game declares in `data.feed.feeds`, such as a social app, a notice board or a paper. Posts name it in their `feed`. ```ts shape import type { FeedDef } from '@ifloom/plugin-feed' type FeedDef = { id: string name: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The feed's id, unique among the game's feeds. | | `name` | `string` | | | The feed's name. | ### feedsOf [#feedsof] Function. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#feedsof). Returns the game's feeds, `data.feed.feeds` from its content and packs, in declared order. ```ts shape import { feedsOf } from '@ifloom/plugin-feed' function feedsOf(game: Game): FeedDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`FeedDef`](#feeddef). ### FeedState [#feedstate] Type. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#feedstate). The feeds a save keeps for the player. The plugin reads feeds and other people's posts from content, so the save keeps only what play changed. ```ts shape import type { FeedState } from '@ifloom/plugin-feed' type FeedState = { appeared: Record own: OwnPost[] reactions: Record seen: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `appeared` | `Record` | | | The posts that have appeared, each id mapped to the turn it appeared on. | | `own` | [`OwnPost[]`](#ownpost) | | | The player's own posts, oldest first. | | `reactions` | `Record` | | | The likes and comments added to other people's posts since they appeared, by post id. | | `seen` | `Record` | | | The number of other people's posts each feed had when the player last looked, by feed id. | ### FeedsView [#feedsview] Type. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#feedsview). The feeds as the player sees them, in `view.plugins.feed`. ```ts shape import type { FeedsView } from '@ifloom/plugin-feed' type FeedsView = { feeds: FeedView[] unread: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `feeds` | [`FeedView[]`](#feedview) | | | The game's feeds, in declared order. | | `unread` | `number` | | | The number of unseen posts across every feed. | ### FeedView [#feedview] Type. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#feedview). A feed as the player sees it, in `view.plugins.feed.feeds`. Its `unread` counts other people's posts the player hasn't seen. ```ts shape import type { FeedView } from '@ifloom/plugin-feed' type FeedView = { id: string name: string posts: PostView[] unread: number seen: RenderedChoice | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The feed's id. | | `name` | `string` | | | The feed's name. | | `posts` | [`PostView[]`](#postview) | | | The feed's posts, newest first, the player's own among them. | | `unread` | `number` | | | The number of other people's posts in the feed the player hasn't seen. The player's own posts never count. | | `seen` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that marks the feed seen, labelled with the `feed/allSeen` string. Null while nothing in it is new. | ### OwnPost [#ownpost] Type. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#ownpost). A post the player made with the `feed/post` effect, as `FeedState` keeps it. ```ts shape import type { OwnPost } from '@ifloom/plugin-feed' type OwnPost = { id: string feed: string turn: number text?: string image?: string video?: string likes: number comments: Comment[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The post's id, which `feed/react` and `feed/likes` name. | | `feed` | `string` | | | The id of the feed the post went to. | | `turn` | `number` | | | The turn the post was made on. | | `text` | `string` | yes | | The post's words, as written. The view fills in their prose tokens. | | `image` | `string` | yes | | The post's picture, as written. | | `video` | `string` | yes | | The post's video clip, as written. | | `likes` | `number` | | | The number of likes the post has. | | `comments` | [`Comment[]`](#comment) | | | The comments on the post, oldest first. | ### PostDef [#postdef] Type. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#postdef). Someone else's post, which the game declares in `data.feed.posts`. It appears the first time its `when` holds after a command. ```ts shape import type { PostDef } from '@ifloom/plugin-feed' type PostDef = { id: string feed: string from: string when: Condition body: Block[] image?: string video?: string likes?: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The post's id, unique among the game's posts. | | `feed` | `string` | | | The id of the feed the post appears in. | | `from` | `string` | | | The poster, a character's id or any name the game's prose uses. | | `when` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | | | The post's condition. The post appears the first time it holds after a command, and stays. | | `body` | [`Block[]`](https://ifloom.dev/docs/api/engine#block) | | | The post's words, as blocks. | | `image` | `string` | yes | | The post's picture, a path in the game's `art/` folder (`'photo/park.jpg'`) or a URL. | | `video` | `string` | yes | | The post's video clip, a path like `image`'s, where a bare name is an `.mp4`. The React UI plays it like a GIF, looping and muted. | | `likes` | `number` | yes | | The number of likes the post has when it appears. 0 if left out. | ### postsOf [#postsof] Function. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#postsof). Returns the game's posts, `data.feed.posts` from its content and packs, in declared order. ```ts shape import { postsOf } from '@ifloom/plugin-feed' function postsOf(game: Game): PostDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`PostDef`](#postdef). ### PostView [#postview] Type. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#postview). A post as the player sees it, in a `FeedView`'s `posts`. ```ts shape import type { PostView } from '@ifloom/plugin-feed' type PostView = { id: string from: string name: string portrait: string | null text: string beats: SceneBeat[] image: string | null video: string | null turn: number likes: number comments: { from: string; name: string; text: string }[] mine: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The post's id. | | `from` | `string` | | | The poster as written, a character's id or a name. It's `''` for the player's own post. | | `name` | `string` | | | The poster's name, or for the player's own post the `playerName` kv key, else the `feed/you` string ("You"). | | `portrait` | `string \| null` | | | The poster's face for an avatar, through `artSrc`. It's a person's `portrait` with the cast, else their entity's picture. It's null for the player's own post and for a poster named only as written. | | `text` | `string` | | | The post's words, tokens filled in, with any picture and video markup in them. | | `beats` | [`SceneBeat[]`](https://ifloom.dev/docs/api/engine#scenebeat) | | | The post's words rendered as beats, as a scene's are, with pictures and videos in the order written. | | `image` | `string \| null` | | | The post's picture's path, through `artSrc`, or null when it has none. | | `video` | `string \| null` | | | The post's video clip's path, through `artSrc`, or null when it has none. | | `turn` | `number` | | | The turn the post appeared on, or was posted on. | | `likes` | `number` | | | The number of likes the post has, its starting likes plus any reactions. | | `comments` | `{ from: string; name: string; text: string }[]` | | | The comments on the post, oldest first, each with its commenter as written, their name and its words. | | `mine` | `boolean` | | | True for the player's own post. | ## @ifloom/plugin-feed/react [#ifloomplugin-feedreact] - Functions: [`useFeed`](#usefeed) - Constants: [`FEED_WORDS`](#feed_words), [`FeedSection`](#feedsection), [`feedUi`](#feedui) - Types: [`FeedControls`](#feedcontrols) ### FEED_WORDS [#feed_words] Const. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#feed_words). The feed plugin's words in English, keyed by name. A game rewords any of them with `ui.` in its strings. ```ts shape import { FEED_WORDS } from '@ifloom/plugin-feed/react' const FEED_WORDS: { readonly likes: '♥ {n}'; } ``` ### FeedControls [#feedcontrols] Type. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#feedcontrols). The feed plugin's view with a way to mark a feed seen, as `useFeed` returns it. ```ts shape import type { FeedControls } from '@ifloom/plugin-feed/react' type FeedControls = { feeds: FeedView[] unread: number seen: (feed: string) => Result } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `feeds` | [`FeedView[]`](#feedview) | | | The game's feeds, in declared order. | | `unread` | `number` | | | The number of unseen posts across every feed. | | `seen` | `(feed: string) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends the `feed/seen` command, which marks the feed's posts seen. | ### FeedSection [#feedsection] Const. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#feedsection). Renders the feed named by an app section's `with.feed`, from `view.plugins.feed`, newest post first. A preset styles its `feed`, `post` and `post-*` parts. Each post shows its likes and comments, and a button marks the feed seen. A post's words render as beats through `Beat`, and its `video` through `Video`, playing, looping and muted. ```ts shape import { FeedSection } from '@ifloom/plugin-feed/react' const FeedSection: ComponentType ``` Uses: [`SectionProps`](https://ifloom.dev/docs/api/react#sectionprops). ### feedUi [#feedui] Const. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#feedui). The feed plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It registers `FeedSection` for a device app's `feed` section, and adds the plugin's words. ```ts shape import { feedUi } from '@ifloom/plugin-feed/react' const feedUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### useFeed [#usefeed] Function. Explained in [Feed](https://ifloom.dev/docs/reference/plugins/feed#usefeed). Returns the feed plugin's view and its command from the running game, or null in a game without the plugin. It re-renders when the view changes. `FeedSection` renders from it. ```ts shape import { useFeed } from '@ifloom/plugin-feed/react' function useFeed(): FeedControls | null ``` Uses: [`FeedControls`](#feedcontrols). # @ifloom/plugin-generators (https://ifloom.dev/docs/api/plugin-generators) Generated from the source of `@ifloom/plugin-generators` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. - Functions: [`drawEntity`](#drawentity), [`generators`](#generators), [`poolsOf`](#poolsof), [`templateKind`](#templatekind), [`templatesOf`](#templatesof) - Types: [`FieldDef`](#fielddef), [`GeneratedEntity`](#generatedentity), [`PoolDef`](#pooldef), [`PoolEntry`](#poolentry), [`TemplateDef`](#templatedef) ## drawEntity [#drawentity] Function. Explained in [Generators](https://ifloom.dev/docs/reference/plugins/generators#drawentity). Returns the values a template draws for the `n`th entity of its kind made in play in this save. The same save, template and `n` always draw the same values. The `generators/generate` effect passes the number the engine's `create` gives the next entity, so each new entity differs and a replay makes the same ones. ```ts shape import { drawEntity } from '@ifloom/plugin-generators' function drawEntity(state: GameState, game: Game, template: TemplateDef, n: number): GeneratedEntity ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`TemplateDef`](#templatedef), [`GeneratedEntity`](#generatedentity). ## FieldDef [#fielddef] Type. Explained in [Generators](https://ifloom.dev/docs/reference/plugins/generators#fielddef). A field of a template, which gives one value of a new entity. Each form is told apart by its shape. The forms are: - a fixed value, as written, such as `'visitor'`, `3` or `true` - `{ pool: 'first-names' }`, one value drawn from a pool by weight - `{ between: [1, 5] }`, a whole number from the first to the second, both included - `{ join: [...], with?: ' ' }`, several fields drawn and joined into one string, with a space if `with` is left out ```ts shape import type { FieldDef } from '@ifloom/plugin-generators' type FieldDef = KvValue | { pool: string } | { between: [ number, number ] } | { join: FieldDef[]; with?: string } ``` Uses: [`KvValue`](https://ifloom.dev/docs/api/engine#kvvalue). ## GeneratedEntity [#generatedentity] Type. Explained in [Generators](https://ifloom.dev/docs/reference/plugins/generators#generatedentity). The values a template draws for one entity, as `drawEntity` returns them. They're the fields of the engine's `create` effect that come from pools and ranges. ```ts shape import type { GeneratedEntity } from '@ifloom/plugin-generators' type GeneratedEntity = { name?: string description?: string image?: string stats: Record kv: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string` | yes | | The drawn name, left out when the template gives none. | | `description` | `string` | yes | | The drawn description, left out when the template gives none. | | `image` | `string` | yes | | The drawn picture's path, left out when the template gives none. | | `stats` | `Record` | | | The drawn stats by id. A field that draws no finite number is left out. | | `kv` | `Record` | | | The drawn kv values by key. | ## generators [#generators] Function. Explained in [Generators](https://ifloom.dev/docs/reference/plugins/generators#generators). Returns the generators plugin, for the game's `plugins`. Content declares pools and templates in `data.generators.pools` and `data.generators.templates`. Its helper writes its effect, such as `generators.generate('regular')`. ```ts shape import { generators } from '@ifloom/plugin-generators' function generators(): DefinedPlugin ``` Uses: [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin). | Helper | Signature | Description | |---|---|---| | `generators.generate` | `(template: string, count?: number):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `generators/generate` effect, which makes `count` new entities from the template, 1 if left out. | ## PoolDef [#pooldef] Type. Explained in [Generators](https://ifloom.dev/docs/reference/plugins/generators#pooldef). A pool the game declares in `data.generators.pools`, a named list of values a template picks from. At least one entry must weigh more than 0. ```ts shape import type { PoolDef } from '@ifloom/plugin-generators' type PoolDef = { id: string values: PoolEntry[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The pool's id, which a field's `{ pool }` names. | | `values` | [`PoolEntry[]`](#poolentry) | | | The pool's entries, each picked by its weight. | ## PoolEntry [#poolentry] Type. Explained in [Generators](https://ifloom.dev/docs/reference/plugins/generators#poolentry). An entry of a pool, a value or a value with a weight. A bare value, or a weight left out, weighs 1. ```ts shape import type { PoolEntry } from '@ifloom/plugin-generators' type PoolEntry = KvValue | { value: KvValue; weight?: number } ``` Uses: [`KvValue`](https://ifloom.dev/docs/api/engine#kvvalue). ## poolsOf [#poolsof] Function. Explained in [Generators](https://ifloom.dev/docs/reference/plugins/generators#poolsof). Returns the game's pools, `data.generators.pools` from its content and packs, in declared order. ```ts shape import { poolsOf } from '@ifloom/plugin-generators' function poolsOf(game: Game): PoolDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`PoolDef`](#pooldef). ## TemplateDef [#templatedef] Type. Explained in [Generators](https://ifloom.dev/docs/reference/plugins/generators#templatedef). A template the game declares in `data.generators.templates`, which makes entities of one kind through the engine's `create` effect. It needs an `of` or a `like`, and a `name` or a `like`. ```ts shape import type { TemplateDef } from '@ifloom/plugin-generators' type TemplateDef = { id: string of?: string like?: EntityRef name?: FieldDef description?: FieldDef image?: FieldDef tags?: string[] traits?: Record effects?: EffectRef[] stats?: Record kv?: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The template's id, which `generators/generate` names. | | `of` | `string` | yes | | The kind of entity the template makes. The `like`'s kind if left out. | | `like` | [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | yes | | The entity the new ones are made like. The engine reads from it the fields the template doesn't give, such as the name, picture, traits and stats. | | `name` | [`FieldDef`](#fielddef) | yes | | The new entity's name. The `like`'s name if left out. | | `description` | [`FieldDef`](#fielddef) | yes | | The new entity's description, drawn as the name is. | | `image` | [`FieldDef`](#fielddef) | yes | | The new entity's picture, a path in the game's `art/` folder, drawn as the name is, such as `{ pool: 'faces' }`. | | `tags` | `string[]` | yes | | The new entity's tags, added after its kind's and its `like`'s. | | `traits` | `Record` | yes | | The new entity's trait data by trait id, over its `like`'s or its kind's, such as `{ 'cast/person': { home: 'park' } }`. | | `effects` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | The effects that run once the new entity is made, with `'$'` as it, such as `[{ receive: '$' }]` to hand it to whichever plugin keeps things. Nothing more happens if left out. | | `stats` | `Record` | yes | | The new entity's stats by id, each a stat the game declares for the kind. A stat left out reads the `like`'s value, else its `start`. | | `kv` | `Record` | yes | | The new entity's kv keys by name. | ## templateKind [#templatekind] Function. Explained in [Generators](https://ifloom.dev/docs/reference/plugins/generators#templatekind). Returns the kind a template makes, its `of`, else its `like`'s kind. It's undefined when the template has neither. ```ts shape import { templateKind } from '@ifloom/plugin-generators' function templateKind(template: TemplateDef): string | undefined ``` Uses: [`TemplateDef`](#templatedef). ## templatesOf [#templatesof] Function. Explained in [Generators](https://ifloom.dev/docs/reference/plugins/generators#templatesof). Returns the game's templates, `data.generators.templates` from its content and packs, in declared order. ```ts shape import { templatesOf } from '@ifloom/plugin-generators' function templatesOf(game: Game): TemplateDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`TemplateDef`](#templatedef). # @ifloom/plugin-inventory (https://ifloom.dev/docs/api/plugin-inventory) Generated from the source of `@ifloom/plugin-inventory` and `@ifloom/plugin-inventory/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-inventory [#ifloomplugin-inventory] - Functions: [`canHold`](#canhold), [`heldBy`](#heldby), [`heldCount`](#heldcount), [`holderOf`](#holderof), [`holdersOf`](#holdersof), [`inventory`](#inventory), [`inventoryKindsOf`](#inventorykindsof), [`usableOf`](#usableof) - Types: [`Holder`](#holder), [`InventoryData`](#inventorydata), [`InventoryOptions`](#inventoryoptions), [`InventoryState`](#inventorystate), [`InventoryThing`](#inventorything), [`InventoryView`](#inventoryview), [`Placement`](#placement), [`Usable`](#usable) ### canHold [#canhold] Function. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#canhold). Returns true when `holder` can hold things now. The player always can, and a unique entity can while it is in the game. ```ts shape import { canHold } from '@ifloom/plugin-inventory' function canHold(state: GameState, game: Game, holder: string): boolean ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game). ### heldBy [#heldby] Function. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#heldby). Returns the things a holder holds, `'you'` if left out, each with its count, in the game's order of its entities. ```ts shape import { heldBy } from '@ifloom/plugin-inventory' function heldBy(state: GameState, game: Game, at?: string): { ref: EntityRef; count: number }[] ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref). ### heldCount [#heldcount] Function. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#heldcount). Returns the count of a thing a holder holds, `'you'` if left out. Returns 0 for a thing not held there or not in the game. ```ts shape import { heldCount } from '@ifloom/plugin-inventory' function heldCount(state: GameState, game: Game, ref: string, at?: string): number ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game). ### Holder [#holder] Type. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#holder). A holder of things, `'player'`, a unique entity (`'character:ava'`) or `'you'`, whoever the player is playing now. ```ts shape import type { Holder } from '@ifloom/plugin-inventory' type Holder = EntityRef | typeof PLAYER | typeof YOU ``` Uses: [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref). ### holderOf [#holderof] Function. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#holderof). Returns the holder of a thing when one holder has it, as always for a unique thing. Undefined when no one holds it. ```ts shape import { holderOf } from '@ifloom/plugin-inventory' function holderOf(state: GameState, game: Game, ref: string): Holder | undefined ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`Holder`](#holder). ### holdersOf [#holdersof] Function. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#holdersof). Returns each holder of a thing with its count, in no set order. ```ts shape import { holdersOf } from '@ifloom/plugin-inventory' function holdersOf(state: GameState, game: Game, ref: string): { holder: Holder; count: number }[] ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`Holder`](#holder). ### inventory [#inventory] Function. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventory). The inventory plugin's factory, with its helpers as properties. `inventory()` returns the plugin for the game's `plugins`, and content calls helpers such as `inventory.usable('Eat', effects)` and `inventory.use('food:apple')`. ```ts shape import { inventory } from '@ifloom/plugin-inventory' function inventory(options?: InventoryOptions): DefinedPlugin ``` Uses: [`InventoryOptions`](#inventoryoptions), [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`InventoryState`](#inventorystate), [`InventoryView`](#inventoryview). | Helper | Signature | Description | |---|---|---| | `inventory.usable` | `(label: string, effects:` [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref)`, options?: { keep?: boolean }): { 'inventory/usable':` [`Usable`](#usable) `}` | Returns the `inventory/usable` trait, to spread into an entity's or a kind's `traits`. Using the thing spends one unless `keep` is true. | | `inventory.at` | `(placement:` [`Placement`](#placement)`): { 'inventory/at':` [`Placement`](#placement) `}` | Returns the `inventory/at` trait, to spread into an entity's `traits`, naming who holds it at the start. | | `inventory.use` | `(ref:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `inventory/use` command, which uses one of a thing the player holds. | | `inventory.drop` | `(ref:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `inventory/drop` command, which drops one of a thing the player holds. | | `inventory.give` | `(ref:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, to:` [`Holder`](#holder)`):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `inventory/give` command, which gives one of a thing the player holds to someone. | | `inventory.move` | `(entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, to:` [`Holder`](#holder)`, options?: { from?:` [`Holder`](#holder)`; by?: number }):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `inventory/move` effect, which moves a thing from one holder to another, from `'you'` if `from` is left out. | | `inventory.set` | `(entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, to: number, holder?:` [`Holder`](#holder)`):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `inventory/set` effect, which sets how many of a thing a holder (`'you'` if left out) holds. | ### InventoryData [#inventorydata] Type. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventorydata). The inventory plugin's content, which the game declares in `data.inventory`. ```ts shape import type { InventoryData } from '@ifloom/plugin-inventory' type InventoryData = { kinds?: { id: string }[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `kinds` | `{ id: string }[]` | yes | | The kinds whose things the inventory shows in `InventoryView`, each an entry with the kind's id (`{ id: 'food' }`), so a mod can add one. Every kind if left out. | ### inventoryKindsOf [#inventorykindsof] Function. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventorykindsof). Returns the kinds the inventory shows, from `data.inventory.kinds` in the game's content and packs. Returns undefined when every kind is shown. ```ts shape import { inventoryKindsOf } from '@ifloom/plugin-inventory' function inventoryKindsOf(game: Game): { id: string }[] | undefined ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game). ### InventoryOptions [#inventoryoptions] Type. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventoryoptions). The inventory plugin's settings, which the game passes to `inventory()`. ```ts shape import type { InventoryOptions } from '@ifloom/plugin-inventory' type InventoryOptions = { carryOver?: readonly string[] | 'all' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `carryOver` | `readonly string[] \| 'all'` | yes | | The things a New Game+ keeps in the player's own inventory, by reference (`'food:apple'`), or `'all'` for everything the player holds, things made in play included. Nothing if left out. | ### InventoryState [#inventorystate] Type. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventorystate). The inventory's state, the counts play changed. ```ts shape import type { InventoryState } from '@ifloom/plugin-inventory' type InventoryState = { held: Record> } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `held` | `Record>` | | | The counts play changed, by holder and then thing. A count stays once written, 0 included. | ### InventoryThing [#inventorything] Type. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventorything). A thing someone holds as the player sees it, in `view.plugins.inventory.things`. ```ts shape import type { InventoryThing } from '@ifloom/plugin-inventory' type InventoryThing = { ref: EntityRef name: string description: string | null image: string | null count: number at: Holder use: RenderedChoice | null drop: RenderedChoice } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `ref` | [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | | | The thing's entity reference, such as `'food:apple'`. | | `name` | `string` | | | The thing's name. | | `description` | `string \| null` | | | The thing's `description`, with its tokens filled, or null when it has none. | | `image` | `string \| null` | | | The path of the thing's picture through `artSrc`, or null when it has none. | | `count` | `number` | | | The number of this thing the holder holds. | | `at` | [`Holder`](#holder) | | | The thing's holder, the protagonist being played or `'player'`. | | `use` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that uses one, labelled by its trait, or null for a thing with no use. Its `command` is the one to send. | | `drop` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) | | | The button that drops one. | ### InventoryView [#inventoryview] Type. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventoryview). The inventory as the player sees it, in `view.plugins.inventory`. ```ts shape import type { InventoryView } from '@ifloom/plugin-inventory' type InventoryView = { things: InventoryThing[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `things` | [`InventoryThing[]`](#inventorything) | | | The things the inventory shows, the played protagonist's first and then the player's. | ### Placement [#placement] Type. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#placement). A thing's starting place, one holder for one of it or a count for each holder (`{ player: 2, 'place:larder': 6 }`). ```ts shape import type { Placement } from '@ifloom/plugin-inventory' type Placement = Holder | Partial> ``` Uses: [`Holder`](#holder). ### Usable [#usable] Type. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#usable). The data of the `inventory/usable` trait, which makes a thing usable. It gives the button's label, the effects of using one and whether one is kept. ```ts shape import type { Usable } from '@ifloom/plugin-inventory' type Usable = { label: string effects: EffectRef[] keep?: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `label` | `string` | | | The label of the button that uses one, such as "Eat the sandwich". | | `effects` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | | | The effects of using one. They read the state as it was before one was spent. | | `keep` | `boolean` | yes | | True when using one doesn't spend it, as for a book read or a torch switched on. One is spent if left out. | ### usableOf [#usableof] Function. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#usableof). Returns a thing's `inventory/usable` trait, read through the entity it was made `like`. Returns undefined for a thing with no use. ```ts shape import { usableOf, type Usable } from '@ifloom/plugin-inventory' function usableOf(state: GameState, game: Game, ref: EntityRef): Usable | undefined ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref), [`Usable`](#usable). ## @ifloom/plugin-inventory/react [#ifloomplugin-inventoryreact] - Components: [`InventorySection`](#inventorysection) - Functions: [`useInventory`](#useinventory) - Constants: [`INVENTORY_WORDS`](#inventory_words), [`InventoryCard`](#inventorycard), [`inventoryUi`](#inventoryui) - Types: [`InventoryControls`](#inventorycontrols), [`InventoryProps`](#inventoryprops) ### INVENTORY_WORDS [#inventory_words] Const. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventory_words). The inventory plugin's UI words, in English. A game rewords any of them with `ui.` in its strings. ```ts shape import { INVENTORY_WORDS } from '@ifloom/plugin-inventory/react' const INVENTORY_WORDS: { inventory: 'Carrying' heldCount: '×{n}' drop: 'Drop' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `inventory` | `'Carrying'` | | | The heading over the things the player carries. | | `heldCount` | `'×{n}'` | | | The count beside a thing held more than once, with `{n}` for the number. | | `drop` | `'Drop'` | | | The label of the button that drops one. | ### InventoryCard [#inventorycard] Const. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventorycard). Renders the things the player holds from `view.plugins.inventory`, each usable one with a button. It renders nothing while they hold nothing, or in a game without the plugin. A button that can't be used now is disabled with the engine's reason, and the `drop` prop adds a button that drops one. A preset can style the parts `inventory`, `inventory-title`, `thing`, `thing-name`, `thing-count`, `thing-text` and `thing-drop`. ```ts shape import { InventoryCard } from '@ifloom/plugin-inventory/react' const InventoryCard: ComponentType ``` Uses: [`InventoryProps`](#inventoryprops). ### InventoryControls [#inventorycontrols] Type. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventorycontrols). The inventory plugin's view with functions that send its commands, as `useInventory` returns it. ```ts shape import type { InventoryControls } from '@ifloom/plugin-inventory/react' type InventoryControls = { things: InventoryThing[] use: (ref: EntityRef) => Result drop: (ref: EntityRef) => Result give: (ref: EntityRef, to: Holder) => Result } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `things` | [`InventoryThing[]`](#inventorything) | | | The things the inventory shows, the played protagonist's first and then the player's. | | `use` | `(ref:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends `inventory/use` for one of a thing the player holds. A refusal carries the same reason the button shows. | | `drop` | `(ref:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends `inventory/drop` for one of a thing the player holds. | | `give` | `(ref:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, to:` [`Holder`](#holder)`) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends `inventory/give`, which gives one of a thing the player holds to someone. | ### InventoryProps [#inventoryprops] Type. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventoryprops). The props of `InventoryCard`. ```ts shape import type { InventoryProps } from '@ifloom/plugin-inventory/react' type InventoryProps = { className?: string title?: string | false drop?: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `className` | `string` | yes | | Classes added to the `inventory` part's own. | | `title` | `string \| false` | yes | | The heading, the `inventory` word if left out. `false` leaves it out, as under a section's title. | | `drop` | `boolean` | yes | | True to give each thing a button that drops one. | ### InventorySection [#inventorysection] Component. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventorysection). Renders `InventoryCard` in a folding sidebar section titled with the `inventory` word. It hides itself while nothing is held. ```ts shape import { InventorySection } from '@ifloom/plugin-inventory/react' function InventorySection(): JSX.Element ``` ### inventoryUi [#inventoryui] Const. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#inventoryui). The inventory plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It adds `InventorySection` to the sidebar and an `inventory` panel, and the plugin's words. ```ts shape import { inventoryUi } from '@ifloom/plugin-inventory/react' const inventoryUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### useInventory [#useinventory] Function. Explained in [Inventory](https://ifloom.dev/docs/reference/plugins/inventory#useinventory). Returns the inventory plugin's view and commands from the running game, or null in a game without the plugin. It re-renders when the view changes. ```ts shape import { useInventory } from '@ifloom/plugin-inventory/react' function useInventory(): InventoryControls | null ``` Uses: [`InventoryControls`](#inventorycontrols). # @ifloom/plugin-jobs (https://ifloom.dev/docs/api/plugin-jobs) Generated from the source of `@ifloom/plugin-jobs` and `@ifloom/plugin-jobs/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-jobs [#ifloomplugin-jobs] - Functions: [`jobOf`](#jobof), [`jobs`](#jobs), [`jobsOf`](#jobsof) - Types: [`FireDef`](#firedef), [`HeldJob`](#heldjob), [`JobDef`](#jobdef), [`JobsState`](#jobsstate), [`JobsView`](#jobsview), [`JobView`](#jobview), [`RankDef`](#rankdef), [`RankView`](#rankview), [`ShiftDef`](#shiftdef) ### FireDef [#firedef] Type. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#firedef). The rules that get the player fired from a job, which the game declares in a `JobDef`'s `fire`. ```ts shape import type { FireDef } from '@ifloom/plugin-jobs' type FireDef = { missed?: number when?: Condition } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `missed` | `number` | yes | | The number of missed shifts, in all, that gets the player fired. At least 1. | | `when` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | yes | | The condition that gets the player fired as soon as it holds after a command, such as a performance stat too low. | ### HeldJob [#heldjob] Type. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#heldjob). The record a save keeps for a job the player holds, in `JobsState`'s `held`. The plugin reads the job's definition from content. ```ts shape import type { HeldJob } from '@ifloom/plugin-jobs' type HeldJob = { rank: number shifts: number missed: number hiredOn: number lastWorked: number | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `rank` | `number` | | | The index of the rank the player holds, from 0. | | `shifts` | `number` | | | The number of shifts the player has worked at the job. | | `missed` | `number` | | | The number of shifts the player has missed at the job. | | `hiredOn` | `number` | | | The day the player was hired, the calendar's day or the turn without the calendar. | | `lastWorked` | `number \| null` | | | The day of the last shift worked, or null before the first. | ### JobDef [#jobdef] Type. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#jobdef). A job the game declares in `data.jobs.jobs`. It needs at least one rank. ```ts shape import type { JobDef } from '@ifloom/plugin-jobs' type JobDef = { id: string name: string description?: string blocked?: Blocked[] days?: number[] hours?: string[] shift: ShiftDef ranks: RankDef[] fire?: FireDef } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The job's id. | | `name` | `string` | | | The job's name, such as "Weekend help". | | `description` | `string` | yes | | The job's line or two for the job board. | | `blocked` | [`Blocked[]`](https://ifloom.dev/docs/api/engine#blocked) | yes | | The reasons an application is refused. The first entry whose `when` holds gives its reason. | | `days` | `number[]` | yes | | The weekdays the job has shifts on, from 0, read with the calendar plugin. Every day if left out. | | `hours` | `string[]` | yes | | The calendar periods a shift can start in. Any period if left out. | | `shift` | [`ShiftDef`](#shiftdef) | | | The job's shift, its cost, time and effects. | | `ranks` | [`RankDef[]`](#rankdef) | | | The job's ladder of ranks, lowest first. The player is hired at the first. | | `fire` | [`FireDef`](#firedef) | yes | | The rules that get the player fired. The player is never fired if left out. | ### jobOf [#jobof] Function. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#jobof). Returns the job with this id, or undefined when the game has none. ```ts shape import { jobOf } from '@ifloom/plugin-jobs' function jobOf(game: Game, id: string): JobDef | undefined ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`JobDef`](#jobdef). ### jobs [#jobs] Function. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#jobs). The jobs plugin's factory, with its helpers as properties. `jobs()` returns the plugin for the game's `plugins`, and content calls helpers such as `jobs.apply('cafe')` and `jobs.fire('cafe')`. ```ts shape import { jobs } from '@ifloom/plugin-jobs' function jobs(): DefinedPlugin ``` Uses: [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`JobsState`](#jobsstate), [`JobsView`](#jobsview). | Helper | Signature | Description | |---|---|---| | `jobs.open` | `(jobs?: string[]):` [`Effect`](https://ifloom.dev/docs/api/engine#effect) | Returns the effect that opens the job board in the `jobs` panel, showing only `jobs` if given. | | `jobs.apply` | `(job: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `jobs/apply` command, which applies for the job. | | `jobs.work` | `(job: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `jobs/work` command, which works a shift at the job. | | `jobs.quit` | `(job: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `jobs/quit` command, which leaves the job. | | `jobs.hire` | `(job: string):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `jobs/hire` effect, which hires the player now without checking the job's `blocked`. | | `jobs.fire` | `(job: string):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `jobs/fire` effect, which fires the player from the job now, with a notice. | | `jobs.hired` | `(job: string, rank?: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `jobs/hired` condition, which holds while the player holds the job, at `rank` if given. | | `jobs.fired` | `(job: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `jobs/fired` condition, which holds once the player has been fired from the job. | | `jobs.shifts` | `(job: string, range:` [`Range`](https://ifloom.dev/docs/api/engine#range)`):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `jobs/shifts` condition, which holds while the shifts worked at a held job fall in the range. | | `jobs.worked` | `(job?: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `jobs/worked` condition, which holds once the player has worked a shift today, at `job` or at any job. | ### jobsOf [#jobsof] Function. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#jobsof). Returns the game's jobs, from `data.jobs.jobs` in its content and packs. ```ts shape import { jobsOf } from '@ifloom/plugin-jobs' function jobsOf(game: Game): JobDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`JobDef`](#jobdef). ### JobsState [#jobsstate] Type. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#jobsstate). The jobs a save keeps for the player, held and fired. The plugin reads the jobs from content. ```ts shape import type { JobsState } from '@ifloom/plugin-jobs' type JobsState = { held: Record fired: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `held` | `Record` | | | The jobs the player holds, by job id. | | `fired` | `Record` | | | The day the player was fired from each job, by job id. The player can't apply for these again. | ### JobsView [#jobsview] Type. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#jobsview). The jobs as the player sees them, in `view.plugins.jobs`. ```ts shape import type { JobsView } from '@ifloom/plugin-jobs' type JobsView = { jobs: JobView[] panel: JobView[] | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `jobs` | [`JobView[]`](#jobview) | | | The game's jobs, in the order the game declares them. | | `panel` | [`JobView[]`](#jobview) `\| null` | | | The jobs on the open `jobs` panel, or null while it's closed. It holds only the jobs the panel's `with.job` names, or every job when it names none. | ### JobView [#jobview] Type. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#jobview). A job as the player sees it, in `view.plugins.jobs.jobs`. ```ts shape import type { JobView } from '@ifloom/plugin-jobs' type JobView = { id: string name: string description: string hired: boolean firedOn: number | null rank: RankView | null next: (RankView & { shiftsToGo: number }) | null pay: Price | null shifts: number missed: number nextShift: { day: number; inDays: number } | null apply: RenderedChoice | null work: RenderedChoice | null quit: RenderedChoice | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The job's id. | | `name` | `string` | | | The job's name. | | `description` | `string` | | | The job's description, or `''` when it has none. | | `hired` | `boolean` | | | True while the player holds the job. | | `firedOn` | `number \| null` | | | The day the player was fired from the job, or null. | | `rank` | [`RankView`](#rankview) `\| null` | | | The rank the player holds, or null when not hired. | | `next` | `(`[`RankView`](#rankview) `& { shiftsToGo: number }) \| null` | | | The next rank up with the number of shifts still needed for it, or null at the top or when not hired. `shiftsToGo` is 0 when only the rank's condition is missing. | | `pay` | [`Price`](https://ifloom.dev/docs/api/engine#price) `\| null` | | | The pay for a shift now, the held rank's or the first rank's for a job not held. | | `shifts` | `number` | | | The number of shifts the player has worked at the job. | | `missed` | `number` | | | The number of shifts the player has missed at the job. | | `nextShift` | `{ day: number; inDays: number } \| null` | | | The next day with a shift, with `inDays` 0 for today. Null when not hired or when no shift falls in the next two weeks. | | `apply` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that applies, or null once hired or fired. Its `disabled` gives the reason an application is refused. | | `work` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that works a shift, or null when not hired. Its `price` is the shift's cost. | | `quit` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that leaves the job, labelled with the `jobs/quit` string (`Quit`), or null when not hired. | ### RankDef [#rankdef] Type. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#rankdef). A rank on a job's ladder, which the game declares in a `JobDef`'s `ranks`. The player starts at the first. ```ts shape import type { RankDef } from '@ifloom/plugin-jobs' type RankDef = { id: string name: string pay: Record requires?: { shifts?: number; when?: Condition } } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The rank's id, unique within its job. | | `name` | `string` | | | The rank's name, such as "Barista". | | `pay` | `Record` | | | The pay for a shift at this rank, by stat, such as `{ coins: 18 }`. | | `requires` | `{ shifts?: number; when?:` [`Condition`](https://ifloom.dev/docs/api/engine#condition) `}` | yes | | The rank's requirements for a promotion, a number of shifts worked and a condition. The first rank, where the player starts, can't have any. | ### RankView [#rankview] Type. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#rankview). A rank as the player sees it, in a `JobView`'s `rank` and `next`. ```ts shape import type { RankView } from '@ifloom/plugin-jobs' type RankView = { id: string name: string pay: Price | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The rank's id. | | `name` | `string` | | | The rank's name. | | `pay` | [`Price`](https://ifloom.dev/docs/api/engine#price) `\| null` | | | The pay for a shift at this rank, or null when it pays nothing. | ### ShiftDef [#shiftdef] Type. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#shiftdef). A job's shift, which the game declares in a `JobDef`'s `shift`. It sets what one shift costs, takes and does. ```ts shape import type { ShiftDef } from '@ifloom/plugin-jobs' type ShiftDef = { blocked?: Blocked[] cost?: Record passes?: number effects?: EffectRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `blocked` | [`Blocked[]`](https://ifloom.dev/docs/api/engine#blocked) | yes | | The reasons a shift is refused. The first entry whose `when` holds gives its reason. A workplace is one entry, such as `places.onlyAt(['cafe'], { string: 'jobs/notHere' })`, which never holds without the places plugin. | | `cost` | `Record` | yes | | The stats a shift spends, by id, such as `{ energy: 30 }`. The plugin refuses the shift while the player has too little, as for an action's cost. | | `passes` | `number` | yes | | The number of the calendar's periods a shift takes. None if left out, or without the calendar. | | `effects` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | The shift's other effects, which run after the cost and the time and before the pay, such as raising a performance stat. | ## @ifloom/plugin-jobs/react [#ifloomplugin-jobsreact] - Functions: [`useJobs`](#usejobs) - Constants: [`JobBoard`](#jobboard), [`JOBS_WORDS`](#jobs_words), [`jobsUi`](#jobsui) - Types: [`JobsControls`](#jobscontrols) ### JobBoard [#jobboard] Const. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#jobboard). Renders the job board from `view.plugins.jobs.jobs`, each job with its rank, pay, next shift, promotion and record. The `jobs` prop shows only those jobs by id, and `title={false}` leaves the heading off. A job not held has an Apply button, and a job held has Work a shift and Quit. A disabled button shows the engine's reason, and a job the player was fired from says so. A preset can style the parts `jobs`, `jobs-title`, `job`, `job-title`, `job-rank`, `job-fired`, `job-text`, `job-details`, `job-pay`, `job-shift`, `job-next`, `job-record` and `job-actions`. ```ts shape import { JobBoard } from '@ifloom/plugin-jobs/react' const JobBoard: ComponentType<{ className?: string; title?: string | false; jobs?: readonly string[]; }> ``` ### JOBS_WORDS [#jobs_words] Const. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#jobs_words). The jobs plugin's UI words, in English. A game rewords any of them with `ui.` in its strings. ```ts shape import { JOBS_WORDS } from '@ifloom/plugin-jobs/react' const JOBS_WORDS: { applyJob: 'Apply' jobFired: 'Let go' jobMissed: 'Missed: {n}' jobNextRank: 'Next: {title}, after {n} more shifts' jobNextRankOne: 'Next: {title}, after 1 more shift' jobNextRankSoon: 'Next: {title}' jobPay: 'Pays {pay} a shift' jobShifts: 'Shifts worked: {n}' jobs: 'Jobs' shiftInDays: 'Next shift: in {n} days' shiftToday: 'Next shift: today' shiftTomorrow: 'Next shift: tomorrow' workShift: 'Work a shift' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `applyJob` | `'Apply'` | | | The label of the button that applies for a job. | | `jobFired` | `'Let go'` | | | The badge on a job the player was fired from. | | `jobMissed` | `'Missed: {n}'` | | | The count of shifts missed, with `{n}`. | | `jobNextRank` | `'Next: {title}, after {n} more shifts'` | | | The line that names the next rank, with its `{title}` and the `{n}` shifts still to work. | | `jobNextRankOne` | `'Next: {title}, after 1 more shift'` | | | The line that names the next rank, with its `{title}`, when one shift is still to work. | | `jobNextRankSoon` | `'Next: {title}'` | | | The line that names the next rank, with its `{title}`, when no more shifts are needed. | | `jobPay` | `'Pays {pay} a shift'` | | | The line that gives a shift's pay, with `{pay}`. | | `jobShifts` | `'Shifts worked: {n}'` | | | The count of shifts worked, with `{n}`. | | `jobs` | `'Jobs'` | | | The title of the job board. | | `shiftInDays` | `'Next shift: in {n} days'` | | | The line that gives the next shift, `{n}` days ahead. | | `shiftToday` | `'Next shift: today'` | | | The line that gives the next shift as today. | | `shiftTomorrow` | `'Next shift: tomorrow'` | | | The line that gives the next shift as tomorrow. | | `workShift` | `'Work a shift'` | | | The label of the button that works a shift. | ### JobsControls [#jobscontrols] Type. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#jobscontrols). The jobs plugin's view with the jobs held and functions that send its commands, as `useJobs` returns it. ```ts shape import type { JobsControls } from '@ifloom/plugin-jobs/react' type JobsControls = { jobs: JobView[] panel: JobView[] | null held: JobView[] apply: (job: string) => Result work: (job: string) => Result quit: (job: string) => Result } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `jobs` | [`JobView[]`](#jobview) | | | The game's jobs, in the order the game declares them. | | `panel` | [`JobView[]`](#jobview) `\| null` | | | The jobs on the open `jobs` panel, or null while it's closed. It holds only the jobs the panel's `with.job` names, or every job when it names none. | | `held` | [`JobView[]`](#jobview) | | | The jobs the player holds, in the order the game declares them. | | `apply` | `(job: string) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends `jobs/apply` for the job. A refusal carries the same reason its `apply` button shows. | | `work` | `(job: string) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends `jobs/work`, which works a shift at the job. | | `quit` | `(job: string) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends `jobs/quit`, which leaves the job. The player can apply again. | ### jobsUi [#jobsui] Const. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#jobsui). The jobs plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It renders the `jobs` panel, which `jobs.open()` opens, as a `JobBoard` of the jobs it was opened with, and adds the plugin's words. It adds nothing to the layout, so the board shows only when content opens it. ```ts shape import { jobsUi } from '@ifloom/plugin-jobs/react' const jobsUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### useJobs [#usejobs] Function. Explained in [Jobs](https://ifloom.dev/docs/reference/plugins/jobs#usejobs). Returns the jobs plugin's view and commands from the running game, or null in a game without the plugin. It re-renders when the view changes. ```ts shape import { useJobs } from '@ifloom/plugin-jobs/react' function useJobs(): JobsControls | null ``` Uses: [`JobsControls`](#jobscontrols). # @ifloom/plugin-messages (https://ifloom.dev/docs/api/plugin-messages) Generated from the source of `@ifloom/plugin-messages` and `@ifloom/plugin-messages/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-messages [#ifloomplugin-messages] - Functions: [`channelsOf`](#channelsof), [`messages`](#messages), [`messagesOf`](#messagesof) - Types: [`Arrival`](#arrival), [`Channel`](#channel), [`ChannelView`](#channelview), [`MessageDef`](#messagedef), [`MessagesState`](#messagesstate), [`MessagesView`](#messagesview), [`MessageView`](#messageview), [`ReplyDef`](#replydef), [`ThreadView`](#threadview) ### Arrival [#arrival] Type. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#arrival). The record a save keeps of one arrival of a message, in `MessagesState`'s `arrived`. A message drawn from a pool can arrive again, and each arrival has its own reply and read mark. ```ts shape import type { Arrival } from '@ifloom/plugin-messages' type Arrival = { key: string message: string turn: number day: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `key` | `string` | | | The arrival's key, the message's id the first time it arrives and then `~2`, `~3` and so on. The plugin keeps replies and reads by this key, and the reply command names it. | | `message` | `string` | | | The message's id. | | `turn` | `number` | | | The turn the message arrived on. | | `day` | `number` | | | The day the message arrived, the calendar's day or the turn in a game without the calendar. | ### Channel [#channel] Type. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#channel). A channel the game declares in `data.messages.channels`, such as texts, email or the doormat. ```ts shape import type { Channel } from '@ifloom/plugin-messages' type Channel = { id: string name: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The channel's id, which a message's `channel` names. | | `name` | `string` | | | The channel's name. | ### channelsOf [#channelsof] Function. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#channelsof). Returns the game's channels in order, from `data.messages.channels` in its content and packs. ```ts shape import { channelsOf } from '@ifloom/plugin-messages' function channelsOf(game: Game): Channel[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`Channel`](#channel). ### ChannelView [#channelview] Type. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#channelview). A channel as the player sees it, in `view.plugins.messages.channels`. ```ts shape import type { ChannelView } from '@ifloom/plugin-messages' type ChannelView = { id: string name: string threads: ThreadView[] unread: number read: RenderedChoice | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The channel's id. | | `name` | `string` | | | The channel's name. | | `threads` | [`ThreadView[]`](#threadview) | | | The channel's threads, the one with the latest arrival first. | | `unread` | `number` | | | The number of the channel's messages the player hasn't read. | | `read` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that marks the whole channel read, labelled with the `messages/allRead` string (`Mark all read`), or null while nothing in it is unread. | ### MessageDef [#messagedef] Type. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#messagedef). A message the game declares in `data.messages.messages`. It arrives once by its `when`, or each time `messages/draw` draws it from a pool. ```ts shape import type { MessageDef } from '@ifloom/plugin-messages' type MessageDef = { id: string channel: string from: string thread?: string when?: Condition drawnFrom?: string[] weight?: number body: Block[] replies?: ReplyDef[] effects?: EffectRef[] after?: { ms: number } typing?: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The message's id. | | `channel` | `string` | | | The id of the channel the message arrives in. | | `from` | `string` | | | The message's sender, a character id or any name the game's prose uses. | | `thread` | `string` | yes | | The id of the thread the message belongs in. The sender if left out. | | `when` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | yes | | The condition for the message to arrive, the first time it holds after a command. Left out, the message arrives after the first command. For a message in a pool, `messages/draw` can draw it only while this holds, and any time if left out. | | `drawnFrom` | `string[]` | yes | | The pools `messages/draw` can draw the message from. A message with pools arrives only when drawn, never by `when` alone, and arrives again each time it is drawn. | | `weight` | `number` | yes | | The message's weight in a draw, against the others that can be drawn. 1 if left out. | | `body` | [`Block[]`](https://ifloom.dev/docs/api/engine#block) | | | The message's words, a body of blocks like a scene's. | | `replies` | [`ReplyDef[]`](#replydef) | yes | | The replies the player can choose from, one per arrival. None if left out. | | `effects` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | The effects that run each time the message arrives, in the same command, after the plugin records the arrival. A trigger on `messages/arrived` runs a command later, since triggers run before the plugins deliver. | | `after` | `{ ms: number }` | yes | | The message's wait of `ms` milliseconds after the thread's previous arrival, once its `when` holds. The message arrives at once if left out. The engine's `tick` runs it down as it does a timer. One message waits at a time, and while it waits, every other message with `after` and every later message in its thread wait until it has arrived. | | `typing` | `boolean` | yes | | True when the thread shows the other side typing while the message waits. True if left out. | ### messages [#messages] Function. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#messages). The messages plugin's factory, with its helpers as properties. `messages()` returns the plugin for the game's `plugins`, and content calls helpers such as `messages.reply('hi', 'wave')`. ```ts shape import { messages } from '@ifloom/plugin-messages' function messages(): DefinedPlugin ``` Uses: [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`MessagesState`](#messagesstate), [`MessagesView`](#messagesview). | Helper | Signature | Description | |---|---|---| | `messages.reply` | `(message: string, reply: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `messages/reply` command, which sends the reply to an arrival, by the message's id or the arrival's key. | | `messages.draw` | `(pool: string):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `messages/draw` effect, which draws one message from the pool and delivers it as a new arrival. | | `messages.since` | `(message: string, range:` [`Range`](https://ifloom.dev/docs/api/engine#range)`):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `messages/since` condition, which holds while the whole days since the message last arrived fall in the range. | | `messages.read` | `(thread?: string \| { channel: string }):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `messages/read` command, which marks a thread, a channel (`{ channel }`) or every message read. | | `messages.arrived` | `(message: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `messages/arrived` condition, which holds once the message has arrived. | | `messages.replied` | `(message: string, reply?: string, range?:` [`Range`](https://ifloom.dev/docs/api/engine#range)`):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `messages/replied` condition, which holds once the player has replied to the message, with `reply` and in the range if given. | | `messages.messageRead` | `(message: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `messages/read` condition, which holds once the player has read the message's latest arrival. | ### messagesOf [#messagesof] Function. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#messagesof). Returns the game's messages, from `data.messages.messages` in its content and packs. ```ts shape import { messagesOf } from '@ifloom/plugin-messages' function messagesOf(game: Game): MessageDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`MessageDef`](#messagedef). ### MessagesState [#messagesstate] Type. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#messagesstate). The messages a save keeps for the player, their arrivals, replies and reads. The plugin reads the messages from content. ```ts shape import type { MessagesState, Arrival } from '@ifloom/plugin-messages' type MessagesState = { arrived: Arrival[] replied: Record repliedOn: Record read: Record due: { key: string; thread: string; typing: boolean } | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `arrived` | [`Arrival[]`](#arrival) | | | The arrivals so far, oldest first. | | `replied` | `Record` | | | The id of the reply sent to each arrival, by the arrival's key. | | `repliedOn` | `Record` | | | The day each reply was sent, by the arrival's key, the calendar's day or the turn without the calendar. | | `read` | `Record` | | | The arrivals the player has read, by key. | | `due` | `{ key: string; thread: string; typing: boolean } \| null` | | | The message waiting to arrive, with its id, its thread and whether the thread shows typing, or null. The plugin's timer `messages.due` runs while it waits and delivers it when it runs out. | ### MessagesView [#messagesview] Type. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#messagesview). The messages as the player sees them, in `view.plugins.messages`. ```ts shape import type { MessagesView } from '@ifloom/plugin-messages' type MessagesView = { channels: ChannelView[] unread: number waiting: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `channels` | [`ChannelView[]`](#channelview) | | | The game's channels in the order it declares them, each with its threads. | | `unread` | `number` | | | The number of unread messages in all channels. | | `waiting` | `boolean` | | | True while a message with `after` waits to arrive in any thread. | ### MessageView [#messageview] Type. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#messageview). One arrival of a message as the player sees it, in a `ThreadView`'s `messages`. ```ts shape import type { MessageView } from '@ifloom/plugin-messages' type MessageView = { id: string key: string from: string name: string text: string beats: SceneBeat[] turn: number read: boolean replies: RenderedChoice[] replied: string | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The message's id. A message that arrives twice shows twice, with one id and two keys. | | `key` | `string` | | | The arrival's key, which a UI can use as a list key (see `Arrival`). | | `from` | `string` | | | The message's sender as the message's `from` gives it, a character id or a name. | | `name` | `string` | | | The sender's name if the sender is a character, else `from` as given. | | `text` | `string` | | | The message's words with tokens filled, including any picture and video markup. | | `beats` | [`SceneBeat[]`](https://ifloom.dev/docs/api/engine#scenebeat) | | | The message's body rendered as beats, as a scene's is. The beats are its paragraphs and its pictures and videos, from markup or `{ media }` blocks, in the order written. | | `turn` | `number` | | | The turn the message arrived on. | | `read` | `boolean` | | | True once the player has read the message. | | `replies` | [`RenderedChoice[]`](https://ifloom.dev/docs/api/engine#renderedchoice) | | | The replies on offer until one is sent, each a button that sends its `command`. | | `replied` | `string \| null` | | | The label of the reply sent, or null before one is sent. | ### ReplyDef [#replydef] Type. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#replydef). A reply the game declares in a `MessageDef`'s `replies`. The player can send one reply to each arrival. ```ts shape import type { ReplyDef } from '@ifloom/plugin-messages' type ReplyDef = { id: string label?: string when?: Condition effects?: EffectRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The reply's id, unique within its message. | | `label` | `string` | yes | | The reply's label, such as "On my way", with tokens filled. The reply's id if left out. | | `when` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | yes | | The condition that must hold for the reply to be on offer. | | `effects` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | The effects of sending the reply, after the plugin records it. | ### ThreadView [#threadview] Type. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#threadview). A thread of messages as the player sees it, in a `ChannelView`'s `threads`. ```ts shape import type { ThreadView } from '@ifloom/plugin-messages' type ThreadView = { id: string name: string image: string | null portrait: string | null messages: MessageView[] unread: number read: RenderedChoice | null typing: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The thread's id, its `thread` or its sender. | | `name` | `string` | | | The thread's name, the sender's name for a character or the id as given. | | `image` | `string \| null` | | | The path of the sender's picture, their entity's `image` through `artSrc`, or null for a sender who is only a name. | | `portrait` | `string \| null` | | | The path of the sender's face for an avatar, a character's `portrait` with the cast plugin, else their `image`. | | `messages` | [`MessageView[]`](#messageview) | | | The thread's messages, oldest first. | | `unread` | `number` | | | The number of the thread's messages the player hasn't read. | | `read` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that marks the thread read, labelled with the `messages/markRead` string (`Mark read`), or null while nothing in it is unread. | | `typing` | `boolean` | | | True while a message with `after` waits to arrive in this thread and its `typing` isn't false. | ## @ifloom/plugin-messages/react [#ifloomplugin-messagesreact] - Functions: [`useMessages`](#usemessages) - Constants: [`MESSAGES_WORDS`](#messages_words), [`MessagesSection`](#messagessection), [`messagesUi`](#messagesui) - Types: [`MessagesControls`](#messagescontrols) ### MESSAGES_WORDS [#messages_words] Const. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#messages_words). The messages plugin's UI words, in English. A game rewords any of them with `ui.` in its strings. ```ts shape import { MESSAGES_WORDS } from '@ifloom/plugin-messages/react' const MESSAGES_WORDS: { noMessages: 'No messages yet.' typing: '{name} is typing' typingShort: 'typing…' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `noMessages` | `'No messages yet.'` | | | The line a section shows while it has no conversations. | | `typing` | `'{name} is typing'` | | | The label screen readers read for a typing bubble, with the sender's `{name}`. | | `typingShort` | `'typing…'` | | | The last line a conversation shows while its next message is on its way. | ### MessagesControls [#messagescontrols] Type. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#messagescontrols). The messages plugin's view with a function that sends its read command, as `useMessages` returns it. Each reply is a `RenderedChoice` whose `command` sends it. ```ts shape import type { MessagesControls } from '@ifloom/plugin-messages/react' type MessagesControls = { channels: ChannelView[] unread: number waiting: boolean read: (channel: string) => Result } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `channels` | [`ChannelView[]`](#channelview) | | | The game's channels in the order it declares them, each with its threads. | | `unread` | `number` | | | The number of unread messages in all channels. | | `waiting` | `boolean` | | | True while a message with `after` waits to arrive in any thread. | | `read` | `(channel: string) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends `messages/read`, which marks the channel's messages read. | ### MessagesSection [#messagessection] Const. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#messagessection). Renders one messages channel from `view.plugins.messages.channels` as a device's app section, in the style of a phone. It shows the list of threads first, and opening a thread shows its messages and marks it read. Each thread in the list (`conversations`) is a `conversation` button with the sender's portrait, name, last line and an unread dot, under a button that marks the channel read. An empty channel shows the `messages-empty` line. An open thread has a back button (`thread-back`), its messages, the reply sent, the replies on offer, and a typing bubble while a message with `after` waits. Each message is a `bubble` part with `data-from="them"` or `data-from="player"`, and the typing bubble also has `data-typing`. A message's beats render through `Beat`, so its pictures and videos show as they do in a scene. ```ts shape import { MessagesSection } from '@ifloom/plugin-messages/react' const MessagesSection: ComponentType ``` Uses: [`SectionProps`](https://ifloom.dev/docs/api/react#sectionprops). ### messagesUi [#messagesui] Const. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#messagesui). The messages plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It renders a `MessagesSection` wherever a device's app has a `messages` section, and adds the plugin's words. ```ts shape import { messagesUi } from '@ifloom/plugin-messages/react' const messagesUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### useMessages [#usemessages] Function. Explained in [Messages](https://ifloom.dev/docs/reference/plugins/messages#usemessages). Returns the messages plugin's view and read command from the running game, or null in a game without the plugin. It re-renders when the view changes. ```ts shape import { useMessages } from '@ifloom/plugin-messages/react' function useMessages(): MessagesControls | null ``` Uses: [`MessagesControls`](#messagescontrols). # @ifloom/plugin-places (https://ifloom.dev/docs/api/plugin-places) Generated from the source of `@ifloom/plugin-places` and `@ifloom/plugin-places/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-places [#ifloomplugin-places] - Functions: [`locationOf`](#locationof), [`locationsOf`](#locationsof), [`lyingCount`](#lyingcount), [`places`](#places) - Constants: [`LOCATION`](#location) - Types: [`Arrival`](#arrival), [`ExitView`](#exitview), [`Lies`](#lies), [`LyingView`](#lyingview), [`Place`](#place), [`PlaceDef`](#placedef), [`PlacesOptions`](#placesoptions), [`PlacesState`](#placesstate), [`PlacesView`](#placesview), [`PlaceView`](#placeview) ### Arrival [#arrival] Type. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#arrival). The effects that run as the player walks into a location by an exit, in a `Place`'s `arrive`. ```ts shape import type { Arrival } from '@ifloom/plugin-places' type Arrival = { when?: Condition effects: EffectRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `when` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | yes | | The condition that must hold for the effects to run. They always run if left out. | | `effects` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | | | The effects that run on arrival. | ### ExitView [#exitview] Type. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#exitview). An exit from the location the player is at as the player sees it, in `view.plugins.places.exits`. It is a `RenderedChoice` labelled with the destination's name, so its `command` takes the exit. Its `disabled` gives the reason the exit is refused, `warning` a plugin's soft refusal and `price` the cost of going. The other fields describe the destination. ```ts shape import type { ExitView } from '@ifloom/plugin-places' type ExitView = { tags: string[] ref: EntityRef description: string | null image: string | null // … } ``` Plugins add fields of their own to it, which their pages list. | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `tags` | `string[]` | | | The choice's or action's tags, for a UI to style or filter it by. The destination's tags. | | `ref` | [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | | | The destination's entity reference, such as `'location:park'`. | | `description` | `string \| null` | | | The destination's `description`, the line under its name, or null when it has none. | | `image` | `string \| null` | | | The path of the destination's picture, its `image` through `artSrc`, or null when it has none. | ### Lies [#lies] Type. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#lies). The data of the `places/lies` trait, which starts a thing lying in a location. It's the location's id, or the full form with a condition to find it and effects. ```ts shape import type { Lies } from '@ifloom/plugin-places' type Lies = string | { at: string; count?: number; when?: Condition; onFind?: EffectRef[]; onPickUp?: EffectRef[] } ``` Uses: [`Condition`](https://ifloom.dev/docs/api/engine#condition), [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref). ### LOCATION [#location] Const. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#location). The id of the kind the plugin brings for its locations, `location`, as in `'location:park'`. The kind is unique: each location is one place. ```ts shape import { LOCATION } from '@ifloom/plugin-places' const LOCATION: 'location' ``` ### locationOf [#locationof] Function. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#locationof). Returns the `places/location` trait of a location, named by its id (`'park'`) or reference, read through the entity it was made `like`. Returns undefined for anything that isn't a location. ```ts shape import { locationOf } from '@ifloom/plugin-places' function locationOf(state: GameState, game: Game, ref: string | null | undefined): Place | undefined ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`Place`](#place). ### locationsOf [#locationsof] Function. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#locationsof). Returns the references of every location in the game now, each entity with the `places/location` trait. Those content declares come first in its order, then those made in play. ```ts shape import { locationsOf } from '@ifloom/plugin-places' function locationsOf(state: GameState, game: Game): EntityRef[] ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref). ### lyingCount [#lyingcount] Function. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#lyingcount). Returns how many of a thing lie in a location now, whether or not the player can see them. ```ts shape import { lyingCount } from '@ifloom/plugin-places' function lyingCount(state: GameState, game: Game, ref: string, at: string): number ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game). ### LyingView [#lyingview] Type. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#lyingview). A thing lying at the location the player is at as the player sees it, in `view.plugins.places.things`. ```ts shape import type { LyingView } from '@ifloom/plugin-places' type LyingView = { ref: EntityRef name: string image: string | null count: number pickUp: RenderedChoice } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `ref` | [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | | | The thing's entity reference, such as `'note:paper'`. | | `name` | `string` | | | The thing's name. | | `image` | `string \| null` | | | The path of the thing's picture through `artSrc`, or null when it has none. | | `count` | `number` | | | The number of this thing lying here. | | `pickUp` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) | | | The button that picks one up. Its `command` is the one to send. | ### Place [#place] Type. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#place). The data of the `places/location` trait, which makes an entity a location the player can be at. The location's name, `description`, `image` and `tags` are the entity's. ```ts shape import type { Place, Arrival } from '@ifloom/plugin-places' type Place = { parent?: string exits: readonly string[] picture?: PictureDef blocked?: Blocked[] body: Block[] actions?: ActionDef[] audio?: Record ui?: Ui arrive?: Arrival } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `parent` | `string` | yes | | The id of the location this one is inside, such as the building a shop is in. `places/within` follows it. | | `exits` | `readonly string[]` | | | The ids of the locations one step away. | | `picture` | [`PictureDef`](https://ifloom.dev/docs/api/engine#picturedef) | yes | | The location's layered picture with hotspots, rendered with the room. A hotspot here sends a `command`, since a location has no choices. | | `blocked` | [`Blocked[]`](https://ifloom.dev/docs/api/engine#blocked) | yes | | The reasons travel here is refused, such as a door shut for the night. With `hide`, the exit is left out of the view instead of disabled. | | `body` | [`Block[]`](https://ifloom.dev/docs/api/engine#block) | | | The location's body, the blocks the player reads here while no scene is open. | | `actions` | [`ActionDef[]`](https://ifloom.dev/docs/api/engine#actiondef) | yes | | The location's actions, offered as buttons in the room. | | `audio` | `Record` | yes | | The audio that plays while the player is here, by channel, such as `{ ambience: 'cafe.murmur' }`. Null silences a channel, and an open scene's audio and an `audio` effect's override it. | | `ui` | [`Ui`](https://ifloom.dev/docs/api/engine#ui)`<`[`SceneUi`](https://ifloom.dev/docs/api/engine#sceneui)`>` | yes | | The room's presentation hints while no scene is open, carried to `view.scene.ui` as a scene's are, such as the React UI's `{ transition: 'slide-left' }`. The engine gives them no meaning. | | `arrive` | [`Arrival`](#arrival) | yes | | The effects that run after the player walks in by an exit, such as someone catching them on the way in. A `places/move` doesn't run them. | ### PlaceDef [#placedef] Type. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#placedef). A location the game declares in `entities` with `places.location()`. It has an entity's fields and the `places/location` trait's side by side, and its `ui` is the trait's room hints. ```ts shape import type { PlaceDef, Arrival } from '@ifloom/plugin-places' type PlaceDef = { parent?: string exits: readonly string[] picture?: PictureDef blocked?: Blocked[] body: Block[] actions?: ActionDef[] audio?: Record ui?: Ui arrive?: Arrival of?: string // … } ``` Plugins add fields of their own to it, which their pages list. | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `parent` | `string` | yes | | The id of the location this one is inside, such as the building a shop is in. `places/within` follows it. | | `exits` | `readonly string[]` | | | The ids of the locations one step away. | | `picture` | [`PictureDef`](https://ifloom.dev/docs/api/engine#picturedef) | yes | | The location's layered picture with hotspots, rendered with the room. A hotspot here sends a `command`, since a location has no choices. | | `blocked` | [`Blocked[]`](https://ifloom.dev/docs/api/engine#blocked) | yes | | The reasons travel here is refused, such as a door shut for the night. With `hide`, the exit is left out of the view instead of disabled. | | `body` | [`Block[]`](https://ifloom.dev/docs/api/engine#block) | | | The location's body, the blocks the player reads here while no scene is open. | | `actions` | [`ActionDef[]`](https://ifloom.dev/docs/api/engine#actiondef) | yes | | The location's actions, offered as buttons in the room. | | `audio` | `Record` | yes | | The audio that plays while the player is here, by channel, such as `{ ambience: 'cafe.murmur' }`. Null silences a channel, and an open scene's audio and an `audio` effect's override it. | | `ui` | [`Ui`](https://ifloom.dev/docs/api/engine#ui)`<`[`SceneUi`](https://ifloom.dev/docs/api/engine#sceneui)`>` | yes | | The room's presentation hints while no scene is open, carried to `view.scene.ui` as a scene's are, such as the React UI's `{ transition: 'slide-left' }`. The engine gives them no meaning. | | `arrive` | [`Arrival`](#arrival) | yes | | The effects that run after the player walks in by an exit, such as someone catching them on the way in. A `places/move` doesn't run them. | | `of` | `string` | yes | | The location's kind. The plugin's own kind, `location`, if left out. | ### places [#places] Function. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#places). The places plugin's factory, with its helpers as properties. `places(options)` returns the plugin for the game's `plugins`, and content calls helpers such as `places.location({ ... })`, `places.go('park')` and `places.at('cafe')`. ```ts shape import { places } from '@ifloom/plugin-places' function places(options?: PlacesOptions): DefinedPlugin ``` Uses: [`PlacesOptions`](#placesoptions), [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`PlacesState`](#placesstate), [`PlacesView`](#placesview). | Helper | Signature | Description | |---|---|---| | `places.location` | `(def:` [`PlaceDef`](#placedef)`):` [`EntityDef`](https://ifloom.dev/docs/api/engine#entitydef) | Returns a location for content's `entities`, an entity with the `places/location` trait, from the entity's fields and the trait's. | | `places.locationRef` | `(id: string):` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | Returns the entity reference of a location; a bare id is one of the `location` kind. | | `places.lies` | `(at: string, more?: Omit, 'at'>): { 'places/lies':` [`Lies`](#lies) `}` | Returns the `places/lies` trait, to spread into an entity's `traits`, naming where it starts lying and any `when` to find it. | | `places.put` | `(entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, options?: { at?: string; by?: number }):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `places/put` effect, which puts a thing down where the player is, or `at` a location. | | `places.pickUp` | `(ref:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `places/pickUp` command, which picks up one of a thing lying where the player is. | | `places.go` | `(id: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `places/go` command, which walks to a location by an exit. | | `places.at` | `(...places: string[]):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `places/at` condition, which holds while the player is at any of these locations. | | `places.within` | `(...places: string[]):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `places/within` condition, which holds while the player is at any of these locations or anywhere inside one. | | `places.away` | `(...places: string[]):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `places/away` condition, which holds while the player is at none of these locations or at no location. | | `places.move` | `(place: string):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `places/move` effect, which puts the player at the location at once, closing any scene. | | `places.onlyAt` | `(places: string[], reason?:` [`Reason`](https://ifloom.dev/docs/api/engine#reason)`, options?: { hide?: boolean }):` [`Blocked`](https://ifloom.dev/docs/api/engine#blocked) | Returns a `blocked` entry that refuses anywhere but these locations, with `reason` or the `places/notHere` string. | | `places.where` | `(state:` [`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`, game:` [`Game`](https://ifloom.dev/docs/api/engine#game)`): string \| null` | Returns the id of the location the player is at, from the `places/here` query, or null. | ### PlacesOptions [#placesoptions] Type. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#placesoptions). Settings for `places()`. ```ts shape import type { PlacesOptions } from '@ifloom/plugin-places' type PlacesOptions = { start?: string onPickUp?: EffectRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `start` | `string` | yes | | The id of the location a new game starts at. The player is at no location if left out. | | `onPickUp` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | The effects that run each time the player picks anything up, after the thing's own `onPickUp`, with `'$'` as the thing. | ### PlacesState [#placesstate] Type. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#placesstate). The location a save keeps for the player. The plugin reads the locations from content. ```ts shape import type { PlacesState } from '@ifloom/plugin-places' type PlacesState = { at: string | null floor: Record> found: string[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `at` | `string \| null` | | | The id of the location the player is at, its full reference for a location of another kind, or null when at none. | | `floor` | `Record>` | | | The counts of things lying in each location that play changed, by location id and then thing. A count stays once written, 0 included. For a count play hasn't changed, the plugin reads the thing's `places/lies`. | | `found` | `string[]` | | | The things with a `when` the player has found, by reference. | ### PlacesView [#placesview] Type. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#placesview). The player's location, its exits and the things lying there as the player sees them, in `view.plugins.places`. ```ts shape import type { PlacesView } from '@ifloom/plugin-places' type PlacesView = { location: PlaceView | null exits: ExitView[] things: LyingView[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `location` | [`PlaceView`](#placeview) `\| null` | | | The location the player is at, or null when at none. | | `exits` | [`ExitView[]`](#exitview) | | | The location's exits in the order it lists them. It is empty while a scene is open or a lock holds everything. | | `things` | [`LyingView[]`](#lyingview) | | | The things lying in the location that the player can see, such as a thing they dropped. It is empty while a scene is open or a lock holds everything. | ### PlaceView [#placeview] Type. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#placeview). The location the player is at as the player sees it, in `view.plugins.places.location`. ```ts shape import type { PlaceView } from '@ifloom/plugin-places' type PlaceView = { id: string ref: EntityRef name: string description: string | null tags: string[] image: string | null picture: PictureView | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The location's id, as `places.go` names it. | | `ref` | [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | | | The location's entity reference, such as `'location:park'`. | | `name` | `string` | | | The location's name. | | `description` | `string \| null` | | | The location's `description`, the line under its name, or null when it has none. | | `tags` | `string[]` | | | The location's tags, which a UI can style it by. | | `image` | `string \| null` | | | The path of the location's picture, its `image` through `artSrc`, or null when it has none. | | `picture` | [`PictureView`](https://ifloom.dev/docs/api/engine#pictureview) `\| null` | | | The location's layered picture, rendered by the engine's `pictureView`, or null when it has none. Its hotspots are left out while a scene is open or a lock holds everything, as the exits are. | ## @ifloom/plugin-places/react [#ifloomplugin-placesreact] - Functions: [`usePlaces`](#useplaces) - Constants: [`Exits`](#exits), [`LocationCard`](#locationcard), [`placesUi`](#placesui) - Types: [`PlacesControls`](#placescontrols) ### Exits [#exits] Const. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#exits). Renders the exits from `view.plugins.places.exits`, each a button that is disabled with its reason when refused. It renders nothing without the places plugin, and a preset can style the parts `exits` and `exit`. ```ts shape import { Exits } from '@ifloom/plugin-places/react' const Exits: ComponentType<{ className?: string; }> ``` ### LocationCard [#locationcard] Const. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#locationcard). Renders the player's location from `view.plugins.places.location`, its name and `description` under its layered picture, with the things lying there and a button to pick each up. `Exits` renders the exits. A preset can style the parts `location`, `location-name`, `location-text`, `location-things`, `location-thing`, `location-thing-name` and `location-thing-pick`. ```ts shape import { LocationCard } from '@ifloom/plugin-places/react' const LocationCard: ComponentType ``` ### PlacesControls [#placescontrols] Type. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#placescontrols). The places plugin's view with functions that take an exit and pick up a thing, as `usePlaces` returns it. ```ts shape import type { PlacesControls } from '@ifloom/plugin-places/react' type PlacesControls = { location: PlaceView | null exits: ExitView[] things: LyingView[] go: (exit: string) => Result pickUp: (thing: EntityRef) => Result } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `location` | [`PlaceView`](#placeview) `\| null` | | | The location the player is at, or null when at none. | | `exits` | [`ExitView[]`](#exitview) | | | The location's exits in the order it lists them. It is empty while a scene is open or a lock holds everything. | | `things` | [`LyingView[]`](#lyingview) | | | The things lying in the location that the player can see, such as a thing they dropped. It is empty while a scene is open or a lock holds everything. | | `go` | `(exit: string) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends the command of the exit to the location with this id. The engine refuses it, as any command, when the exit is disabled or missing. | | `pickUp` | `(thing:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends the `pickUp` command for one of the thing lying here with this reference, such as `'note:paper'`. | ### placesUi [#placesui] Const. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#placesui). The places plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It renders the `LocationCard` and the `Exits` in the room, before the room's actions. ```ts shape import { placesUi } from '@ifloom/plugin-places/react' const placesUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### usePlaces [#useplaces] Function. Explained in [Places](https://ifloom.dev/docs/reference/plugins/places#useplaces). Returns the places plugin's view and commands from the running game, or null in a game without the plugin. It re-renders when the view changes. ```ts shape import { usePlaces } from '@ifloom/plugin-places/react' function usePlaces(): PlacesControls | null ``` Uses: [`PlacesControls`](#placescontrols). # @ifloom/plugin-quests (https://ifloom.dev/docs/api/plugin-quests) Generated from the source of `@ifloom/plugin-quests` and `@ifloom/plugin-quests/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-quests [#ifloomplugin-quests] - Functions: [`advance`](#advance), [`questOf`](#questof), [`quests`](#quests), [`questsOf`](#questsof) - Types: [`QuestDef`](#questdef), [`QuestEntry`](#questentry), [`QuestsState`](#questsstate), [`QuestStage`](#queststage), [`QuestsView`](#questsview) ### advance [#advance] Function. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#advance). Returns the quests record brought up to date with the game state. It never takes progress back. ```ts shape import { advance } from '@ifloom/plugin-quests' function advance(record: QuestsState, state: GameState, game: Game): QuestsState ``` Uses: [`QuestsState`](#questsstate), [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game). ### QuestDef [#questdef] Type. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#questdef). A quest the game declares in `data.quests.quests`. It needs at least one stage. ```ts shape import type { QuestDef } from '@ifloom/plugin-quests' type QuestDef = { id: string name: string description?: string storyline?: string starts?: Condition secret?: boolean stages: QuestStage[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The quest's id. | | `name` | `string` | | | The quest's name, such as "Find your feet". | | `description` | `string` | yes | | The quest's line or two for the quest list. | | `storyline` | `string` | yes | | The id of the storyline the quest belongs to, for a UI that groups quests by storyline. | | `starts` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | yes | | The condition that starts the quest the first time it holds. Without it, only the `quests/start` effect starts the quest. | | `secret` | `boolean` | yes | | True to leave the quest out of the count of quests to find until it starts. | | `stages` | [`QuestStage[]`](#queststage) | | | The quest's stages, in order. The quest is done when the last stage is. | ### QuestEntry [#questentry] Type. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#questentry). A started quest as the player sees it, in `view.plugins.quests.active` and `done`. ```ts shape import type { QuestEntry } from '@ifloom/plugin-quests' type QuestEntry = { id: string name: string description: string storyline: string | null hint: string stage: number stages: number startedOn: number doneOn: number | null tracked: boolean updated: boolean track: RenderedChoice | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The quest's id. | | `name` | `string` | | | The quest's name. | | `description` | `string` | | | The quest's description, or `''` when it has none. | | `storyline` | `string \| null` | | | The id of the quest's storyline, for a UI that groups quests by storyline, or null. | | `hint` | `string` | | | The hint for the stage the player is on, or `''` once the quest is done. | | `stage` | `number` | | | The number of the quest's stages done. | | `stages` | `number` | | | The number of the quest's stages. | | `startedOn` | `number` | | | The turn the quest started on. | | `doneOn` | `number \| null` | | | The turn the quest was done on, or null while it isn't. | | `tracked` | `boolean` | | | True when the player tracks this quest. | | `updated` | `boolean` | | | True when the quest has started or moved on since the player last looked. | | `track` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that tracks the quest, or stops tracking it once tracked, or null once the quest is done. Its label is the `quests/track` or `quests/untrack` string. | ### questOf [#questof] Function. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#questof). Returns the quest with this id, or undefined when the game has none. ```ts shape import { questOf } from '@ifloom/plugin-quests' function questOf(game: Game, id: string): QuestDef | undefined ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`QuestDef`](#questdef). ### quests [#quests] Function. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#quests). The quests plugin's factory, with its helpers as properties. `quests()` returns the plugin for the game's `plugins`, and content calls helpers such as `quests.done('bread')`. ```ts shape import { quests } from '@ifloom/plugin-quests' function quests(): DefinedPlugin ``` Uses: [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`QuestsState`](#questsstate), [`QuestsView`](#questsview). | Helper | Signature | Description | |---|---|---| | `quests.active` | `(quest: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `quests/active` condition, which holds while the quest is started and not finished. | | `quests.done` | `(quest: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `quests/done` condition, which holds once the quest is finished. | | `quests.reached` | `(quest: string, stage: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `quests/reached` condition, which holds once this stage of the quest is done. | | `quests.start` | `(quest: string):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `quests/start` effect, which starts the quest now if it hasn't started. | | `quests.track` | `(quest?: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `quests/track` command, which tracks the quest, or stops tracking with no argument. | | `quests.seen` | `(quest?: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `quests/seen` command, which marks the quest's news seen, or every quest's with no argument. | ### questsOf [#questsof] Function. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#questsof). Returns the game's quests, from `data.quests.quests` in its content and packs. ```ts shape import { questsOf } from '@ifloom/plugin-quests' function questsOf(game: Game): QuestDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`QuestDef`](#questdef). ### QuestsState [#questsstate] Type. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#questsstate). The quests a save keeps for the player, their progress, tracking and news. The plugin reads the quests from content. ```ts shape import type { QuestsState } from '@ifloom/plugin-quests' type QuestsState = { started: Record reached: Record done: Record tracked: string | null seen: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `started` | `Record` | | | The turn each started quest started on, by quest id. | | `reached` | `Record` | | | The number of stages done in each started quest, by quest id. | | `done` | `Record` | | | The turn each finished quest finished on, by quest id. | | `tracked` | `string \| null` | | | The id of the quest the player tracks, or null. | | `seen` | `Record` | | | Each quest's progress when the player last looked at it, by quest id. It counts the stages done, plus one once the quest is finished. | ### QuestStage [#queststage] Type. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#queststage). A stage the game declares in a `QuestDef`'s `stages`. The stage is done the first time its `done` holds after the stages before it. ```ts shape import type { QuestStage } from '@ifloom/plugin-quests' type QuestStage = { id: string hint: string done: Condition } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The stage's id, unique within its quest. | | `hint` | `string` | | | The stage's hint, which the player reads while on this stage. | | `done` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | | | The condition that marks the stage done, the first time it holds once the stages before it are done. | ### QuestsView [#questsview] Type. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#questsview). The quests as the player sees them, in `view.plugins.quests`. ```ts shape import type { QuestsView } from '@ifloom/plugin-quests' type QuestsView = { active: QuestEntry[] done: QuestEntry[] toFind: number updates: number seen: RenderedChoice | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `active` | [`QuestEntry[]`](#questentry) | | | The quests started and not finished, the tracked one first and then the newest first. | | `done` | [`QuestEntry[]`](#questentry) | | | The finished quests, the most recent first. | | `toFind` | `number` | | | The number of quests not started yet, secret ones left out. | | `updates` | `number` | | | The number of quests with news the player hasn't looked at, for a badge. | | `seen` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that marks every quest's news seen, labelled with the `quests/allSeen` string (`Mark all seen`), or null while there is none. | ## @ifloom/plugin-quests/react [#ifloomplugin-questsreact] - Components: [`QuestsSection`](#questssection) - Functions: [`useQuests`](#usequests) - Constants: [`QuestLog`](#questlog), [`QUESTS_WORDS`](#quests_words), [`questsUi`](#questsui) - Types: [`QuestsControls`](#questscontrols) ### QuestLog [#questlog] Const. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#questlog). Renders the quest log from `view.plugins.quests`, the active quests with their hints and track buttons, then the finished ones. `title` sets the heading, such as "Journal", and `title={false}` leaves it off. A preset can style the parts `quests`, `quests-title`, `quest`, `quest-title`, `quest-summary`, `quest-hint`, `quest-stage`, `quests-done` and `quest-done`. ```ts shape import { QuestLog } from '@ifloom/plugin-quests/react' const QuestLog: ComponentType<{ className?: string; title?: string | false; }> ``` ### QUESTS_WORDS [#quests_words] Const. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#quests_words). The quests plugin's UI words, in English. A game rewords any of them with `ui.` in its strings. ```ts shape import { QUESTS_WORDS } from '@ifloom/plugin-quests/react' const QUESTS_WORDS: { questNew: 'New' questStage: '{stage} of {stages}' quests: 'Quests' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `questNew` | `'New'` | | | The badge on a quest that has changed since the player last looked. | | `questStage` | `'{stage} of {stages}'` | | | The count of a quest's stages done, with `{stage}` and `{stages}`. | | `quests` | `'Quests'` | | | The title of the quest log and its section. | ### QuestsControls [#questscontrols] Type. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#questscontrols). The quests plugin's view with a function that tracks any quest, as `useQuests` returns it. ```ts shape import type { QuestsControls } from '@ifloom/plugin-quests/react' type QuestsControls = { active: QuestEntry[] done: QuestEntry[] toFind: number updates: number seen: RenderedChoice | null track: (id: string | null) => Result } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `active` | [`QuestEntry[]`](#questentry) | | | The quests started and not finished, the tracked one first and then the newest first. | | `done` | [`QuestEntry[]`](#questentry) | | | The finished quests, the most recent first. | | `toFind` | `number` | | | The number of quests not started yet, secret ones left out. | | `updates` | `number` | | | The number of quests with news the player hasn't looked at, for a badge. | | `seen` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that marks every quest's news seen, labelled with the `quests/allSeen` string (`Mark all seen`), or null while there is none. | | `track` | `(id: string \| null) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends `quests/track` for the quest with this id, or stops tracking with `null`. Each quest's `track` button does the same for that quest. | ### QuestsSection [#questssection] Component. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#questssection). Renders the default layout's Quests section, a button with the count of news from `view.plugins.quests.updates` that opens the `QuestLog` in a dialog. ```ts shape import { QuestsSection } from '@ifloom/plugin-quests/react' function QuestsSection(): JSX.Element ``` ### questsUi [#questsui] Const. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#questsui). The quests plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It adds the `QuestsSection` to the sidebar, renders the `quests` panel as a `QuestLog`, and adds the plugin's words. ```ts shape import { questsUi } from '@ifloom/plugin-quests/react' const questsUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### useQuests [#usequests] Function. Explained in [Quests](https://ifloom.dev/docs/reference/plugins/quests#usequests). Returns the quests plugin's view and track command from the running game, or null in a game without the plugin. It re-renders when the view changes. ```ts shape import { useQuests } from '@ifloom/plugin-quests/react' function useQuests(): QuestsControls | null ``` Uses: [`QuestsControls`](#questscontrols). # @ifloom/plugin-shop (https://ifloom.dev/docs/api/plugin-shop) Generated from the source of `@ifloom/plugin-shop` and `@ifloom/plugin-shop/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-shop [#ifloomplugin-shop] - Functions: [`sellableOf`](#sellableof), [`shop`](#shop), [`vendorOf`](#vendorof), [`vendorsOf`](#vendorsof) - Types: [`DiscountDef`](#discountdef), [`GoodDef`](#gooddef), [`GoodView`](#goodview), [`Restock`](#restock), [`Sellable`](#sellable), [`ShopOptions`](#shopoptions), [`ShopState`](#shopstate), [`ShopView`](#shopview), [`Stock`](#stock), [`StockRecord`](#stockrecord), [`Vendor`](#vendor), [`VendorDef`](#vendordef), [`VendorView`](#vendorview) ### DiscountDef [#discountdef] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#discountdef). A vendor's daily discounts, which the game declares in its `discounts`. The vendor marks `count` goods down each day, drawn from the save's seed. ```ts shape import type { DiscountDef } from '@ifloom/plugin-shop' type DiscountDef = { off: number count?: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `off` | `number` | | | The fraction off, such as `0.25` for a quarter. | | `count` | `number` | yes | | The number of goods marked down each day. 1 if left out. | ### GoodDef [#gooddef] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#gooddef). A good the game declares in a vendor's `goods`, a thing the vendor sells with its price and stock. ```ts shape import type { GoodDef } from '@ifloom/plugin-shop' type GoodDef = { entity: EntityRef price?: Record stock?: Stock restock?: Restock when?: Condition deliver?: false | string onBuy?: EffectRef[] onSell?: EffectRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `entity` | [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | | | The reference of the thing sold, such as `'food:apple'`. A game that keeps things in kv keys declares a light entity, a name and no traits. | | `price` | `Record` | yes | | The price of one, by stat, such as `{ coins: 4 }`, each stat spendable. The thing's `shop/sellable` price if left out. | | `stock` | [`Stock`](#stock) | yes | | The number the vendor has, which `restock` tops back up to, or `'unlimited'`, or `'once'` for one sale only. `'once'` suits upgrades and unique things. `'unlimited'` if left out, or `'once'` for a unique thing. | | `restock` | [`Restock`](#restock) | yes | | The interval a number `stock` is topped back up at. Never if left out. | | `when` | [`Condition`](https://ifloom.dev/docs/api/engine#condition) | yes | | The condition that must hold for the good to be on offer. | | `deliver` | `false \| string` | yes | | The plugin a purchase goes to, or `false` to give nothing, so the purchase is only its `onBuy`, such as a kv flag. A plugin's id gives it to that plugin's receiver, as a `receive`'s `via` does. To whichever plugin that keeps things claims it first if left out. | | `onBuy` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | Effects that run for each one bought, after it's given, with `'$'` as the thing, such as `[{ kv: 'kitchen.coffeeMachine', to: true }]`. | | `onSell` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | Effects that run for each one sold back, after it's taken, with `'$'` as the thing. | ### GoodView [#goodview] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#goodview). A good as the player sees it, in a `VendorView`'s `goods`. ```ts shape import type { GoodView } from '@ifloom/plugin-shop' type GoodView = { entity: EntityRef name: string description: string | null image: string | null stock: number | null owned: number off: number fullPrice: Price | null buy: RenderedChoice sell: RenderedChoice | null sellFor: Price | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `entity` | [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | | | The reference of the thing sold, such as `'food:apple'`. | | `name` | `string` | | | The thing's name. | | `description` | `string \| null` | | | The thing's description, or null when it has none. | | `image` | `string \| null` | | | The path of the thing's picture through `artSrc`, or null when it has none. | | `stock` | `number \| null` | | | The number the vendor has left, or null when the good never runs out. | | `owned` | `number` | | | The number of this thing the player owns, across the plugins that keep things. | | `off` | `number` | | | The fraction off today, or 0. | | `fullPrice` | [`Price`](https://ifloom.dev/docs/api/engine#price) `\| null` | | | The price before today's discount, or null when there is no discount. | | `buy` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) | | | The button that buys one, with its price and any reason it's disabled. Its `command` is the one to send. | | `sell` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that sells one back, or null when the vendor buys nothing back. | | `sellFor` | [`Price`](https://ifloom.dev/docs/api/engine#price) `\| null` | | | The price the vendor pays to buy one back, or null when it buys nothing back. | ### Restock [#restock] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#restock). The interval a good's stock is topped up at, every turn or every calendar day. `'day'` means every turn in a game without the calendar. ```ts shape import type { Restock } from '@ifloom/plugin-shop' type Restock = 'turn' | 'day' ``` ### Sellable [#sellable] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#sellable). The data of the `shop/sellable` trait, a thing's price wherever a vendor sells it without a price of its own. ```ts shape import type { Sellable } from '@ifloom/plugin-shop' type Sellable = { price: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `price` | `Record` | | | The price of one, by stat, such as `{ coins: 4 }`. A good's own `price` overrides it. | ### sellableOf [#sellableof] Function. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#sellableof). Returns a thing's `shop/sellable` trait, its price where a good gives none. Returns undefined for a thing without the trait. ```ts shape import { sellableOf } from '@ifloom/plugin-shop' function sellableOf(state: GameState, game: Game, ref: EntityRef): Sellable | undefined ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref), [`Sellable`](#sellable). ### shop [#shop] Function. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#shop). The shop plugin's factory, with its helpers as properties. `shop()` returns the plugin for the game's `plugins`, and content calls helpers such as `shop.vendor({ ... })` and `shop.buy('counter', 'food:bun')`. ```ts shape import { shop } from '@ifloom/plugin-shop' function shop(options?: ShopOptions): DefinedPlugin ``` Uses: [`ShopOptions`](#shopoptions), [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`ShopState`](#shopstate), [`ShopView`](#shopview). | Helper | Signature | Description | |---|---|---| | `shop.vendor` | `(def:` [`VendorDef`](#vendordef)`):` [`EntityDef`](https://ifloom.dev/docs/api/engine#entitydef) | Returns a vendor for content's `entities`, an entity with the `shop/vendor` trait, from the entity's fields and the trait's. | | `shop.vendorRef` | `(vendor: string):` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | Returns the entity reference of a vendor; a bare id is one of the `vendor` kind. | | `shop.sellable` | `(price: Record): { 'shop/sellable':` [`Sellable`](#sellable) `}` | Returns the `shop/sellable` trait, to spread into an entity's or a kind's `traits`. | | `shop.buy` | `(vendor: string, entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, count?: number):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `shop/buy` command, which buys `count` of a thing from a vendor, 1 if left out. | | `shop.sell` | `(vendor: string, entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, count?: number):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `shop/sell` command, which sells `count` of a thing back to a vendor, 1 if left out. | | `shop.open` | `(vendor: string):` [`Effect`](https://ifloom.dev/docs/api/engine#effect) | Returns the effect that opens the vendor's counter in the `shop` panel. | | `shop.vendorOpen` | `(vendor: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `shop/open` condition, which holds while the vendor is open, wherever the player is. | | `shop.inStock` | `(vendor: string, entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `shop/inStock` condition, which holds while the vendor offers the thing and has one left. | | `shop.outside` | `(...periods: string[]):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `shop/outside` condition, which holds while the calendar's period is none of these. | | `shop.hours` | `(periods: readonly string[], reason?:` [`Reason`](https://ifloom.dev/docs/api/engine#reason)`):` [`Blocked`](https://ifloom.dev/docs/api/engine#blocked) | Returns a `blocked` entry for a vendor's opening hours, which closes it outside these calendar periods. | ### ShopOptions [#shopoptions] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#shopoptions). The shop plugin's settings, which the game passes to `shop()`. ```ts shape import type { ShopOptions } from '@ifloom/plugin-shop' type ShopOptions = { onBuy?: EffectRef[] onSell?: EffectRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `onBuy` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | Effects that run for each one of anything bought from any vendor, after the good's and the vendor's, with `'$'` as the thing. | | `onSell` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | Effects that run for each one of anything sold back to any vendor, after the good's and the vendor's, with `'$'` as the thing. | ### ShopState [#shopstate] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#shopstate). The stock a save keeps for the vendors, only the goods play changed. The plugin reads the goods from content. ```ts shape import type { ShopState } from '@ifloom/plugin-shop' type ShopState = { stock: Record> } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `stock` | `Record>` | | | The number of each limited good each vendor has left, by vendor and then by thing. | ### ShopView [#shopview] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#shopview). The vendors as the player sees them, in `view.plugins.shop`. ```ts shape import type { ShopView } from '@ifloom/plugin-shop' type ShopView = { vendors: VendorView[] panel: VendorView | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `vendors` | [`VendorView[]`](#vendorview) | | | The game's vendors, in the order the game declares them. | | `panel` | [`VendorView`](#vendorview) `\| null` | | | The vendor the open `shop` panel shows, named by its `with.vendor`, or null while no `shop` panel is open. A UI renders it in the panel as it is. | ### Stock [#stock] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#stock). The number of a good a vendor has, which `restock` tops back up, or `'unlimited'`, or `'once'` for a single sale. ```ts shape import type { Stock } from '@ifloom/plugin-shop' type Stock = number | 'unlimited' | 'once' ``` ### StockRecord [#stockrecord] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#stockrecord). The record a save keeps of one good's stock once play changed it, in `ShopState`'s `stock`. ```ts shape import type { StockRecord } from '@ifloom/plugin-shop' type StockRecord = { left: number at: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `left` | `number` | | | The number the vendor had left then. | | `at` | `number` | | | The turn or day it was written on, which a `restock` compares with now, or 0 for a good that never restocks. | ### Vendor [#vendor] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#vendor). The data of the `shop/vendor` trait, which makes an entity a vendor the player buys from. The vendor's name, such as "The counter", is the entity's. ```ts shape import type { Vendor } from '@ifloom/plugin-shop' type Vendor = { blocked?: Blocked[] goods: GoodDef[] buysBack?: number discounts?: DiscountDef onBuy?: EffectRef[] onSell?: EffectRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `blocked` | [`Blocked[]`](https://ifloom.dev/docs/api/engine#blocked) | yes | | The reasons the vendor refuses to trade. The first entry that holds gives the reason, and the vendor is open everywhere if left out. While an entry with `hide` holds, the vendor isn't `here`, as with `places.onlyAt(['cafe'], undefined, { hide: true })`. Any other entry closes the vendor with its reason, as the opening hours `shop.hours(['morning', 'afternoon'])` writes do. | | `goods` | [`GoodDef[]`](#gooddef) | | | The vendor's goods, in the order shown. | | `buysBack` | `number` | yes | | The fraction of a good's full price the vendor pays to buy one back. It buys nothing back if left out. | | `discounts` | [`DiscountDef`](#discountdef) | yes | | The vendor's daily discounts. None if left out. | | `onBuy` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | Effects that run for each one of any good bought from the vendor, after the good's own, with `'$'` as the thing. | | `onSell` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | Effects that run for each one of any good sold back to the vendor, after the good's own, with `'$'` as the thing. | ### VendorDef [#vendordef] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#vendordef). A vendor the game declares in `entities` with `shop.vendor()`. It has an entity's fields and the `shop/vendor` trait's side by side. ```ts shape import type { VendorDef } from '@ifloom/plugin-shop' type VendorDef = { blocked?: Blocked[] goods: GoodDef[] buysBack?: number discounts?: DiscountDef onBuy?: EffectRef[] onSell?: EffectRef[] of?: string // … } ``` Plugins add fields of their own to it, which their pages list. | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `blocked` | [`Blocked[]`](https://ifloom.dev/docs/api/engine#blocked) | yes | | The reasons the vendor refuses to trade. The first entry that holds gives the reason, and the vendor is open everywhere if left out. While an entry with `hide` holds, the vendor isn't `here`, as with `places.onlyAt(['cafe'], undefined, { hide: true })`. Any other entry closes the vendor with its reason, as the opening hours `shop.hours(['morning', 'afternoon'])` writes do. | | `goods` | [`GoodDef[]`](#gooddef) | | | The vendor's goods, in the order shown. | | `buysBack` | `number` | yes | | The fraction of a good's full price the vendor pays to buy one back. It buys nothing back if left out. | | `discounts` | [`DiscountDef`](#discountdef) | yes | | The vendor's daily discounts. None if left out. | | `onBuy` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | Effects that run for each one of any good bought from the vendor, after the good's own, with `'$'` as the thing. | | `onSell` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | Effects that run for each one of any good sold back to the vendor, after the good's own, with `'$'` as the thing. | | `of` | `string` | yes | | The vendor's kind. The plugin's own kind, `vendor`, if left out. | ### vendorOf [#vendorof] Function. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#vendorof). Returns the `shop/vendor` trait of a vendor, named by its id (`'counter'`) or reference, without any good that names no thing. Returns undefined for anything that isn't a vendor. ```ts shape import { vendorOf } from '@ifloom/plugin-shop' function vendorOf(state: GameState, game: Game, ref: string | null | undefined): Vendor | undefined ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`Vendor`](#vendor). ### vendorsOf [#vendorsof] Function. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#vendorsof). Returns the references of every vendor in the game now, each entity with the `shop/vendor` trait. Those content declares come first in its order, then those made in play. ```ts shape import { vendorsOf } from '@ifloom/plugin-shop' function vendorsOf(state: GameState, game: Game): EntityRef[] ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref). ### VendorView [#vendorview] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#vendorview). A vendor as the player sees it, in `view.plugins.shop.vendors`. ```ts shape import type { VendorView } from '@ifloom/plugin-shop' type VendorView = { id: string ref: EntityRef name: string here: boolean closed: string | null buysBack: boolean goods: GoodView[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The vendor's id as `shop.buy` names it, the bare id for one of the `vendor` kind, else its full reference. | | `ref` | [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | | | The vendor's entity reference, such as `'vendor:counter'`. | | `name` | `string` | | | The vendor's name. | | `here` | `boolean` | | | True while none of the vendor's `blocked` entries with `hide` holds, so the vendor is where the player is. | | `closed` | `string \| null` | | | The reason the vendor is closed, from its first `blocked` entry without `hide` that holds, or null while it's open. | | `buysBack` | `boolean` | | | True when the vendor buys things back. | | `goods` | [`GoodView[]`](#goodview) | | | The goods on offer now, in the order the vendor lists them. | ## @ifloom/plugin-shop/react [#ifloomplugin-shopreact] - Functions: [`useShop`](#useshop) - Constants: [`SHOP_WORDS`](#shop_words), [`ShopCounter`](#shopcounter), [`ShopDialog`](#shopdialog), [`shopUi`](#shopui) - Types: [`ShopControls`](#shopcontrols), [`ShopCounterProps`](#shopcounterprops), [`ShopDialogProps`](#shopdialogprops) ### SHOP_WORDS [#shop_words] Const. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#shop_words). The shop plugin's UI words, in English. A game rewords any of them with `ui.` in its strings, such as `{ 'ui.buy': 'Get' }`. ```ts shape import { SHOP_WORDS } from '@ifloom/plugin-shop/react' const SHOP_WORDS: { buy: 'Buy' sellFor: 'Sell for {price}' stockLeft: '{n} left' owned: 'You have {n}' percentOff: '{percent}% off' noGoods: 'Nothing for sale.' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `buy` | `'Buy'` | | | The label of a good's buy button. | | `sellFor` | `'Sell for {price}'` | | | The label of a good's sell button, with its `{price}`. | | `stockLeft` | `'{n} left'` | | | The count of a good the vendor has left, with `{n}`. | | `owned` | `'You have {n}'` | | | The count of a good the player holds, with `{n}`. | | `percentOff` | `'{percent}% off'` | | | The badge on a good with today's discount, with its `{percent}`. | | `noGoods` | `'Nothing for sale.'` | | | The line a vendor's counter shows while it has no goods. | ### ShopControls [#shopcontrols] Type. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#shopcontrols). The shop plugin's view with the vendors here and functions that send its commands, as `useShop` returns it. ```ts shape import type { ShopControls } from '@ifloom/plugin-shop/react' type ShopControls = { vendors: VendorView[] panel: VendorView | null here: VendorView[] buy: (vendor: string, entity: EntityRef, count?: number) => Result sell: (vendor: string, entity: EntityRef, count?: number) => Result } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `vendors` | [`VendorView[]`](#vendorview) | | | The game's vendors, in the order the game declares them. | | `panel` | [`VendorView`](#vendorview) `\| null` | | | The vendor the open `shop` panel shows, named by its `with.vendor`, or null while no `shop` panel is open. A UI renders it in the panel as it is. | | `here` | [`VendorView[]`](#vendorview) | | | The vendors whose `here` is true, for a layout of your own to show. | | `buy` | `(vendor: string, entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, count?: number) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends `shop/buy` for `count` of a thing, 1 if left out. A refusal carries the same reason the buy button shows. | | `sell` | `(vendor: string, entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, count?: number) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends `shop/sell` for `count` of a thing, 1 if left out. | ### ShopCounter [#shopcounter] Const. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#shopcounter). Renders a vendor's goods from a `VendorView`, each with its picture, name, price, stock and a buy button. A sell button shows when the vendor buys back and the player holds one. Each good also shows its description, today's discount and how many the player holds. A disabled button shows its reason, and a closed vendor shows its reason above its goods. A preset can style the parts `shop`, `shop-closed`, `shop-empty`, `goods`, `good`, `good-name`, `good-desc`, `good-image`, `good-details`, `good-off`, `good-full-price`, `good-stock`, `good-owned` and `good-actions`. ```ts shape import { ShopCounter } from '@ifloom/plugin-shop/react' const ShopCounter: ComponentType ``` Uses: [`ShopCounterProps`](#shopcounterprops). ### ShopCounterProps [#shopcounterprops] Type. Props for `ShopCounter`. ```ts shape import type { ShopCounterProps } from '@ifloom/plugin-shop/react' type ShopCounterProps = { vendor: VendorView className?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `vendor` | [`VendorView`](#vendorview) | | | The vendor to render, from `view.plugins.shop`. | | `className` | `string` | yes | | The class added to the counter's root. | ### ShopDialog [#shopdialog] Const. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#shopdialog). Renders the vendor with this id from `view.plugins.shop.vendors` as a `ShopCounter` in a dialog titled with its name. The dialog is closed while `vendorId` is null or names no vendor. ```ts shape import { ShopDialog } from '@ifloom/plugin-shop/react' const ShopDialog: ComponentType ``` Uses: [`ShopDialogProps`](#shopdialogprops). ### ShopDialogProps [#shopdialogprops] Type. Props for `ShopDialog`. ```ts shape import type { ShopDialogProps } from '@ifloom/plugin-shop/react' type ShopDialogProps = { vendorId: string | null onClose: () => void } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `vendorId` | `string \| null` | | | The id of the vendor to show, or null to keep the dialog closed. | | `onClose` | `() => void` | | | The function the dialog calls when the player closes it. | ### shopUi [#shopui] Const. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#shopui). The shop plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It renders the `shop` panel, which `shop.open(vendor)` opens, as that vendor's `ShopCounter` titled with its name, and adds the plugin's words. It adds nothing to the layout, so a counter shows only when content opens one. ```ts shape import { shopUi } from '@ifloom/plugin-shop/react' const shopUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### useShop [#useshop] Function. Explained in [Shop](https://ifloom.dev/docs/reference/plugins/shop#useshop). Returns the shop plugin's view and commands from the running game, or null in a game without the plugin. It re-renders when the view changes. ```ts shape import { useShop } from '@ifloom/plugin-shop/react' function useShop(): ShopControls | null ``` Uses: [`ShopControls`](#shopcontrols). # @ifloom/plugin-statuses (https://ifloom.dev/docs/api/plugin-statuses) Generated from the source of `@ifloom/plugin-statuses` and `@ifloom/plugin-statuses/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-statuses [#ifloomplugin-statuses] - Functions: [`statuses`](#statuses), [`statusesOf`](#statusesof), [`statusOf`](#statusof) - Types: [`ActiveRecord`](#activerecord), [`ActiveStatus`](#activestatus), [`Reapply`](#reapply), [`StatusDef`](#statusdef), [`StatusesState`](#statusesstate), [`StatusesView`](#statusesview), [`StatusModifier`](#statusmodifier) ### ActiveRecord [#activerecord] Type. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#activerecord). The record a save keeps for one active status, in `StatusesState`'s `active`. The plugin reads the status's definition from content. ```ts shape import type { ActiveRecord } from '@ifloom/plugin-statuses' type ActiveRecord = { id: string left: number[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The status's id. | | `left` | `number[]` | | | The turns left on each stack, oldest stack first. | ### ActiveStatus [#activestatus] Type. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#activestatus). An active status as the player sees it, in `view.plugins.statuses.active`. ```ts shape import type { ActiveStatus } from '@ifloom/plugin-statuses' type ActiveStatus = { id: string name: string description: string turnsLeft: number stacks: number modifiers: StatModifier[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The status's id. | | `name` | `string` | | | The status's name. | | `description` | `string` | | | The status's description, or `''` when it has none. | | `turnsLeft` | `number` | | | The turns left on the status's longest stack. | | `stacks` | `number` | | | The number of the status's stacks still running, 1 unless it stacks. | | `modifiers` | [`StatModifier[]`](https://ifloom.dev/docs/api/engine-plugin#statmodifier) | | | The status's changes to the stats now, all its stacks together, one entry per stat. | ### Reapply [#reapply] Type. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#reapply). The rule for applying a status that is already active. `'refresh'` starts its turns again, and `'stack'` adds another stack. ```ts shape import type { Reapply } from '@ifloom/plugin-statuses' type Reapply = 'refresh' | 'stack' ``` ### StatusDef [#statusdef] Type. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#statusdef). A timed status the game declares in `data.statuses.statuses`. It lasts `turns` turns from the turn it is applied in. ```ts shape import type { StatusDef } from '@ifloom/plugin-statuses' type StatusDef = { id: string name: string description?: string turns: number modifiers?: StatusModifier[] effects?: { start?: EffectRef[]; turn?: EffectRef[]; end?: EffectRef[] } reapply?: Reapply max?: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The status's id. | | `name` | `string` | | | The status's name, such as "Caffeinated". | | `description` | `string` | yes | | The status's description, a line for the UI to show. | | `turns` | `number` | | | The number of turns the status lasts, counting the end of the turn it was applied in. | | `modifiers` | [`StatusModifier[]`](#statusmodifier) | yes | | The status's changes to the player's stats while it lasts, per stack. The plugin never writes them to the stats. | | `effects` | `{ start?:` [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref)`; turn?:` [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref)`; end?:` [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) `}` | yes | | The status's effects as it runs. `start` runs as the status starts, `turn` once per stack at the end of each turn, and `end` once per stack that runs out. `start` also runs for each stack added, but not for a refresh or a stack that replaces the oldest at `max`. The `turn` effects run before the status's turns go down. | | `reapply` | [`Reapply`](#reapply) | yes | | The rule for applying the status again while it is active. `'refresh'` if left out. | | `max` | `number` | yes | | The most stacks the status can have, with `reapply: 'stack'`. A new stack past it replaces the oldest, and there is no limit if left out. | ### statuses [#statuses] Function. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#statuses). The statuses plugin's factory, with its helpers as properties. `statuses()` returns the plugin for the game's `plugins`, and content calls helpers such as `statuses.apply('caffeinated')`. ```ts shape import { statuses } from '@ifloom/plugin-statuses' function statuses(): DefinedPlugin ``` Uses: [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`StatusesState`](#statusesstate), [`StatusesView`](#statusesview). | Helper | Signature | Description | |---|---|---| | `statuses.active` | `(id: string, stacks?:` [`Range`](https://ifloom.dev/docs/api/engine#range)`):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `statuses/active` condition, which holds while the status is active, with a number of stacks in the range if given. | | `statuses.apply` | `(id: string):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `statuses/apply` effect, which starts the status, or refreshes or stacks it if it's already active. | | `statuses.remove` | `(id: string, runEnd?: boolean):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `statuses/remove` effect, which takes every stack of the status off, running its `end` effects with `runEnd`. | ### statusesOf [#statusesof] Function. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#statusesof). Returns the game's timed statuses, from `data.statuses.statuses` in its content and packs. ```ts shape import { statusesOf } from '@ifloom/plugin-statuses' function statusesOf(game: Game): StatusDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`StatusDef`](#statusdef). ### StatusesState [#statusesstate] Type. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#statusesstate). The active statuses a save keeps for the player. The plugin reads each status's definition from content. ```ts shape import type { StatusesState } from '@ifloom/plugin-statuses' type StatusesState = { active: ActiveRecord[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `active` | [`ActiveRecord[]`](#activerecord) | | | The active statuses, in the order they were first applied. | ### StatusesView [#statusesview] Type. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#statusesview). The active statuses as the player sees them, in `view.plugins.statuses`. ```ts shape import type { StatusesView } from '@ifloom/plugin-statuses' type StatusesView = { active: ActiveStatus[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `active` | [`ActiveStatus[]`](#activestatus) | | | The active statuses, in the order they were first applied. | ### StatusModifier [#statusmodifier] Type. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#statusmodifier). A change a status makes to the value one of the player's stats reads, per stack. ```ts shape import type { StatusModifier } from '@ifloom/plugin-statuses' type StatusModifier = { // … } ``` Plugins add fields of their own to it, which their pages list. ### statusOf [#statusof] Function. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#statusof). Returns the status with this id, or undefined when the game has none. ```ts shape import { statusOf } from '@ifloom/plugin-statuses' function statusOf(game: Game, id: string): StatusDef | undefined ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`StatusDef`](#statusdef). ## @ifloom/plugin-statuses/react [#ifloomplugin-statusesreact] - Functions: [`useStatuses`](#usestatuses) - Constants: [`STATUSES_WORDS`](#statuses_words), [`statusesUi`](#statusesui), [`StatusList`](#statuslist) ### STATUSES_WORDS [#statuses_words] Const. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#statuses_words). The statuses plugin's UI words, in English. A game rewords any of them with `ui.` in its strings. ```ts shape import { STATUSES_WORDS } from '@ifloom/plugin-statuses/react' const STATUSES_WORDS: { modifierAdd: '{n} {stat}' modifierMultiply: '×{n} {stat}' statusStacks: '×{n}' statuses: 'Statuses' turnLeft: '1 turn left' turnsLeft: '{n} turns left' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `modifierAdd` | `'{n} {stat}'` | | | The line for a modifier that adds to a stat, with the signed `{n}` and the `{stat}`. | | `modifierMultiply` | `'×{n} {stat}'` | | | The line for a modifier that multiplies a stat, with `{n}` and the `{stat}`. | | `statusStacks` | `'×{n}'` | | | The badge on a status with more than one stack, with `{n}`. | | `statuses` | `'Statuses'` | | | The title of the status list. | | `turnLeft` | `'1 turn left'` | | | The line on a status with one turn left. | | `turnsLeft` | `'{n} turns left'` | | | The line on a status with `{n}` turns left. | ### statusesUi [#statusesui] Const. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#statusesui). The statuses plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It renders the `StatusList` under the stats in the sidebar and as the `statuses` panel, and adds the plugin's words. ```ts shape import { statusesUi } from '@ifloom/plugin-statuses/react' const statusesUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### StatusList [#statuslist] Const. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#statuslist). Renders the active statuses from `view.plugins.statuses.active`, each with its name, stacks, turns left, description and changes to the stats. It renders nothing while no status is active or without the plugin. A preset can style the parts `statuses`, `statuses-title`, `status`, `status-label`, `status-stacks`, `status-turns`, `status-summary` and `status-modifiers`. ```ts shape import { StatusList } from '@ifloom/plugin-statuses/react' const StatusList: ComponentType<{ className?: string; title?: string | false; }> ``` ### useStatuses [#usestatuses] Function. Explained in [Statuses](https://ifloom.dev/docs/reference/plugins/statuses#usestatuses). Returns the statuses plugin's view from the running game, or null in a game without the plugin. It re-renders when the view changes. ```ts shape import { useStatuses } from '@ifloom/plugin-statuses/react' function useStatuses(): StatusesView | null ``` Uses: [`StatusesView`](#statusesview). # @ifloom/plugin-unlocks (https://ifloom.dev/docs/api/plugin-unlocks) Generated from the source of `@ifloom/plugin-unlocks` and `@ifloom/plugin-unlocks/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-unlocks [#ifloomplugin-unlocks] - Functions: [`cheatOf`](#cheatof), [`cheatsOf`](#cheatsof), [`codeFits`](#codefits), [`contentScript`](#contentscript), [`enterCode`](#entercode), [`envName`](#envname), [`lockContent`](#lockcontent), [`lockedContent`](#lockedcontent-1), [`normaliseCode`](#normalisecode), [`startUnlocks`](#startunlocks), [`unlockedPacks`](#unlockedpacks), [`unlockHash`](#unlockhash), [`unlocks`](#unlocks), [`unlocksOf`](#unlocksof) - Constants: [`ITERATIONS`](#iterations) - Types: [`CheatDef`](#cheatdef), [`CheatUse`](#cheatuse), [`CheatView`](#cheatview), [`Entered`](#entered), [`LockedContent`](#lockedcontent), [`UnlockDef`](#unlockdef), [`UnlocksProfile`](#unlocksprofile), [`UnlocksState`](#unlocksstate), [`UnlockStatus`](#unlockstatus), [`UnlocksView`](#unlocksview), [`UnlockView`](#unlockview) ### CheatDef [#cheatdef] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#cheatdef). A cheat the game declares in `data.unlocks.cheats`. Using it runs its effects at once, in any scene and through any lock, and ends no turn unless its effects do. ```ts shape import type { CheatDef } from '@ifloom/plugin-unlocks' type CheatDef = { id: string name: string description?: string effects: EffectRef[] blocked?: Blocked[] group?: string once?: Once } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The cheat's id, unique among the game's cheats. | | `name` | `string` | | | The cheat's name, which its button shows, such as "+20 coins". | | `description` | `string` | yes | | The cheat's line in the cheats panel. | | `effects` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | | | The cheat's effects, run in order. It must have at least one. | | `blocked` | [`Blocked[]`](https://ifloom.dev/docs/api/engine#blocked) | yes | | The cheat's refusals. The first entry whose `when` holds refuses the button with its reason, or leaves the cheat out of the view with `hide`. A supporter-only cheat is `{ when: { not: { 'unlocks/has': { unlock: 'supporter' } } }, reason: 'For supporters' }`. | | `group` | `string` | yes | | The heading the cheat is listed under in the panel. Cheats with none come first. | | `once` | [`Once`](https://ifloom.dev/docs/api/engine#once) | yes | | The cheat's limit, once in a save (`{ per: 'game' }`) or once a turn (`{ per: 'turn' }`), as a choice's `once` is. `reason` is the refusal once it's used. The `unlocks/usedOnce` string, "Already used.", if left out. | ### cheatOf [#cheatof] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#cheatof). Returns the game's cheat with the id `id`, or undefined when there is none. ```ts shape import { cheatOf } from '@ifloom/plugin-unlocks' function cheatOf(game: Game, id: string): CheatDef | undefined ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`CheatDef`](#cheatdef). ### cheatsOf [#cheatsof] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#cheatsof). Returns the game's cheats, `data.unlocks.cheats` from its content and packs, in declared order. ```ts shape import { cheatsOf } from '@ifloom/plugin-unlocks' function cheatsOf(game: Game): CheatDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`CheatDef`](#cheatdef). ### CheatUse [#cheatuse] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#cheatuse). A use of a cheat, one entry of `UnlocksState.cheated`. ```ts shape import type { CheatUse } from '@ifloom/plugin-unlocks' type CheatUse = { cheat: string turn: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `cheat` | `string` | | | The id of the cheat used. | | `turn` | `number` | | | The turn the cheat was used on. | ### CheatView [#cheatview] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#cheatview). A cheat as the player sees it, in `view.plugins.unlocks.cheats`. ```ts shape import type { CheatView } from '@ifloom/plugin-unlocks' type CheatView = { id: string name: string description: string group: string | null once: 'game' | 'turn' | null used: number button: RenderedChoice } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The cheat's id. | | `name` | `string` | | | The cheat's name. | | `description` | `string` | | | The cheat's description, or `''` when it has none. | | `group` | `string \| null` | | | The heading the cheat goes under, or null when it has none. | | `once` | `'game' \| 'turn' \| null` | | | The cheat's `once` limit, `'game'` or `'turn'`, or null when it can be used any number of times. | | `used` | `number` | | | The number of times this save has used the cheat. | | `button` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) | | | The cheat's button. It's refused with its reason while a `blocked` entry holds, or once a `once` cheat is used. | ### codeFits [#codefits] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#codefits). Returns true when the code is the unlock's code. ```ts shape import { codeFits } from '@ifloom/plugin-unlocks' function codeFits(code: string, game: string, def: UnlockDef): Promise ``` Uses: [`UnlockDef`](#unlockdef). ### contentScript [#contentscript] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#contentscript). Returns the script `ifloom build` puts in the page's head, which holds the encrypted content by unlock. ```ts shape import { contentScript } from '@ifloom/plugin-unlocks' function contentScript(locked: readonly LockedContent[]): string ``` Uses: [`LockedContent`](#lockedcontent). ### enterCode [#entercode] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#entercode). Returns the unlock a code opens, checked against every unlock on a runner `startUnlocks` was started on, or the reason it opens none. It never throws. The profile remembers a code that works, and the game in play records its unlock. The runner's snapshot reports the check at `helpers.unlocks` while it runs and after. ```ts shape import { enterCode } from '@ifloom/plugin-unlocks' function enterCode(runner: Runner, code: string): Promise> ``` Uses: [`Runner`](https://ifloom.dev/docs/api/engine#runner), [`Result`](https://ifloom.dev/docs/api/engine#result), [`Entered`](#entered). ### Entered [#entered] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#entered). The unlock a code opened, as `enterCode` returns it. ```ts shape import type { Entered } from '@ifloom/plugin-unlocks' type Entered = { unlock: string name: string already: boolean restart: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `unlock` | `string` | | | The unlock's id. | | `name` | `string` | | | The unlock's name. | | `already` | `boolean` | | | True when the unlock was open already, so the code worked and changed nothing. | | `restart` | `boolean` | | | True when the unlock has packs the game in play doesn't have yet. Reloading the page builds the game again with them. | ### envName [#envname] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#envname). Returns the name of the environment variable `ifloom build` reads an unlock's code from, such as `IFLOOM_UNLOCK_SUPPORTER` for `supporter`. ```ts shape import { envName } from '@ifloom/plugin-unlocks' function envName(unlock: string): string ``` ### ITERATIONS [#iterations] Const. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#iterations). The number of PBKDF2 rounds for an unlock without its own `iterations`. It makes guessing codes one by one take a long time. ```ts shape import { ITERATIONS } from '@ifloom/plugin-unlocks' const ITERATIONS: 600000 ``` ### lockContent [#lockcontent] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#lockcontent). Returns an unlock's packs encrypted under its code, for the page, as `ifloom build` does with each file in `src/unlocks/`. The packs must be data, as a mod's are. It throws when the code isn't the unlock's, so a build can't ship content no code opens, and when a pack holds a function. ```ts shape import { lockContent } from '@ifloom/plugin-unlocks' function lockContent(code: string, game: string, def: UnlockDef, packs: readonly Pack[]): Promise ``` Uses: [`UnlockDef`](#unlockdef), [`Pack`](https://ifloom.dev/docs/api/engine#pack), [`LockedContent`](#lockedcontent). ### LockedContent [#lockedcontent] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#lockedcontent-1). An unlock's encrypted packs as `ifloom build` writes them into the page. ```ts shape import type { LockedContent } from '@ifloom/plugin-unlocks' type LockedContent = { ifloomUnlock: 1 game: string unlock: string iv: string data: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `ifloomUnlock` | `1` | | | The format of this record, 1. | | `game` | `string` | | | The game's id. | | `unlock` | `string` | | | The unlock's id. | | `iv` | `string` | | | The AES-GCM nonce, in base64. | | `data` | `string` | | | The packs as JSON, encrypted, in base64. | ### lockedContent [#lockedcontent-1] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#lockedcontent). Returns the encrypted content `ifloom build` put in the page, by unlock. Returns an empty record in a page without any. ```ts shape import { lockedContent } from '@ifloom/plugin-unlocks' function lockedContent(): Readonly> ``` Uses: [`LockedContent`](#lockedcontent). ### normaliseCode [#normalisecode] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#normalisecode). Returns a code in the form the plugin checks, Unicode-normalised, without spaces or hyphens, in capitals. So `bread-2026`, `BREAD 2026` and `Bread2026` are one code. ```ts shape import { normaliseCode } from '@ifloom/plugin-unlocks' function normaliseCode(code: string): string ``` ### startUnlocks [#startunlocks] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#startunlocks). Starts code entry on a runner and returns the function that stops it. Start it once per runner, which needs a `profile`. It records every unlock the profile remembers into the game in play, each new game and each loaded save, so a supporter enters a code once, and `enterCode` checks the codes the player enters. It reports an `UnlockStatus` at `snapshot.helpers.unlocks`. Pass `content` only in tests, since it reads the page's own otherwise. ```ts shape import { startUnlocks } from '@ifloom/plugin-unlocks' function startUnlocks(runner: Runner, options?: { content?: Readonly> }): () => void ``` Uses: [`Runner`](https://ifloom.dev/docs/api/engine#runner), [`LockedContent`](#lockedcontent). ### UnlockDef [#unlockdef] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlockdef). An unlock the game declares in `data.unlocks.unlocks`. It holds the code's hash, never the code. ```ts shape import type { UnlockDef } from '@ifloom/plugin-unlocks' type UnlockDef = { id: string name: string description?: string hash: string salt?: string iterations?: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The unlock's id. | | `name` | `string` | | | The unlock's name, such as "Supporter edition". | | `description` | `string` | yes | | The unlock's description, a line for the list of unlocks. | | `hash` | `string` | | | The code's hash in hex, as `ifloom unlock-hash` prints it. | | `salt` | `string` | yes | | The unlock's extra salt, mixed in after the game's and the unlock's ids. Changing it changes the hash without changing the code. | | `iterations` | `number` | yes | | The number of PBKDF2 rounds for this code. 600,000 if left out, and fewer only in tests. | ### unlockedPacks [#unlockedpacks] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlockedpacks). Returns the packs of every unlock the profile remembers, decrypted and checked that this engine can read them. Call it before building the game, and pass them as `loadGame(content, base, { packs: unlocked.packs })`. An unlock whose code has changed since it was entered, as in a new release with new codes, can't be opened and is listed in `problems`. The player then enters the new code. ```ts shape import { unlockedPacks } from '@ifloom/plugin-unlocks' function unlockedPacks(game: string, profile: Profile, content?: Readonly>): Promise<{ packs: Pack[]; problems: string[] }> ``` Uses: [`Profile`](https://ifloom.dev/docs/api/engine#profile), [`LockedContent`](#lockedcontent), [`Pack`](https://ifloom.dev/docs/api/engine#pack). ### unlockHash [#unlockhash] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlockhash). Returns the hash of a code for an unlock, in hex, the value for the unlock's `hash`. `ifloom unlock-hash` prints it, so you never write the code into the game. ```ts shape import { unlockHash } from '@ifloom/plugin-unlocks' function unlockHash(code: string, game: string, def: Pick): Promise ``` Uses: [`UnlockDef`](#unlockdef). ### unlocks [#unlocks] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlocks). The unlocks plugin's factory, with its helpers as properties. `unlocks()` returns the plugin for the game's `plugins`, and content calls helpers such as `unlocks.has('supporter')` and `unlocks.cheat('rich')`. ```ts shape import { unlocks } from '@ifloom/plugin-unlocks' function unlocks(): DefinedPlugin ``` Uses: [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`UnlocksState`](#unlocksstate), [`UnlocksView`](#unlocksview). | Helper | Signature | Description | |---|---|---| | `unlocks.has` | `(unlock: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `unlocks/has` condition, which holds once this save records the unlock. | | `unlocks.record` | `(unlock: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `unlocks/record` command, which records the unlock in this save. `startUnlocks` sends it. | | `unlocks.cheat` | `(cheat: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `unlocks/cheat` command, which runs the cheat's effects through any lock and logs the use. | | `unlocks.cheated` | `(cheat?: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `unlocks/cheated` condition, which holds once this save has used the cheat, or any cheat when none is named. | ### unlocksOf [#unlocksof] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlocksof). Returns the game's unlocks, from `data.unlocks.unlocks` in its content and packs. ```ts shape import { unlocksOf } from '@ifloom/plugin-unlocks' function unlocksOf(game: Game): UnlockDef[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`UnlockDef`](#unlockdef). ### UnlocksProfile [#unlocksprofile] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlocksprofile). The record the plugin keeps in the player's profile, under `unlocks`. It never holds a code. ```ts shape import type { UnlocksProfile } from '@ifloom/plugin-unlocks' type UnlocksProfile = { unlocked: Record } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `unlocked` | `Record` | | | The proof made from each code that worked, in hex, by unlock id. | ### UnlocksState [#unlocksstate] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlocksstate). The unlocks and cheat uses a save keeps. The plugin reads the unlocks and cheats themselves from content. ```ts shape import type { UnlocksState } from '@ifloom/plugin-unlocks' type UnlocksState = { unlocked: string[] cheated: CheatUse[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `unlocked` | `string[]` | | | The ids of the unlocks recorded in this save, in the order they were recorded. | | `cheated` | [`CheatUse[]`](#cheatuse) | | | The save's uses of cheats, oldest first. | ### UnlockStatus [#unlockstatus] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlockstatus). The state of code entry that `startUnlocks` reports in the runner's snapshot, at `snapshot.helpers.unlocks`. ```ts shape import type { UnlockStatus } from '@ifloom/plugin-unlocks' type UnlockStatus = { status: 'idle' | 'checking' | 'wrong' | 'unlocked' reason: string | null entered: Entered | null } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `status` | `'idle' \| 'checking' \| 'wrong' \| 'unlocked'` | | | The state of code entry, `checking`, `wrong`, `unlocked` or `idle`. It's `wrong` when the last code didn't work and `unlocked` when it did. It's `checking` while a code is checked, slowly on purpose, and while the profile's remembered codes are checked at start. | | `reason` | `string \| null` | | | The reason the last code didn't work while `status` is `wrong`, else null. | | `entered` | [`Entered`](#entered) `\| null` | | | The unlock the last code opened while `status` is `unlocked`, else null. | ### UnlocksView [#unlocksview] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlocksview). The unlocks and cheats as the player sees them, in `view.plugins.unlocks`. ```ts shape import type { UnlocksView } from '@ifloom/plugin-unlocks' type UnlocksView = { unlocks: UnlockView[] unlocked: number total: number cheats: CheatView[] cheated: number } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `unlocks` | [`UnlockView[]`](#unlockview) | | | The game's unlocks, in the order the game declares them. | | `unlocked` | `number` | | | The number of unlocks this save records. | | `total` | `number` | | | The number of unlocks the game declares. | | `cheats` | [`CheatView[]`](#cheatview) | | | The cheats the player can see, in the order the game declares them. A cheat refused by an entry with `hide` is left out. | | `cheated` | `number` | | | The number of cheat uses in this save, counting every cheat. | ### UnlockView [#unlockview] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlockview). An unlock as the player sees it, in `view.plugins.unlocks.unlocks`. ```ts shape import type { UnlockView } from '@ifloom/plugin-unlocks' type UnlockView = { id: string name: string description: string unlocked: boolean } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The unlock's id. | | `name` | `string` | | | The unlock's name. | | `description` | `string` | | | The unlock's description, or `''` when it has none. | | `unlocked` | `boolean` | | | True when this save records the unlock. | ## @ifloom/plugin-unlocks/react [#ifloomplugin-unlocksreact] - Functions: [`unlocksUiWith`](#unlocksuiwith), [`useCheats`](#usecheats), [`useUnlocks`](#useunlocks) - Constants: [`CheatPanel`](#cheatpanel), [`CheatsButton`](#cheatsbutton), [`UNLOCKS_WORDS`](#unlocks_words), [`UnlocksPanel`](#unlockspanel), [`unlocksUi`](#unlocksui) - Types: [`CheatGroup`](#cheatgroup), [`CheatsControls`](#cheatscontrols), [`UnlocksControls`](#unlockscontrols), [`UnlocksUiOptions`](#unlocksuioptions) ### CheatGroup [#cheatgroup] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#cheatgroup). A group of the cheats panel, a heading and the cheats under it. The cheats with no group form one with a null name. ```ts shape import type { CheatGroup } from '@ifloom/plugin-unlocks/react' type CheatGroup = { name: string | null cheats: CheatView[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `name` | `string \| null` | | | The group's heading, or null for the cheats with no group. | | `cheats` | [`CheatView[]`](#cheatview) | | | The group's cheats, in the order the game declares them. | ### CheatPanel [#cheatpanel] Const. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#cheatpanel). Renders the cheats from `view.plugins.unlocks.cheats` under their groups' headings, each with its button, its description and its use count. A preset styles its `cheats`, `cheats-group`, `cheats-group-title`, `cheat`, `cheat-text` and `cheat-used` parts. A refused cheat's button is disabled with its reason, such as a supporter cheat before the unlock or a `once` cheat after its use. It renders nothing while the player can see no cheat. ```ts shape import { CheatPanel } from '@ifloom/plugin-unlocks/react' const CheatPanel: ComponentType<{ className?: string; }> ``` ### CheatsButton [#cheatsbutton] Const. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#cheatsbutton). Renders the button that opens the `CheatPanel` in a dialog. A preset styles its `cheats-button` part. It renders nothing in a game without the plugin, or while the player can see no cheat. ```ts shape import { CheatsButton } from '@ifloom/plugin-unlocks/react' const CheatsButton: ComponentType<{ className?: string; }> ``` ### CheatsControls [#cheatscontrols] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#cheatscontrols). The cheats from the unlocks plugin's view, grouped, with a way to use one, as `useCheats` returns them. ```ts shape import type { CheatsControls } from '@ifloom/plugin-unlocks/react' type CheatsControls = { cheats: CheatView[] cheated: number groups: CheatGroup[] use: (cheat: string) => Result } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `cheats` | [`CheatView[]`](#cheatview) | | | The cheats the player can see, in the order the game declares them. | | `cheated` | `number` | | | The number of cheat uses in this save, counting every cheat. | | `groups` | [`CheatGroup[]`](#cheatgroup) | | | The cheats grouped by their `group`, the ungrouped ones first, then each group in the order it first appears. | | `use` | `(cheat: string) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends the `unlocks/cheat` command for the cheat. A refused use returns the reason its button gives. | ### UNLOCKS_WORDS [#unlocks_words] Const. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlocks_words). The unlocks plugin's UI words, in English. A game rewords any of them with `ui.` in its strings. ```ts shape import { UNLOCKS_WORDS } from '@ifloom/plugin-unlocks/react' const UNLOCKS_WORDS: { cheatUsedOnce: 'Used once' cheatUsedTimes: 'Used {n} times' cheats: 'Cheats' checkingCode: 'Checking…' code: 'Code' enterCode: 'Enter a code' locked: 'Locked' restartForUnlock: 'Restart to add it' unlock: 'Unlock' unlocked: 'Unlocked' unlockedAlready: '{label} was unlocked already.' unlockedNow: 'Unlocked: {label}.' } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `cheatUsedOnce` | `'Used once'` | | | The note on a cheat the player has used once. | | `cheatUsedTimes` | `'Used {n} times'` | | | The note on a cheat the player has used more than once, with `{n}` uses. | | `cheats` | `'Cheats'` | | | The label of the cheats button and the title of its dialog. | | `checkingCode` | `'Checking…'` | | | The label of the unlock button while a code is checked. | | `code` | `'Code'` | | | The placeholder and the screen readers' label of the code box. | | `enterCode` | `'Enter a code'` | | | The heading over the code box, and the label of the menu button that opens it without pages. | | `locked` | `'Locked'` | | | The state of an unlock the player hasn't opened. | | `restartForUnlock` | `'Restart to add it'` | | | The label of the button that restarts the game to add the packs a code opened. | | `unlock` | `'Unlock'` | | | The label of the button that checks the code. | | `unlocked` | `'Unlocked'` | | | The state of an unlock the player has opened. | | `unlockedAlready` | `'{label} was unlocked already.'` | | | The message for a code that opened an unlock the player had already, with its `{label}`. | | `unlockedNow` | `'Unlocked: {label}.'` | | | The message for a code that has just opened an unlock, with its `{label}`. | ### UnlocksControls [#unlockscontrols] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlockscontrols). The unlocks plugin's view with the code box's state and a function that enters a code, as `useUnlocks` returns it. ```ts shape import type { UnlocksControls } from '@ifloom/plugin-unlocks/react' type UnlocksControls = { unlocks: UnlockView[] unlocked: number total: number cheats: CheatView[] cheated: number available: boolean enter: (code: string) => Promise checking: boolean entered: Entered | null message: string | null restart: (() => void) | undefined problems: string[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `unlocks` | [`UnlockView[]`](#unlockview) | | | The game's unlocks, in the order the game declares them. | | `unlocked` | `number` | | | The number of unlocks this save records. | | `total` | `number` | | | The number of unlocks the game declares. | | `cheats` | [`CheatView[]`](#cheatview) | | | The cheats the player can see, in the order the game declares them. A cheat refused by an entry with `hide` is left out. | | `cheated` | `number` | | | The number of cheat uses in this save, counting every cheat. | | `available` | `boolean` | | | True when code entry has started on the runner, which the unlocks UI does. | | `enter` | `(code: string) => Promise` | | | Checks a code with `enterCode` and resolves true when it opened an unlock. `entered` then names it, or `message` gives the reason it didn't. | | `checking` | `boolean` | | | True while a code is checked, slowly on purpose, from the snapshot's `helpers.unlocks.status`. | | `entered` | [`Entered`](#entered) `\| null` | | | The unlock the last code opened, or null. | | `message` | `string \| null` | | | The reason the last code didn't work, or null. | | `restart` | `(() => void) \| undefined` | | | The function that builds the game again with the packs a code just opened, `onChange` from `unlocksUiWith`. It is undefined unless the last code needs it. | | `problems` | `string[]` | | | The problems opening the packs the profile remembers, such as a code that has changed since. | ### UnlocksPanel [#unlockspanel] Const. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlockspanel). Renders the code box and the list of unlocks from `view.plugins.unlocks`. It shows the unlock a code opened, or why the code failed. A restart button shows when the code opened packs the game in play doesn't have yet. The unlocks UI puts it on the settings page, or in the menu without pages. A preset can style the parts `unlocks`, `unlocks-title`, `unlock-form`, `unlock-input`, `unlocks-message`, `unlocks-entered`, `unlock-problem`, `unlocks-list`, `unlock`, `unlock-name`, `unlock-state` and `unlock-text`. ```ts shape import { UnlocksPanel } from '@ifloom/plugin-unlocks/react' const UnlocksPanel: ComponentType<{ className?: string; }> ``` ### unlocksUi [#unlocksui] Const. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlocksui). The unlocks plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It puts the `UnlocksPanel` on the settings page, and the `CheatsButton` in the sidebar. Without pages, the `UnlocksPanel` is behind a menu button. The `CheatsButton` opens the `CheatPanel`. Each renders nothing while the game has no unlocks, or the player can see no cheat. It also starts code entry on the runner. `unlocksUiWith` returns the same UI with problems and a restart. ```ts shape import { unlocksUi } from '@ifloom/plugin-unlocks/react' const unlocksUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### UnlocksUiOptions [#unlocksuioptions] Type. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlocksuioptions). Settings for `unlocksUiWith`. Without them, the UI shows no problems and offers no restart. ```ts shape import type { UnlocksUiOptions } from '@ifloom/plugin-unlocks/react' type UnlocksUiOptions = { problems?: string[] onChange?: () => void start?: (runner: Runner) => () => void } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `problems` | `string[]` | yes | | The `problems` from `unlockedPacks`, shown under the code box. | | `onChange` | `() => void` | yes | | The function that builds the game again with the packs a code has just opened, such as `() => location.reload()`. | | `start` | `(runner:` [`Runner`](https://ifloom.dev/docs/api/engine#runner)`) => () => void` | yes | | The function that starts code entry on the runner and returns the function that stops it. `startUnlocks` if left out. | ### unlocksUiWith [#unlocksuiwith] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#unlocksuiwith). Returns the unlocks plugin's React UI with settings. It shows the `problems` from `unlockedPacks` under the code box. Its restart button calls `onChange` once a code has opened packs the game in play doesn't have yet. ```ts shape import { unlocksUiWith } from '@ifloom/plugin-unlocks/react' function unlocksUiWith(options?: UnlocksUiOptions): PluginUi ``` Uses: [`UnlocksUiOptions`](#unlocksuioptions), [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). ### useCheats [#usecheats] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#usecheats). Returns the cheats from the unlocks plugin's view, their groups and their command from the running game, or null in a game without the plugin. It re-renders when the view changes. `CheatPanel` renders from it. ```ts shape import { useCheats } from '@ifloom/plugin-unlocks/react' function useCheats(): CheatsControls | null ``` Uses: [`CheatsControls`](#cheatscontrols). ### useUnlocks [#useunlocks] Function. Explained in [Unlocks and cheats](https://ifloom.dev/docs/reference/plugins/unlocks#useunlocks). Returns the unlocks plugin's view and the code box's state from the running game, or null in a game without the plugin. It re-renders when the view or the snapshot's `helpers.unlocks` changes. Before code entry has started on the runner, `available` is false and the list of unlocks still shows. ```ts shape import { useUnlocks } from '@ifloom/plugin-unlocks/react' function useUnlocks(): UnlocksControls | null ``` Uses: [`UnlocksControls`](#unlockscontrols). # @ifloom/plugin-wardrobe (https://ifloom.dev/docs/api/plugin-wardrobe) Generated from the source of `@ifloom/plugin-wardrobe` and `@ifloom/plugin-wardrobe/react` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. ## @ifloom/plugin-wardrobe [#ifloomplugin-wardrobe] - Functions: [`ownedHere`](#ownedhere), [`slotsOf`](#slotsof), [`wardrobe`](#wardrobe), [`wearableOf`](#wearableof) - Types: [`Closet`](#closet), [`Owners`](#owners), [`WardrobeOptions`](#wardrobeoptions), [`WardrobeSlot`](#wardrobeslot), [`WardrobeState`](#wardrobestate), [`WardrobeView`](#wardrobeview), [`Wearable`](#wearable) ### Closet [#closet] Type. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#closet). The data of the `wardrobe/closet` trait, which makes a location somewhere the player can change clothes. While the player is there, the room offers a button that opens the `wardrobe` panel. The button needs the places plugin, which says where the player is. ```ts shape import type { Closet } from '@ifloom/plugin-wardrobe' type Closet = { label?: string } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `label` | `string` | yes | | The label of the button that opens the `wardrobe` panel. The `wardrobe/open` string (`Wardrobe`) if left out. | ### ownedHere [#ownedhere] Function. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#ownedhere). Returns how many of a thing a body (`'you'` if left out) has in its wardrobe, its starts read from `wardrobe/owned`. ```ts shape import { ownedHere } from '@ifloom/plugin-wardrobe' function ownedHere(state: GameState, game: Game, ref: string, at?: string): number ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game). ### Owners [#owners] Type. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#owners). The bodies that own a thing at the start, one body for one of it or a count for each body (`{ player: 1, 'character:sam': 1 }`). ```ts shape import type { Owners } from '@ifloom/plugin-wardrobe' type Owners = EntityRef | typeof PLAYER | Partial> ``` Uses: [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref). ### slotsOf [#slotsof] Function. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#slotsof). Returns the game's slots in order, from `data.wardrobe.slots` in its content and packs. ```ts shape import { slotsOf } from '@ifloom/plugin-wardrobe' function slotsOf(game: Game): WardrobeSlot[] ``` Uses: [`Game`](https://ifloom.dev/docs/api/engine#game), [`WardrobeSlot`](#wardrobeslot). ### wardrobe [#wardrobe] Function. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wardrobe). The wardrobe plugin's factory, with its helpers as properties. `wardrobe()` returns the plugin for the game's `plugins`, and content calls helpers such as `wardrobe.wearable('coat')` and `wardrobe.wear('clothing:scarf')`. ```ts shape import { wardrobe } from '@ifloom/plugin-wardrobe' function wardrobe(options?: WardrobeOptions): DefinedPlugin ``` Uses: [`WardrobeOptions`](#wardrobeoptions), [`DefinedPlugin`](https://ifloom.dev/docs/api/engine-plugin#definedplugin), [`WardrobeState`](#wardrobestate), [`WardrobeView`](#wardrobeview). | Helper | Signature | Description | |---|---|---| | `wardrobe.wearable` | `(slot: string, hooks?: { onWear?:` [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref)`; onTakeOff?:` [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) `}): { 'wardrobe/wearable':` [`Wearable`](#wearable) `}` | Returns the `wardrobe/wearable` trait for a slot, with its `onWear` and `onTakeOff` effects, to spread into `traits`. | | `wardrobe.owned` | `(owners:` [`Owners`](#owners)`): { 'wardrobe/owned':` [`Owners`](#owners) `}` | Returns the `wardrobe/owned` trait, to spread into an entity's `traits`, naming whose wardrobe it starts in. | | `wardrobe.closet` | `(options?:` [`Closet`](#closet)`): { 'wardrobe/closet':` [`Closet`](#closet) `}` | Returns the `wardrobe/closet` trait, to spread into a location's `traits`, which offers a button that opens the `wardrobe` panel. | | `wardrobe.wearing` | `(entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, slot?: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `wardrobe/wearing` condition, which holds while whoever the player is playing wears the thing, in `slot` if given. | | `wardrobe.slotFilled` | `(slot: string):` [`Condition`](https://ifloom.dev/docs/api/engine#condition) | Returns the `wardrobe/wearing` condition for a slot, which holds while whoever the player is playing has something in it. | | `wardrobe.wear` | `(entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `wardrobe/wear` command, which puts on a thing the player owns. | | `wardrobe.takeOff` | `(slot: string):` [`CommandRef`](https://ifloom.dev/docs/api/engine#commandref) | Returns the `wardrobe/takeOff` command, which takes off whatever is in the slot. | | `wardrobe.store` | `(entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, options?: { at?:` [`Someone`](https://ifloom.dev/docs/api/engine#someone)`; by?: number; via?: string }):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `wardrobe/store` effect, which puts a thing someone carries away in their wardrobe. | | `wardrobe.takeOut` | `(entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`, options?: { at?:` [`Someone`](https://ifloom.dev/docs/api/engine#someone)`; by?: number; via?: string }):` [`EffectRef`](https://ifloom.dev/docs/api/engine#effectref) | Returns the `wardrobe/takeOut` effect, which takes a thing out of someone's wardrobe into the next receiver. | ### WardrobeOptions [#wardrobeoptions] Type. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wardrobeoptions). The wardrobe plugin's settings, which the game passes to `wardrobe()`. ```ts shape import type { WardrobeOptions } from '@ifloom/plugin-wardrobe' type WardrobeOptions = { claims?: boolean onWear?: EffectRef[] onTakeOff?: EffectRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `claims` | `boolean` | yes | | False for a game where clothes are carried before they're put away. True if left out. With it false, the wardrobe claims nothing a `receive` gives, so wearables go to the next receiver, and `wardrobe/store` puts them away by name. | | `onWear` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | Effects that run when a body puts on anything, after the thing's own `onWear`. | | `onTakeOff` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | Effects that run when a body takes off anything, after the thing's own `onTakeOff`. | ### WardrobeSlot [#wardrobeslot] Type. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wardrobeslot). A slot the game declares in `data.wardrobe.slots`, a part of the body where a thing can be worn. ```ts shape import type { WardrobeSlot } from '@ifloom/plugin-wardrobe' type WardrobeSlot = { id: string label: string start?: EntityRef } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The slot's id, which a wearable thing's `slot` names. | | `label` | `string` | | | The slot's label. | | `start` | [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) | yes | | The wearable thing in the slot at the start, one the player owns at the start. The slot starts empty if left out. | ### WardrobeState [#wardrobestate] Type. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wardrobestate). The clothes a save keeps for each body. The plugin reads slots and wearable things from content. ```ts shape import type { WardrobeState } from '@ifloom/plugin-wardrobe' type WardrobeState = { worn: Record> owned: Record> } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `worn` | `Record>` | | | The thing worn in each slot, by body (`'player'` or a protagonist such as `'character:sam'`) and then by slot id. | | `owned` | `Record>` | | | The counts of clothes in each body's wardrobe that play changed, by body and then thing. A count written once is kept, 0 included. For the rest, the plugin reads each thing's `wardrobe/owned` trait. | ### WardrobeView [#wardrobeview] Type. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wardrobeview). The wardrobe of whoever the player is playing as the player sees it, in `view.plugins.wardrobe`. ```ts shape import type { WardrobeView } from '@ifloom/plugin-wardrobe' type WardrobeView = { slots: { id: string; label: string; entity: EntityRef | null; name: string | null; takeOff: RenderedChoice | null }[] spare: { entity: EntityRef; name: string; slot: string; wear: RenderedChoice }[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `slots` | `{ id: string; label: string; entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) `\| null; name: string \| null; takeOff:…` | | | The game's slots in order, each with the thing in it. | | `spare` | `{ entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`; name: string; slot: string; wear:` [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `}[]` | | | The wearable things whoever is played owns and isn't wearing, in the order of the game's entities. Each has its slot and the button that puts it on, labelled with the `wardrobe/wear` string (`Wear {thing}`). | ### Wearable [#wearable] Type. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wearable). The data of the `wardrobe/wearable` trait, which makes a thing wearable in one slot. ```ts shape import type { Wearable } from '@ifloom/plugin-wardrobe' type Wearable = { slot: string onWear?: EffectRef[] onTakeOff?: EffectRef[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `slot` | `string` | | | The id of the slot the thing goes in, such as `'coat'`. | | `onWear` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | Effects that run when a body puts the thing on, such as `[{ kv: 'onDuty', to: true }]`, before the game-wide ones. | | `onTakeOff` | [`EffectRef[]`](https://ifloom.dev/docs/api/engine#effectref) | yes | | Effects that run when a body takes the thing off, or it comes off by itself, before the game-wide ones. | ### wearableOf [#wearableof] Function. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wearableof). Returns a thing's `wardrobe/wearable` trait, read through the entity it was made `like`. Returns undefined for a thing that can't be worn. ```ts shape import { wearableOf } from '@ifloom/plugin-wardrobe' function wearableOf(state: GameState, game: Game, ref: string): Wearable | undefined ``` Uses: [`GameState`](https://ifloom.dev/docs/api/engine#gamestate), [`Game`](https://ifloom.dev/docs/api/engine#game), [`Wearable`](#wearable). ## @ifloom/plugin-wardrobe/react [#ifloomplugin-wardrobereact] - Components: [`WardrobeSection`](#wardrobesection) - Functions: [`useWardrobe`](#usewardrobe) - Constants: [`WARDROBE_WORDS`](#wardrobe_words), [`WardrobeCard`](#wardrobecard), [`wardrobeUi`](#wardrobeui) - Types: [`WardrobeControls`](#wardrobecontrols), [`WardrobeSlotControls`](#wardrobeslotcontrols) ### useWardrobe [#usewardrobe] Function. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#usewardrobe). Returns the wardrobe plugin's view and commands from the running game, or null in a game without the plugin. It re-renders when the view changes. ```ts shape import { useWardrobe } from '@ifloom/plugin-wardrobe/react' function useWardrobe(): WardrobeControls | null ``` Uses: [`WardrobeControls`](#wardrobecontrols). ### WARDROBE_WORDS [#wardrobe_words] Const. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wardrobe_words). The wardrobe plugin's UI words, in English. A game rewords any of them with `ui.` in its strings. ```ts shape import { WARDROBE_WORDS } from '@ifloom/plugin-wardrobe/react' const WARDROBE_WORDS: { readonly nothingOn: 'Nothing'; readonly wardrobe: 'Wearing'; } ``` ### WardrobeCard [#wardrobecard] Const. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wardrobecard). Renders what the player has on from `view.plugins.wardrobe`, slot by slot, with the other things they could wear. It renders nothing without the plugin. A button that can't be used now is disabled with the engine's reason. A preset can style the parts `wardrobe`, `wardrobe-title`, `wardrobe-slot`, `wardrobe-slot-name` and `wardrobe-worn`. ```ts shape import { WardrobeCard } from '@ifloom/plugin-wardrobe/react' const WardrobeCard: ComponentType<{ className?: string; title?: string | false; }> ``` ### WardrobeControls [#wardrobecontrols] Type. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wardrobecontrols). The wardrobe plugin's view, slot by slot with its buttons, and functions that send its commands, as `useWardrobe` returns it. ```ts shape import type { WardrobeControls } from '@ifloom/plugin-wardrobe/react' type WardrobeControls = { spare: { entity: EntityRef; name: string; slot: string; wear: RenderedChoice }[] slots: WardrobeSlotControls[] wear: (entity: EntityRef) => Result takeOff: (slot: string) => Result } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `spare` | `{ entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`; name: string; slot: string; wear:` [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `}[]` | | | The wearable things whoever is played owns and isn't wearing, in the order of the game's entities. Each has its slot and the button that puts it on, labelled with the `wardrobe/wear` string (`Wear {thing}`). | | `slots` | [`WardrobeSlotControls[]`](#wardrobeslotcontrols) | | | The game's slots in order, each with the thing in it and its buttons. | | `wear` | `(entity:` [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref)`) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends `wardrobe/wear` for a thing the player holds, by its reference, such as `'clothing:scarf'`. | | `takeOff` | `(slot: string) =>` [`Result`](https://ifloom.dev/docs/api/engine#result)`<`[`GameState`](https://ifloom.dev/docs/api/engine#gamestate)`>` | | | Sends `wardrobe/takeOff`, which empties the slot with this id. | ### WardrobeSection [#wardrobesection] Component. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wardrobesection). Renders a Wearing section that folds, holding the `WardrobeCard`. `wardrobeUi` doesn't place it, so put it in your layout's `` to keep what the player wears on screen. ```ts shape import { WardrobeSection } from '@ifloom/plugin-wardrobe/react' function WardrobeSection(): JSX.Element ``` ### WardrobeSlotControls [#wardrobeslotcontrols] Type. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wardrobeslotcontrols). A slot as `useWardrobe` returns it, with the thing in it and the buttons that take it off or put another thing on. ```ts shape import type { WardrobeSlotControls } from '@ifloom/plugin-wardrobe/react' type WardrobeSlotControls = { id: string label: string entity: EntityRef | null name: string | null takeOff: RenderedChoice | null wear: RenderedChoice[] } ``` | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `id` | `string` | | | The slot's id. | | `label` | `string` | | | The slot's label. | | `entity` | [`EntityRef`](https://ifloom.dev/docs/api/engine#entityref) `\| null` | | | The thing in the slot, or null while the slot is empty. | | `name` | `string \| null` | | | The name of the thing in the slot, or null while the slot is empty. | | `takeOff` | [`RenderedChoice`](https://ifloom.dev/docs/api/engine#renderedchoice) `\| null` | | | The button that takes the thing off, labelled with the `wardrobe/takeOff` string, or null while the slot is empty. | | `wear` | [`RenderedChoice[]`](https://ifloom.dev/docs/api/engine#renderedchoice) | | | The `wear` buttons of the spare things for this slot, from the view's `spare`. | ### wardrobeUi [#wardrobeui] Const. Explained in [Wardrobe](https://ifloom.dev/docs/reference/plugins/wardrobe#wardrobeui). The wardrobe plugin's React UI, for `plugins` on `mountGame` or `GameProvider`. It renders the `wardrobe` panel, which a closet's button or any `{ panel: 'wardrobe' }` opens, as a `WardrobeCard`, and adds the plugin's words. It adds nothing to the sidebar, where a layout can place `WardrobeSection`. ```ts shape import { wardrobeUi } from '@ifloom/plugin-wardrobe/react' const wardrobeUi: PluginUi ``` Uses: [`PluginUi`](https://ifloom.dev/docs/api/react-kit#pluginui). # @ifloom/react/kit (https://ifloom.dev/docs/api/react-kit) Generated from the source of `@ifloom/react/kit` and its TSDoc by `npm run api-docs`. Each export links to the page that explains it, where one does. - Components: [`BackButton`](#backbutton), [`Badge`](#badge), [`Button`](#button), [`Card`](#card), [`CardContent`](#cardcontent), [`CardDescription`](#carddescription), [`CardFooter`](#cardfooter), [`CardHeader`](#cardheader), [`CardTitle`](#cardtitle), [`Dialog`](#dialog), [`DialogClose`](#dialogclose), [`DialogContent`](#dialogcontent), [`DialogDescription`](#dialogdescription), [`DialogHeader`](#dialogheader), [`DialogTitle`](#dialogtitle), [`DialogTrigger`](#dialogtrigger), [`PageHeading`](#pageheading), [`PartDialog`](#partdialog), [`ScrollArea`](#scrollarea), [`Separator`](#separator), [`Tabs`](#tabs), [`TabsContent`](#tabscontent), [`TabsList`](#tabslist), [`TabsTrigger`](#tabstrigger), [`Tooltip`](#tooltip), [`TooltipContent`](#tooltipcontent), [`TooltipProvider`](#tooltipprovider), [`TooltipTrigger`](#tooltiptrigger) - Functions: [`badgeVariants`](#badgevariants), [`buttonVariants`](#buttonvariants), [`cn`](#cn), [`overridable`](#overridable), [`pluginKit`](#pluginkit-1), [`useDialogParts`](#usedialogparts), [`useKitPart`](#usekitpart), [`usePageParts`](#usepageparts), [`usePlugin`](#useplugin) - Constants: [`Icon`](#icon), [`KIT_LAYOUT`](#kit_layout), [`KIT_LOOKS`](#kit_looks), [`KIT_PARTS`](#kit_parts), [`PROSE`](#prose) - Types: [`BadgeProps`](#badgeprops), [`ButtonProps`](#buttonprops), [`DialogContentProps`](#dialogcontentprops), [`HintCheckContext`](#hintcheckcontext), [`IconName`](#iconname), [`KitPart`](#kitpart), [`Override`](#override), [`PluginControls`](#plugincontrols), [`PluginKit`](#pluginkit), [`PluginPage`](#pluginpage), [`PluginPanel`](#pluginpanel), [`PluginUi`](#pluginui), [`PluginViewOf`](#pluginviewof), [`UiHint`](#uihint) ## BackButton [#backbutton] Component. Explained in [Plugin UIs and the kit](https://ifloom.dev/docs/reference/react/kit#pageheading-and-backbutton). Renders a page's Back button, the `page-back` part, which calls `usePage().back()`. ```ts shape import { BackButton } from '@ifloom/react/kit' function BackButton(): JSX.Element ``` ## Badge [#badge] Component. Explained in [Plugin UIs and the kit](https://ifloom.dev/docs/reference/react/kit#badge). Renders shadcn/ui's badge, a small rounded label in a ``. ```ts shape import { Badge } from '@ifloom/react/kit' function Badge(props: BadgeProps): JSX.Element ``` Uses: [`BadgeProps`](#badgeprops). ## BadgeProps [#badgeprops] Type. The props of `Badge`, a ``'s props and a `variant`. ```ts shape import type { BadgeProps } from '@ifloom/react/kit' type BadgeProps = { variant?: 'default' | 'secondary' | 'outline' | 'destructive' | null // … } ``` Plugins add fields of their own to it, which their pages list. | Field | Type | Optional | Default | Description | |---|---|---|---|---| | `variant` | `'default' \| 'secondary' \| 'outline' \| 'destructive' \| null` | yes | | The badge's look, `default`, `secondary`, `outline` or `destructive`. `default` if left out. | ## badgeVariants [#badgevariants] Function. Returns the Tailwind classes for a badge's `variant`, shadcn/ui's badge variants. `default` if left out. ```ts fragment function badgeVariants(props?: (ConfigVariants<{ variant: { default: string; secondary: string; outline: string; destructive: string; }; }> & ClassProp) | undefined): string ``` ## Button [#button] Component. Explained in [Plugin UIs and the kit](https://ifloom.dev/docs/reference/react/kit#button). Renders shadcn/ui's button, a `