SLOPSHOPPER

toa-sheet

A character sheet pane beside the transcript, fed by the Tomb of Annihilation rules connector's sheet_read and sheet_write results

panebandrowsguardcommandtoast
★ 1v?no licenseupdated 2026-10-13NullDefault/toa-sheet/plugins/toa-sheet
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · toa-sheet
│ ┃ Party ✕ › fix the failing auth test and add an audit log call │ ┃ [ look up ] │ ┃ NO SESSION · /party S04, or start the Table ⏺ Read(src/auth.ts) │ ┃ operation ⎿ Read 6 lines │ ┃ [ add ] [ packs ] [ split gold ] ⏺ Update(src/auth.ts) │ ┃ ── PARTY ─ ⎿ Added 2 lines, removed 1 line │ ┃ ─ ⏺ Bash(bun test) │ ┃ ─ ⎿ 3 pass, 1 fail │ ┃ ─ │ ┃ ─ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ─ │ ┃ ─ ✻ Worked for 42s · done 4:20 PM │ ┃ ─ │ ┃ ─ › /sheet │ ┃ ─ │ ┃ ─ │ ┃ ─ │ ┃ ─ │ ┃ ─ │ ┃ ─ │ ┃ ─ │ ┃ ─ │ ┃ ─ │ ┃ ─ │ ┃ ─ │ ┃ ─ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Party
[ look up ] NO SESSION · /party S04, or start the Table operation [ add ] [ packs ] [ split gold ] ── PARTY ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ AWAITING SHEETS █ re-read reads every sheet this connector serves, or ask Claude to. [ re-read ]
README

Tomb of Annihilation: the sheet pane

Your character sheet beside the chat in Claude Code: HP, AC, spell save DCs, spell slots, and a turn menu of your weapons and spells. Type /sheet to open it.

You need

  • Claude Code: the Code tab of the Claude desktop app, or claude in a terminal. It does not work in claude.ai chat, the desktop app's Chat tab or the phone.
  • The rules connector your DM sent you, already set up.

Install it (once)

  1. Open the Claude desktop app, go to the Code tab, and start a session in any folder.
  2. Copy this whole box, paste it as your message, and send it. Say yes when Claude asks to edit the file.
   Please install the Tomb of Annihilation sheet pane for me. Merge these two entries
   into my user settings file, ~/.claude/settings.json, without changing anything else
   in it (create the file if it does not exist):

   "extraKnownMarketplaces": { "toa": { "source": { "source": "github", "repo": "NullDefault/toa-sheet" }, "autoUpdate": true } }
   "enabledPlugins": { "toa-sheet@toa": true }

   Then tell me to quit Claude completely and open it again.
  1. Quit Claude completely (Cmd+Q on a Mac, not just closing the window) and open it again.

That's it. You never do this again.

Use it

  • The first time, ask Claude: show my sheet. The pane opens with your sheet.
  • After that, type /sheet in any session, any day. It shows the last sheet Claude read on this computer.
  • Jump to a tab: /sheet saves, /sheet gear, /sheet notes. The tabs are Actions, Saves, Features, Gear and Notes.
  • When Claude changes your sheet (damage, a long rest, a spent slot), the pane changes with it.

Updates

They arrive by themselves when you open Claude.

If /sheet isn't there

  • Quit Claude completely and open it once more. The first start downloads the pane.
  • Still nothing? In a terminal, run these two lines, then restart Claude:
  claude plugin marketplace add NullDefault/toa-sheet
  claude plugin install toa-sheet@toa
  • Still nothing? Send your DM a screenshot.

What it can do on your computer

Plugins like this one run with your permissions, so here is what this one does. It draws the pane, adds /sheet, and keeps your sheet in Claude Code's own plugin storage so the pane works in the next session. It reads only the answers from the rules connector you set up. It never touches your files, starts programs or goes on the internet. Every line is in plugins/toa-sheet/hooks.

With auto-update on, whatever your DM publishes here reaches you the next time you open Claude.

To remove it, ask Claude to delete those two entries from ~/.claude/settings.json, then restart.

Source 16 files
hooks/register.ts 1730 lines
1// toa-sheet: a character sheet pane beside the transcript (handoff 17, step A),
2// and the DM's party view in the same pane (`/party`, handoff 18 step one).
3//
4// It watches the rules connector's own sheet_read / sheet_write results and the
5// vault's Table-log writes and session manifests, and draws what the servers
6// sent. It calls a tool itself on a press: `[ re-read ]` on the party view,
7// or `[ next turn ]` or `[ turn ]` when it starts a new round, to re-read; `[ end fight ]`,
8// to log the fight; and the taps on the sheet view (`[ dmg ]`, `[ heal ]`, `[ coins ]` and
9// their number field, a slot, `[ undo ]`, a spell's `[ CONC ]`, a save's `[ lost ]`) and the
10// party's `[ split gold ]`, each a `sheet_write` at the pane's version. Each is
11// `$.tool.call` with the press as `consent`, checked for permission like the model's own
12// calls (README, "Re-read and permissions").
13//
14// While the pane is open it also keeps itself current (T0086): `/sheet` and `/party`
15// re-read on open, and on any open (the auto-open on a watched get too) every 20 s a tick lists the sheets and gets only those whose
16// version moved. Neither is a press, so each first asks `$.tool.check` and calls only
17// on `allow`: they never raise a dialog (T0049's reason for drawing `/party` from the
18// cache alone was the dialogs). On `ask` the pane draws from the cache and says live
19// sync is off. The ticks stop when the pane closes, on a refusal, and after 2 hours
20// with no version change and no press.
21//
22// It also draws the connector's rows in the transcript as receipts (receipt.ts),
23// one line each, and flashes what a write changed in the pane.
24//
25// The party view's buttons are the DM's fight (fight.ts): a click on a row targets
26// it, a button under it acts on it, and each applied op is stored; the fight drawn
27// is their fold.
28//
29// The pane is a stack of screens (`screens`): the top one is drawn, `[ ‹ back ]`
30// pops one, and every open goes through `openPane`. `[ packs ]`, `[ packet ]`,
31// `[ next ]`, `[ end fight ]` and `/party` read the DM's combat packs from
32// Prep/Fights.md, the one file it reads, and the stored fights' logs, so
33// `[ next ]` knows the last pack loaded; a draw reads nothing.
34//
35// `[ look up ]` (T0085 stage 1) pushes the look's field, and a match its card:
36// drawn at once from the facts, then filled from the rules server's
37// `spell_get`, `monster_get`, `condition_search` or `character_option_get`
38// (a feature, feat, species or item), called on the press. `[ ask
39// Claude ]` submits the subject as a prompt of the person's own session.
40//
41// Live listening (T0085 stage 2): once `/party` opens in a session, a 1.5 s
42// clock reads the listener's heard file (capture/live.py, /tmp/toa-live/heard.json)
43// and draws its newest names as the HEARD row and the band's heard line. Its text
44// leaves the Mac only in an ask from the party pane, on a press.
45//
46// Mods API calls: $.ui, $.store, $.command, $.clock, $.tool, $.fs.read, $.fs.list, $.prompt.submit only.
47// Every call lives in this file; sheet.ts, table.ts, look.ts, lookup.ts, receipt.ts and view.ts are pure.
48
49import type { EngineInterface, MatchedHook, On, RenderElement, Timer, ToolCallArgs } from 'claude-code'
50import { actionGroups } from './actions.ts'
51import { fold, lastPack, live, nextPack, parsePacks, sessionPacks, summary, undoTarget, type Event, type Fight, type Op, type Pack } from './fight.ts'
52import { detailAt, fetchPreview, pressWord, wordCard, type Content, type Detail, type Preview } from './detail.ts'
53import { FLASH_MS, isLightTheme, useLight } from './look.ts'
54import { askText, asHeard, candidates, cardOf, factsRow, HEARD_PATH, matches, norm, type Candidate, type Heard } from './lookup.ts'
55import { CONNECTOR, VAULT, receipt } from './receipt.ts'
56import { asApplied, asCheck, asGet, coinChange, entryAfterWrite, entryFromGet, matchEntry, moved, parseCoins, payloadOf, type Entry, type Save } from './sheet.ts'
57import { applyWrite, asManifest, asTableWrite, isSessionId, rosterRows, type TableLog } from './table.ts'
58import { frontmatter, listOf, matchGroup, pickRoster, shownRows, type PcNote, type Roster } from './roster.ts'
59import { bandTree, detailTree, heardBand, holding, hpOf, paneTree, pets, receiptTree, RULES_KEY, slotRows, TABS, tabKey, tabOf, type Adding, type Ask, type LookView, type Reread, type Screen, type TabId, type Tap } from './view.ts'
60
61const PANE = 'toa-sheet'
62const KEY = 'sheet:' // one $.store key per character, so sessions never overwrite each other's characters
63const LAST = 'last'
64const TABLE = 'table:' // one $.store key per session's log
65const SESSION = 'session'
66const FIGHT = 'party:fight' // the current fight's id; its ops are under FIGHT_LOG + id
67const FIGHT_LOG = 'party:log:' // one DM, one session: the last writer wins
68const VAULT_QUERY = 'mcp__vault__vault_query'
69const FIGHTS = 'Prep/Fights.md' // the DM's combat packs, relative to the session's folder (the vault)
70const DRAFT_WRITE: string = 'mcp__vault__draft_write' // typed wide: the vault is no tool the declarations know
71/** The person's own words for the press that raises the mod's call; the engine strips it before any tool sees it. */
72const consent = (label: string, pane: string) => `The user pressed "${label}" on the ${pane} pane`
73
74// Module state. A reload clears it; session.start refills the sheets from $.store.
75const sheets = new Map<string, Entry>()
76let focus: string | null = null
77let tab: TabId = 'actions'
78// The pane's Buttons from each surface's last drawing, handed back unchanged so
79// their press handles survive a redraw (view.ts, PaneView.memo).
80const memos = new Map<string, Map<string, RenderElement>>()
81let paneOpen = false
82let dismissed = false // the user closed the pane: do not open it unasked again this session
83let autoTried = false
84let toasted = false
85let seenHere = false // a sheet result arrived in this session (the band strip waits for one)
86// The last applied write's paths, drawn inverse in the pane until `until` (never stored).
87let flash: { id: string; paths: string[]; until: number } | null = null
88// The pane's screens, the top one drawn; `[ ‹ back ]` pops one.
89let screens: Screen[] = ['sheet']
90let session: string | null = null // the session the party view follows: `/party S04`, or the Table operation's last write
91const logs = new Map<string, TableLog>()
92let logOpen: number | null = null // the log entry drawn whole, by its index; never stored
93let reread: Reread | null = null // the last re-read's outcome, never stored
94let rereading = false
95// The live sync (T0086): the one ticking timer, the time of the last press or
96// version change (the idle stop's clock), and whether the idle stop ended it (a press restarts it).
97const TICK_MS = 20_000
98const IDLE_MS = 2 * 60 * 60_000
99let timer: { cancel: () => void } | null = null
100let quiet = 0
101let idled = false
102let writing = false // a tap's sheet_write is in flight: a tick waits
103let fightEvents: Event[] = [] // the current fight's ops and undos, as stored
104let fightId: string | null = null
105// The DM's hand on the party view, never stored: the picked row, the open number
106// field or add form.
107let sel: { row: string; member: number } | null = null
108let ask: Ask | null = null
109let adding: Adding | null = null
110// The note line under the screen on show; a screen change clears it.
111let note: string | null = null
112let packs: Pack[] | null = null // the packs screen's list, read fresh each time it opens
113// Prep/Fights.md as last read (null: no file) and every stored fight's log, by id: read on a press, never in a draw.
114let packets: ReturnType<typeof parsePacks> | null = null
115let pastLogs = new Map<string, Event[]>()
116let packet: { name: string; page: number } | null = null // the packet screen's pack, by name, and its page
117// The sheet view's taps, never stored: the open number field, and the last tap
118// written on this machine (the version it wrote over, `from`, and the one it wrote, `to`), for `u`.
119let tap: Tap | null = null
120let lastTap: { id: string; from: number; to: number } | null = null
121// The Concentration saves the server raised (patch 19) and nobody has answered, by sheet id: due now,
122// so memory only. Only this session's writes pass the watcher, so a pane sees its own session's saves.
123const saves = new Map<string, Save[]>()
124let split: string | null = null // the party's open `[ split gold ]` field, its text so far
125// Tonight's group (roster.ts): read on `/party`, matched to the cached sheets at each draw. Never stored.
126let roster: Roster | null = null
127let pcNotes: PcNote[] = []
128let showAll = false // `[ all ]` on the PARTY rule: every sheet, the group aside
129// The look (T0085), never stored: the pane it was opened from, the field's text
130// (kept for Back from a card), the open card's candidate, its fetch and page.
131type Look = { pane: 'Party' | 'Sheet'; text: string; cand: Candidate | null; loading: boolean; error: string | null; page: number }
132let look: Look | null = null
133/** The open detail box (T0093): one at a time; a screen or tab change closes it. */
134let detail: Detail | null = null
135// The hover preview (T0093 Layer 3), never stored: the word word.tsx's dwell
136// named, the term card.tsx's dwell named inside its card, the word and the
137// cards (by depth) the pointer is on, and the grace that closes what it left.
138let hover: string | null = null
139let nested: string | null = null
140let onWord: string | null = null
141const onCard = new Set<number>()
142let grace: Timer | null = null
143const GRACE_MS = 150
144// The rules server's answers, by kind and name, for the module's life: a second look draws at once and calls nothing.
145const rules = new Map<string, unknown>()
146const RULES_TOOL = /^mcp__(.+)__(spell_get|monster_get|condition_search|character_option_get)$/
147// A glossary card is drawn from GLOSSARY and calls nothing.
148const TOOL_OF: Partial<Record<Candidate['kind'], string>> = { spell: 'spell_get', monster: 'monster_get', condition: 'condition_search', option: 'character_option_get' }
149// The heard file as last read, while fresh, and the clock that reads it: started by
150// the session's first `/party`, so a player's pane never polls. Never stored.
151let heard: Heard | null = null
152let heardPoll: Timer | null = null
153
154// The receipt hook for both tool families; the mods loader takes hooks only from the top level.
155const rowHook: MatchedHook<'ui.render', { component: 'ToolUse' }> = ($, e, next) => {
156  const r = receipt(e.props, (id) => sheets.get(id)?.sheet)
157  return r ? receiptTree($.ui.resolve(e), r) : next(e)
158}
159
160const message = (err: unknown) => (err instanceof Error ? err.message : String(err))
161const focused = () => (focus ? sheets.get(focus) ?? null : null)
162const firstLine = (s: unknown) => String(s).split('\n')[0]!.slice(0, 120)
163
164function storedEntry(v: unknown): Entry | null {
165  if (!v || typeof v !== 'object') return null
166  const e = v as Entry
167  if (typeof e.id !== 'string' || typeof e.name !== 'string' || !Number.isInteger(e.version) || !e.sheet || typeof e.sheet !== 'object') return null
168  return { ...e, drift: e.drift === true, fromStore: true }
169}
170
171function storedLog(v: unknown): TableLog | null {
172  if (!v || typeof v !== 'object') return null
173  const l = v as TableLog
174  if (typeof l.session !== 'string' || !Array.isArray(l.entries)) return null
175  if (!l.entries.every((t) => t && typeof t.at === 'number' && typeof t.text === 'string')) return null
176  if (l.closedAt !== null && typeof l.closedAt !== 'number') return null
177  if (l.manifest !== null && (!l.manifest || typeof l.manifest !== 'object')) return null
178  return l
179}
180
181const int = (v: unknown) => Number.isInteger(v)
182const intOrNull = (v: unknown) => v === null || Number.isInteger(v)
183const str = (v: unknown) => typeof v === 'string'
184
185function storedOp(o: any): boolean {
186  if (!o || typeof o !== 'object') return false
187  switch (o.op) {
188    case 'add': return str(o.name) && int(o.count) && intOrNull(o.hp) && intOrNull(o.ac) && intOrNull(o.init)
189    case 'pack': return str(o.name) && Array.isArray(o.rows) && o.rows.every((r: any) => r?.op === 'add' && storedOp(r))
190    case 'init': return str(o.row) && str(o.name) && int(o.value)
191    case 'hp': return str(o.row) && int(o.member) && int(o.delta)
192    case 'kill': return str(o.row) && int(o.member)
193    case 'out': case 'point': return str(o.row)
194    case 'down': return str(o.row) && str(o.name) && typeof o.value === 'boolean'
195    case 'next': case 'end': return true
196    default: return false
197  }
198}
199
200/** A stored fight log, or null: anything else (T0055's lines among it) starts the fight empty. */
201function storedEvents(v: unknown): Event[] | null {
202  if (!Array.isArray(v)) return null
203  const ok = v.every((e) => e && typeof e === 'object' && typeof e.at === 'number' && (int(e.undo) || storedOp(e.op)))
204  return ok ? (v as Event[]) : null
205}
206
207async function loadStore($: EngineInterface) {
208  const keys: string[] = (await $.store.keys()) ?? []
209  for (const k of keys) {
210    if (k.startsWith(KEY)) {
211      const e = storedEntry(await $.store.get(k))
212      if (e && !sheets.has(e.id)) sheets.set(e.id, e)
213    } else if (k.startsWith(TABLE)) {
214      const l = storedLog(await $.store.get(k))
215      if (l && !logs.has(l.session)) logs.set(l.session, l)
216    }
217  }
218  const last = await $.store.get(LAST)
219  if (!focus && typeof last === 'string' && sheets.has(last)) focus = last
220  const stored = await $.store.get(SESSION)
221  if (!session && typeof stored === 'string') session = stored
222  const id = await $.store.get(FIGHT)
223  if (!fightId && typeof id === 'string') {
224    const events = storedEvents(await $.store.get(FIGHT_LOG + id)) ?? []
225    // Only a live fight comes back: `u` undoes an end within the sitting, never an old fight's.
226    if (live(fold(events))) {
227      fightId = id
228      fightEvents = events
229    }
230  }
231}
232
233const fight = (): Fight | null => fold(fightEvents)
234const nameOf = (id: string) => live(fight())?.rows.find((r) => r.id === id)?.name ?? sheets.get(id)?.name ?? id
235
236/** Put the keyboard on `key`; an element never drawn (no Input on mobile, the pane closed) answers deny, and the hotkeys still work. */
237async function focusOn($: EngineInterface, key: string) {
238  try {
239    await $.ui.focus({ requestId: PANE, key })
240  } catch {
241    // not drawn here
242  }
243}
244
245/** Park the ring on `next`, a Button, so the hotkeys work again: the way back from a field. */
246const park = ($: EngineInterface) => focusOn($, 'next')
247
248const top = () => screens[screens.length - 1]!
249
250/** Leave the screen on show: its open field or form and its note go; `sel` stays (a row id, re-checked against the fold). */
251function leave() {
252  ask = null
253  tap = null
254  adding = null
255  split = null
256  note = null
257}
258
259/** Back, or Esc on a pushed screen: pop one; back on the look's field, the keys go into it. */
260async function back($: EngineInterface) {
261  popScreen()
262  $.ui.invalidate('ui.render')
263  await openPane($, true)
264  if (top() === 'look') await focusOn($, 'look-field')
265}
266
267/** Show `s`: pushed, or, when it is already on the stack, the stack cut back to it. */
268function pushScreen(s: Screen) {
269  leave()
270  shut()
271  const at = screens.indexOf(s)
272  screens = at >= 0 ? screens.slice(0, at + 1) : [...screens, s]
273}
274
275function popScreen() {
276  leave()
277  shut()
278  if (screens.length > 1) screens = screens.slice(0, -1)
279}
280
281/** The stack `/sheet` and the unasked open start from: Back to Party when the party view has something to show. */
282const sheetStack = (): Screen[] =>
283  rosterRows([...sheets.values()]).length > 1 || (session && logs.has(session)) ? ['party', 'sheet'] : ['sheet']
284
285/**
286 * Where Esc (and its closing at an idle, empty prompt) has somewhere to go: an
287 * open field or form closes, an open box closes, a pushed screen steps back, a lone sheet closes.
288 * Elsewhere on `[party]` Esc hands the keys to the chat and the pane stays (T0055, T0065).
289 */
290const wantsEsc = () => !!(ask || tap || adding) || split !== null || !!detail || screens.length > 1 || top() === 'sheet'
291/** What the pane's last open asked of Esc. */
292let escOn = false
293
294/**
295 * Open the pane on the stack's top, or re-open it after a push or a pop: each
296 * open sets its arguments anew. A Party-rooted stack opens at 60 columns; Esc
297 * is set by `wantsEsc`.
298 */
299function openPane($: EngineInterface, take = false) {
300  const t = top()
301  escOn = wantsEsc()
302  return $.ui.open({
303    id: PANE,
304    title: t === 'sheet' ? focused()?.name ?? 'Sheet' : t === 'look' || t === 'card' ? 'Look up' : 'Party',
305    ...(screens[0] === 'party' ? { columns: 60 } : {}),
306    ...(escOn ? { closeOnEscape: true as const } : {}),
307    ...(take ? { focus: true as const } : {}),
308  })
309}
310
311/** Re-open the pane when a field opening or closing on `[party]` changed what Esc should do, so Esc closes the field, not hands its key to the chat. */
312async function syncEsc($: EngineInterface) {
313  if (paneOpen && escOn !== wantsEsc()) await openPane($)
314}
315
316/** Show a PC's sheet over the screen on show. */
317async function openSheet($: EngineInterface, id: string) {
318  focus = id
319  pushScreen('sheet')
320  $.ui.invalidate('ui.render')
321  await openPane($)
322}
323
324/** Esc in a field, or its `[ cancel ]`: the field or form closes and the keys go back to a Button. */
325async function cancel($: EngineInterface) {
326  const was = tap
327  leave()
328  $.ui.invalidate('ui.render')
329  await openPane($, wantsEsc())
330  return was ? focusOn($, 'tap-d') : park($)
331}
332
333/** A field's `[ apply ]`, or the form's `[ add ]`: the path Enter takes, with the text its change events kept. */
334function submit($: EngineInterface, id: string) {
335  if (id === 'amount-go') return input($, 'amount', 'submit', ask?.text ?? '')
336  if (id === 'tap-go') return input($, 'tap-amount', 'submit', tap?.text ?? '')
337  if (id === 'split-go') return input($, 'split-amount', 'submit', split ?? '')
338  return input($, 'add-init', 'submit', adding?.init ?? '')
339}
340
341/**
342 * One op pressed (or `undo`): stored and drawn. An op that starts a new fight
343 * starts a new log; the old one stays in the store.
344 */
345async function apply($: EngineInterface, op: Op | 'undo') {
346  const at = await $.clock.now()
347  let event: Event
348  if (op === 'undo') {
349    const target = undoTarget(fightEvents)
350    if (target === null) {
351      note = 'nothing to undo'
352      return $.ui.invalidate('ui.render')
353    }
354    event = { at, undo: target }
355  } else event = { at, op }
356  fightEvents = [...fightEvents, event]
357  const f = fight()
358  if (f && f.id !== fightId) {
359    fightEvents = [event]
360    fightId = f.id
361    await $.store.set(FIGHT, fightId)
362  }
363  if (fightId) await $.store.set(FIGHT_LOG + fightId, fightEvents)
364  const row = sel && live(f)?.rows.find((r) => r.id === sel!.row)
365  sel = row && sel ? { row: row.id, member: Math.max(0, Math.min(sel.member, row.members.length - 1)) } : null
366  note = null
367  ask = null
368  $.ui.invalidate('ui.render')
369  await park($)
370}
371
372/**
373 * `[ next turn ]` or `[ turn ]`: apply the op, and when it starts a new round re-read the sheets, so HP the
374 * players wrote shows. Awaited, as `[ re-read ]`'s is: the mod's own watcher sees only the calls made
375 * while the press is in flight.
376 */
377async function turn($: EngineInterface, op: Op, label: string) {
378  const was = fight()?.round ?? 0
379  await apply($, op)
380  if ((fight()?.round ?? 0) > was && (await refresh($, consent(label, 'Party') + ', which starts a new round and re-reads', true))) await startSync($)
381}
382
383/** The note line under the party's order or the sheet's taps. */
384const say = ($: EngineInterface, text: string) => {
385  note = text
386  $.ui.invalidate('ui.render')
387}
388
389/**
390 * The ended fight `f` (its fold before the end) as one Table note, through
391 * `draft_write`. Run after the end is applied and never awaited, so the press
392 * never waits on a permission dialog; a line not logged says why in the note.
393 */
394async function logFight($: EngineInterface, f: Fight) {
395  const not = (why: string) => say($, 'fight ended; not logged: ' + why)
396  const text = summary(f)
397  if (!text) return not('nothing tracked')
398  const s = session
399  if (!s) return not('no session (/party S04)')
400  let why: string
401  try {
402    if (!(await $.tool.list()).some((t) => t.name === DRAFT_WRITE)) return not('no vault connector')
403    // Top-level arguments, as draft_write takes them; the watcher sees the call and logs the line.
404    const r = await $.tool.call({ tool: DRAFT_WRITE, kind: 'table-note', session: s, text, consent: consent('end fight', 'Party') } as ToolCallArgs)
405    if (!('deny' in r) && !r.isError) return
406    why = firstLine('deny' in r ? r.deny : r.text)
407  } catch (err) {
408    why = firstLine(message(err))
409  }
410  $.ui.log('fight: draft_write refused: ' + why)
411  not(why)
412}
413
414/**
415 * A press on the party view: a row's name targets it, or opens a Party PC's
416 * sheet; a member's HP targets that member; `[ init ]` beside a PC asks its
417 * initiative; a button under the row acts on the targeted one.
418 */
419async function act($: EngineInterface, key: string) {
420  ask = null
421  const f = live(fight())
422  if (key.startsWith('row-')) {
423    const id = key.slice(4)
424    if (!f?.rows.some((r) => r.id === id) && sheets.has(id)) return openSheet($, id)
425    sel = { row: id, member: 0 }
426    return $.ui.invalidate('ui.render')
427  }
428  if (key.startsWith('mem-')) {
429    const m = /^mem-(.+)-(\d+)$/.exec(key)
430    if (m) sel = { row: m[1]!, member: Number(m[2]) }
431    return $.ui.invalidate('ui.render')
432  }
433  if (key.startsWith('init-')) sel = { row: key.slice(5), member: 0 }
434  if (key === 'act-stats') {
435    // `sel` stays: Back returns to the row targeted.
436    const r = sel && f?.rows.find((x) => x.id === sel!.row)
437    if (!r || r.side === 'pc') return say($, 'no stats for this row')
438    const name = monsterName(r.name)
439    look = null
440    return openCard($, { name, kind: 'monster', key: norm(name) }, consent('stats: ' + name, 'Party'), 'Party')
441  }
442  if (key === 'act-c') return openPacks($)
443  if (key === 'act-packet') return openPacket($)
444  if (key === 'act-nextpack') {
445    await readPackets($)
446    const p = packets && nextPack(packets.packs, session, lastPack(fightLogs()))
447    return p ? apply($, { op: 'pack', name: p.name, rows: p.rows }) : openPacks($)
448  }
449  if (key.startsWith('pack-')) {
450    const p = packs?.[Number(key.slice(5)) - 1]
451    if (!p) return
452    packs = null
453    pushScreen('party')
454    await openPane($)
455    return apply($, { op: 'pack', name: p.name, rows: p.rows })
456  }
457  if (key === 'act-a') {
458    adding = adding ? null : { name: '', count: '', hp: '', ac: '', init: '' }
459    $.ui.invalidate('ui.render')
460    return adding ? focusOn($, 'add-name') : undefined
461  }
462  if (key === 'act-f') {
463    if (!f) return
464    await apply($, { op: 'end' })
465    void logFight($, f)
466    await readPackets($)
467    return $.ui.invalidate('ui.render')
468  }
469  if (!sel) return say($, 'pick a row first')
470  if (key === 'act-s') return sheets.has(sel.row) ? openSheet($, sel.row) : say($, 'no sheet')
471  const { row: id, member } = sel
472  const row = f?.rows.find((r) => r.id === id)
473  if (key === 'act-i' || key.startsWith('init-')) {
474    ask = { kind: 'init', row: id, member, text: '' }
475    $.ui.invalidate('ui.render')
476    return focusOn($, 'amount')
477  }
478  if (!f) return
479  const tracked = !!row && row.members.length > 0
480  if (key === 'act-d' || key === 'act-h') {
481    if (!tracked) return say($, 'no HP tracked here')
482    ask = { kind: key === 'act-d' ? 'damage' : 'heal', row: id, member, text: '' }
483    $.ui.invalidate('ui.render')
484    return focusOn($, 'amount')
485  }
486  if (key === 'act-x') return tracked ? apply($, { op: 'kill', row: id, member }) : say($, 'no HP tracked here')
487  if (key === 'act-o') return row ? apply($, { op: 'out', row: id }) : say($, 'not in the fight')
488  if (key === 'act-k') return apply($, { op: 'down', row: id, name: nameOf(id), value: !row?.down })
489  if (key === 'act-t') return row ? turn($, { op: 'point', row: id }, 'turn') : say($, 'not in the fight')
490}
491
492const SESSIONS = 'Sessions' // the session notes, Sxx.md, for `present:`
493const PREP = 'Prep' // the prep docs, for `sessions:` and `party:`
494const PCS = 'Lore/Party' // the PC notes, for `aliases:`
495
496/** A file's text, or null when it cannot be read. */
497async function readOr($: EngineInterface, path: string): Promise<string | null> {
498  try {
499    return await $.fs.read(path)
500  } catch {
501    return null
502  }
503}
504
505/** The `.md` files directly in `dir`, by path; none when it cannot be listed. */
506async function mdFiles($: EngineInterface, dir: string): Promise<{ path: string; md: string }[]> {
507  let names: string[]
508  try {
509    names = (await $.fs.list(dir)).filter((f) => f.kind === 'file' && f.name.endsWith('.md')).map((f) => f.name)
510  } catch {
511    return []
512  }
513  const out: { path: string; md: string }[] = []
514  for (const name of names) {
515    const md = await readOr($, `${dir}/${name}`)
516    if (md !== null) out.push({ path: `${dir}/${name}`, md })
517  }
518  return out
519}
520
521/** Tonight's group for the session on show (roster.ts `pickRoster`), and the PC notes' aliases to match it with. */
522async function readRoster($: EngineInterface, typed: string[]) {
523  showAll = false
524  if (!session) {
525    roster = typed.length ? { source: 'args', from: null, names: typed, warning: null } : null
526  } else {
527    const path = `${SESSIONS}/${session}.md`
528    const md = await readOr($, path)
529    roster = pickRoster(md === null ? null : { path, md }, await mdFiles($, PREP), typed, session)
530  }
531  pcNotes = roster ? (await mdFiles($, PCS)).map((f) => ({ name: f.path.slice(PCS.length + 1, -3), aliases: listOf(frontmatter(f.md).aliases) })) : []
532}
533
534/** The group as drawn: the cached sheets it names and the names none does; null with no roster. */
535const groupNow = () => (roster ? matchGroup(rosterRows([...sheets.values()]), roster.names, pcNotes) : null)
536/** The party view's rows: the group's unless `[ all ]`. */
537const partyRows = () => shownRows(rosterRows([...sheets.values()]), groupNow(), showAll)
538
539/** Read Prep/Fights.md fresh, and every stored fight's log, for `[ next ]`. */
540async function readPackets($: EngineInterface) {
541  try {
542    packets = parsePacks(await $.fs.read(FIGHTS))
543  } catch {
544    packets = null // no file
545  }
546  const keys: string[] = (await $.store.keys()) ?? []
547  pastLogs = new Map()
548  for (const k of keys) {
549    if (!k.startsWith(FIGHT_LOG)) continue
550    const events = storedEvents(await $.store.get(k))
551    if (events) pastLogs.set(k.slice(FIGHT_LOG.length), events)
552  }
553}
554
555/** The fights' logs, newest first: the stored ones as last read, the current one as it is now. */
556function fightLogs(): Event[][] {
557  const all = new Map(pastLogs)
558  if (fightId) all.set(fightId, fightEvents)
559  const num = (id: string) => Number(id.slice(1)) || 0
560  return [...all.keys()].sort((a, b) => num(b) - num(a)).map((id) => all.get(id)!)
561}
562
563/** A pack by name: the session's first, then the whole file's. */
564const packNamed = (name: string) => {
565  const all = packets?.packs ?? []
566  return sessionPacks(all, session).find((p) => p.name === name) ?? all.find((p) => p.name === name) ?? null
567}
568
569/** `[ packs ]`: the packs screen, from Prep/Fights.md read fresh; with none, the screen says why. */
570async function openPacks($: EngineInterface) {
571  await readPackets($)
572  const read = packets
573  pushScreen('packs')
574  packs = read?.packs.length ? read.packs : null
575  // A pack that does not read is left out of the list; the note names its line.
576  note = !read ? 'no ' + FIGHTS : read.errors[0] ?? (packs ? null : 'no packs in ' + FIGHTS)
577  $.ui.invalidate('ui.render')
578  await openPane($)
579}
580
581/** `[ packet ]`: the notes of the pack loaded last into the fight on show, from Prep/Fights.md read fresh. */
582async function openPacket($: EngineInterface) {
583  await readPackets($)
584  const name = fight()?.packs.at(-1)
585  if (!name) return
586  if (!packNamed(name)) return say($, `no pack "${name}" in ${FIGHTS}`)
587  packet = { name, page: 0 }
588  pushScreen('packet')
589  $.ui.invalidate('ui.render')
590  await openPane($)
591}
592
593/** A row's monster: its name, a typed ` 2` dropped. */
594const monsterName = (name: string) => name.replace(/ \d+$/, '')
595/** The monsters a look can open: the fight's rows and the packs read, if any. */
596const monsterNames = () => [
597  ...(fight()?.rows ?? []).filter((r) => r.side !== 'pc').map((r) => monsterName(r.name)),
598  ...(packs ?? []).flatMap((p) => p.rows.map((r) => r.name)),
599]
600const lookMatches = () => (look ? matches(look.text, candidates(monsterNames())) : [])
601const cacheKey = (c: Candidate) => c.kind + '|' + (c.kind === 'option' ? c.key : norm(c.name))
602
603/** The look as drawn, while its screens show. */
604function lookView(): LookView | null {
605  const t = top()
606  if (!look || (t !== 'look' && t !== 'card')) return null
607  const card = look.cand ? cardOf(look.cand, rules.get(cacheKey(look.cand)) ?? null, factsRow(look.cand)) : null
608  return { text: look.text, matches: t === 'look' ? lookMatches() : [], card, loading: look.loading, error: look.error, page: look.page }
609}
610
611/** `[ look up ]`: the field, empty, over the screen on show, with the keys in it. */
612async function openLook($: EngineInterface) {
613  look = { pane: top() === 'sheet' ? 'Sheet' : 'Party', text: '', cand: null, loading: false, error: null, page: 0 }
614  pushScreen('look')
615  $.ui.invalidate('ui.render')
616  await openPane($)
617  await focusOn($, 'look-field')
618}
619
620/**
621 * A match, Enter's top match or `[ stats ]`: the card, drawn at once from what
622 * is known (a spell's facts row, a cached answer), then fetched once, on this
623 * press, never ahead of it.
624 */
625async function openCard($: EngineInterface, cand: Candidate, said: string, pane: Look['pane']) {
626  look = { pane, text: look?.text ?? '', cand, loading: false, error: null, page: 0 }
627  pushScreen('card')
628  $.ui.invalidate('ui.render')
629  await openPane($)
630  const k = cacheKey(cand)
631  if (cand.kind === 'glossary' || rules.has(k) || look?.cand !== cand) return
632  look = { ...look, loading: true }
633  $.ui.invalidate('ui.render')
634  const got = await fetchRules($, cand, said)
635  if ('payload' in got) rules.set(k, got.payload)
636  if (look?.cand !== cand) return // the person moved on; the answer is kept for next time
637  look = { ...look, loading: false, error: 'error' in got ? got.error : null }
638  $.ui.invalidate('ui.render')
639}
640
641/**
642 * The rules server's answer for `cand`: the tool found as the re-read finds
643 * `sheet_read` (a cached sheet's server first), its arguments top level.
644 * A condition is searched and the result named exactly is taken.
645 */
646async function fetchRules($: EngineInterface, cand: Candidate, said: string): Promise<{ payload: unknown } | { error: string }> {
647  try {
648    const names = (await $.tool.list()).map((t) => t.name)
649    const want = TOOL_OF[cand.kind]
650    if (!want) return { error: 'nothing to fetch for ' + cand.name }
651    const known = [...sheets.values()].map((e) => `mcp__${e.server}__${want}`).find((n) => names.includes(n))
652    const tool = known ?? names.find((n) => RULES_TOOL.exec(n)?.[2] === want)
653    if (!tool) return { error: 'no rules tool in this session: add the rules connector' }
654    let args: object = { tool, name: cand.name, consent: said }
655    if (cand.kind === 'condition') args = { tool, query: cand.name, limit: 5, consent: said }
656    if (cand.kind === 'option') {
657      const [kind, name, feature] = cand.key.split('|')
658      args = { tool, kind, name, ...(feature ? { feature } : {}), consent: said }
659    }
660    // The name is found at run time, so it is no literal the declarations know.
661    const r = await $.tool.call(args as ToolCallArgs)
662    if ('deny' in r) return { error: firstLine(r.deny) }
663    if (r.isError) return { error: firstLine(r.text) }
664    const p = payloadOf(r)
665    if (!p || !('data' in p) || !p.data || typeof p.data !== 'object') return { error: 'unexpected answer from ' + tool }
666    if (cand.kind !== 'condition') return { payload: p.data }
667    const hit = ((p.data as { results?: unknown[] }).results ?? []).find((x: any) => norm(String(x?.name ?? '')) === norm(cand.name))
668    return hit ? { payload: hit } : { error: 'no ' + cand.name + ' on the rules server' }
669  } catch (err) {
670    return { error: firstLine(message(err)) }
671  }
672}
673
674/**
675 * A word's press, from word.tsx's post or the fallback Button: a `w:c:` word
676 * opens its card (fetched, as a look's match); any other opens, nests or
677 * closes its box.
678 */
679async function pressed($: EngineInterface, key: string) {
680  const cand = wordCard(key)
681  const pane = top() === 'sheet' ? 'Sheet' : 'Party'
682  if (cand) return openCard($, cand, consent('look up: ' + cand.name, pane), pane)
683  detail = pressWord(detail, key)
684  $.ui.invalidate('ui.render')
685}
686
687/** The box and the preview close: a screen or tab change, Esc, `[ × ]`. */
688function shut() {
689  detail = hover = nested = onWord = null
690  onCard.clear()
691  grace?.cancel()
692  grace = null
693}
694
695/**
696 * A click on the preview (or its word): it locks where it stands, a pinned box
697 * drawn above the word; at depth 2 the nested card's term is pinned on its path.
698 */
699function pin(depth: number) {
700  if (!detail?.above && hover) detail = { anchor: hover, path: [hover], above: true }
701  if (depth === 2 && detail?.above && nested) detail = pressWord(detail, nested)
702  hover = nested = null
703  onCard.clear()
704  grace?.cancel()
705  grace = null
706}
707
708/** The grace after the pointer leaves a word or card: what it has not come back to closes. */
709function later($: EngineInterface) {
710  grace?.cancel()
711  grace = null
712  if (!hover && !nested) return
713  grace = $.clock.after(GRACE_MS, () => {
714    grace = null
715    const was = [hover, nested]
716    if (!onCard.has(2)) nested = null
717    if (onWord !== hover && !onCard.size) hover = nested = null
718    if (hover === was[0] && nested === was[1]) return
719    $.ui.invalidate('ui.render')
720    void syncEsc($)
721  })
722}
723
724/** A path's last card as a preview shows it: a fetch word's cached card (hover never fetches), else its box, untitled by its path. */
725function glance(path: string[], rows: Entry[], entry: Entry | null, now: number): Content | null {
726  const k = path.at(-1)!
727  const cand = wordCard(k)
728  if (cand) return fetchPreview(cand, rules.has(cacheKey(cand)) ? cardOf(cand, rules.get(cacheKey(cand)), factsRow(cand)) : null)
729  const c = detailAt(path, rows, entry, now)
730  return c && { ...c, title: c.title.split(' › ').at(-1)!, back: false }
731}
732
733/** The preview as drawn: the pinned box or the hovered word's card, and the term's card dwelt on inside it. */
734function previewView(rows: Entry[], entry: Entry | null, now: number): Preview | null {
735  const pinned = !!detail?.above
736  const base = pinned ? detail!.path : hover ? [hover] : null
737  if (!base) return null
738  const top = pinned ? detailAt(base, rows, entry, now) : glance(base, rows, entry, now)
739  if (!top) return null
740  const to = nested && (nested.startsWith('w:n:') ? 'w:' + nested.slice('w:n:'.length) : nested)
741  return { anchor: pinned ? detail!.anchor : hover!, top, nested: to ? glance([...base, to], rows, entry, now) : null, pinned }
742}
743
744/**
745 * `[ ask Claude ]`: the subject (the card's title and cite, or the field's
746 * text) as a prompt of this session, fired and not awaited (it runs once the
747 * session is idle). The look closes and the note says so at once.
748 */
749async function askClaude($: EngineInterface) {
750  if (!look) return
751  const card = top() === 'card' ? lookView()?.card ?? null : null
752  const subject = card ? { title: card.title, cite: card.cite } : look.text.trim()
753  if (!subject) return
754  void $.prompt.submit({ text: askText({ subject, pane: look.pane, session, tail: look.pane === 'Party' ? heard?.tail : null }) }).catch(() => {})
755  const at = screens.findIndex((s) => s === 'look' || s === 'card')
756  leave()
757  shut()
758  screens = screens.slice(0, Math.max(1, at))
759  look = null
760  await openPane($)
761  say($, 'asked Claude')
762}
763
764/** `[ ask Claude about what was just said ]`: the party pane's question, with the heard file's last minute. */
765function askHeard($: EngineInterface) {
766  void $.prompt.submit({ text: askText({ subject: 'rule on what was just said', pane: 'Party', session, tail: heard?.tail }) }).catch(() => {})
767  say($, 'asked Claude')
768}
769
770/** One tick of the heard poll: the file read (missing is none), redrawn only when its `updated` changed. */
771async function readHeard($: EngineInterface) {
772  let raw: string | null = null
773  try {
774    raw = await $.fs.read(HEARD_PATH)
775  } catch {}
776  const got = asHeard(raw, await $.clock.now())
777  if ((got?.updated ?? null) === (heard?.updated ?? null)) return
778  heard = got
779  $.ui.invalidate('ui.render')
780}
781
782const ADD_FIELDS = ['name', 'count', 'hp', 'ac', 'init'] as const
783/** A numeric add field: an integer, or null when blank (or not a number). */
784const num = (t: string) => (/^\d+$/.test(t.trim()) ? Number(t.trim()) : null)
785
786/** The number field and the add form: a change is drawn back; a submit applies or moves on. */
787async function input($: EngineInterface, element: string, kind: 'change' | 'submit', value: string) {
788  if (element === 'look-field' && look) {
789    look = { ...look, text: value }
790    // A change narrows the matches; Enter opens the top one, and with none does nothing more (never asks).
791    const hit = kind === 'submit' ? lookMatches()[0] : undefined
792    if (hit) return openCard($, hit, consent('look up: ' + hit.name, look.pane), look.pane)
793    return $.ui.invalidate('ui.render')
794  }
795  if (element === 'tap-amount' && tap) {
796    // Drawn back on every change: the host keeps a field's typing until the hook draws a different value.
797    if (kind === 'change') {
798      tap = { ...tap, text: value }
799      return $.ui.invalidate('ui.render')
800    }
801    const t = value.trim()
802    if (!t) {
803      tap = null
804      $.ui.invalidate('ui.render')
805      return focusOn($, 'tap-d')
806    }
807    tap = { ...tap, text: value }
808    if (tap.kind === 'coins') return coins($, t)
809    const n = num(t)
810    if (n === null) {
811      note = 'a number'
812      return $.ui.invalidate('ui.render')
813    }
814    return hp($, n, value)
815  }
816  if (element === 'amount' && ask) {
817    if (kind === 'change') {
818      ask = { ...ask, text: value }
819      return $.ui.invalidate('ui.render')
820    }
821    const t = value.trim()
822    if (!t) {
823      ask = null
824      $.ui.invalidate('ui.render')
825      return park($)
826    }
827    const n = num(t)
828    if (n === null) {
829      ask = { ...ask, text: value }
830      note = 'a number'
831      return $.ui.invalidate('ui.render')
832    }
833    const { kind: what, row, member } = ask
834    return apply($, what === 'init' ? { op: 'init', row, name: nameOf(row), value: n } : { op: 'hp', row, member, delta: what === 'damage' ? -n : n })
835  }
836  if (element === 'split-amount' && split !== null) {
837    split = value
838    if (kind === 'change') return $.ui.invalidate('ui.render')
839    if (!value.trim()) {
840      split = null
841      $.ui.invalidate('ui.render')
842      return park($)
843    }
844    return splitGold($, value.trim())
845  }
846  const field = ADD_FIELDS.find((k) => element === 'add-' + k)
847  if (!field || !adding) return
848  adding = { ...adding, [field]: value }
849  if (kind === 'change') return $.ui.invalidate('ui.render')
850  if (field !== 'init') return focusOn($, 'add-' + ADD_FIELDS[ADD_FIELDS.indexOf(field) + 1])
851  const name = adding.name.trim()
852  if (!name) {
853    note = 'a name'
854    $.ui.invalidate('ui.render')
855    return focusOn($, 'add-name')
856  }
857  const op: Op = { op: 'add', name: name.charAt(0).toUpperCase() + name.slice(1), count: Math.max(1, num(adding.count) ?? 1), hp: num(adding.hp), ac: num(adding.ac), init: num(adding.init) }
858  adding = null
859  await apply($, op)
860  const added = fight()?.rows.find((r) => r.added === fightEvents.length - 1)
861  if (added) sel = { row: added.id, member: 0 }
862  $.ui.invalidate('ui.render')
863}
864
865/** A tap key on the sheet view: `d`/`h` open the number field, `u` undoes the last tap, a slot's digit spends one. */
866async function tapKey($: EngineInterface, key: string) {
867  const entry = focused()
868  if (!entry) return
869  if (key === 'tap-d' || key === 'tap-h') {
870    tap = { kind: key === 'tap-d' ? 'damage' : 'heal', text: '' }
871    $.ui.invalidate('ui.render')
872    return focusOn($, 'tap-amount')
873  }
874  if (key === 'tap-c') {
875    tap = { kind: 'coins', text: '' }
876    $.ui.invalidate('ui.render')
877    return focusOn($, 'tap-amount')
878  }
879  if (key === 'tap-u') {
880    if (!lastTap || lastTap.id !== entry.id) return say($, 'nothing to undo')
881    if (entry.version !== lastTap.to) return say($, 'the sheet changed since: undo in the chat')
882    return write($, entry, { action: 'revert', changes: { version: lastTap.from } }, 'sheet pane: undo', consent('undo', 'Sheet'))
883  }
884  const slot = slotRows(entry).find((s) => s.key === key)
885  if (!slot) return
886  const pact = key === 'slot-pact'
887  const name = pact ? 'pact' : slot.label
888  if (slot.left <= 0) return say($, `no ${name} slots left`)
889  const spell = entry.sheet.spellcasting ?? {}
890  const used = Number(pact ? spell.pact_slots_used ?? 0 : spell.slots_used?.[String(slot.level)] ?? 0)
891  const changes = pact ? { spellcasting: { pact_slots_used: used + 1 } } : { spellcasting: { slots_used: { [String(slot.level)]: used + 1 } } }
892  return write($, entry, { action: 'update', changes }, `sheet pane: ${name} slot`, consent(slot.label, 'Sheet'))
893}
894
895/**
896 * A Concentration spell's `CONC` (`conc-<i>`, the row's index on the actions tab): it writes
897 * the field, spell and source both (a merge patch keeps what it does not name); on the held
898 * spell, `HOLDING`, it writes null, which ends it.
899 */
900async function concentrate($: EngineInterface, key: string) {
901  const entry = focused()
902  const row = entry ? actionGroups(entry, new Map(), () => false).flatMap((g) => g.rows)[Number(key.slice(5))] : undefined
903  if (!entry || !row) return
904  const changes = holding(entry, row) ? { concentration: null } : { concentration: { spell: row.name, source: row.source || null } }
905  return write($, entry, { action: 'update', changes }, 'sheet pane: concentrate', consent('concentrate · ' + row.name, 'Sheet'))
906}
907
908/** A save line's `[ held ]` (`held-<id>-<k>`) drops it here; `[ lost ]` (`lost-<id>-<k>`) ends the sheet's Concentration. */
909async function answerSave($: EngineInterface, key: string) {
910  const [, verb, id = '', k] = /^(held|lost)-(.+)-(\d+)$/.exec(key) ?? []
911  const entry = sheets.get(id)
912  if (!entry) return
913  if (verb === 'held') {
914    const left = (saves.get(id) ?? []).filter((_, i) => i !== Number(k))
915    if (left.length) saves.set(id, left)
916    else saves.delete(id)
917    $.ui.invalidate('ui.render')
918    return
919  }
920  const pane = top() === 'sheet' ? 'Sheet' : 'Party'
921  return write($, entry, { action: 'update', changes: { concentration: null } }, 'sheet pane: lost concentration', consent('lost · ' + entry.name, pane))
922}
923
924/**
925 * A pets-tab or gear-tab press. `comp-d`/`comp-h` open the number field for
926 * that companion; `comp-u` spends one use, `comp-s` dismisses or summons back,
927 * `comp-x` removes it (undo brings it back); `eq-<row>` equips or unequips an
928 * item. Each write is a JSON Patch that first tests the companion's id or the
929 * item's name at that index, so a stale pane cannot change the wrong one.
930 */
931async function petKey($: EngineInterface, key: string) {
932  const entry = focused()
933  if (!entry) return
934  const eq = /^eq-(\d+)$/.exec(key)
935  if (eq) {
936    const n = Number(eq[1])
937    const item = (entry.sheet.inventory ?? [])[n]
938    if (!item) return
939    const worn = inSlot(entry).has(String(item.name)) && item.equipped !== false
940    const changes = [{ op: 'test', path: `/inventory/${n}/name`, value: item.name }, { op: 'add', path: `/inventory/${n}/equipped`, value: !worn }]
941    return write($, entry, { action: 'update', changes }, `sheet pane: ${worn ? 'unequip' : 'equip'} ${item.name}`, consent(`${worn ? 'unequip' : 'equip'} · ${item.name}`, 'Sheet'))
942  }
943  const [, verb = '', i = '', j] = /^comp-([dhusx])-(\d+)(?:-(\d+))?$/.exec(key) ?? []
944  const p = pets(entry)[Number(i)]
945  if (!p) return
946  if (verb === 'd' || verb === 'h') {
947    tap = { kind: verb === 'd' ? 'damage' : 'heal', text: '', companion: { index: p.index, name: p.name } }
948    $.ui.invalidate('ui.render')
949    return focusOn($, 'tap-amount')
950  }
951  const test = { op: 'test', path: `/companions/${p.index}/id`, value: p.id }
952  if (verb === 'u') {
953    const r = p.resources[Number(j)]
954    if (!r) return
955    if (r.max !== null && r.used >= r.max) return say($, `no ${r.name} left`)
956    // A use that mends the companion (Repair): the number field takes the roll; apply spends the use and heals.
957    if (r.heal && r.self) {
958      tap = { kind: 'heal', text: '', companion: { index: p.index, name: p.name, use: { index: Number(j), label: `${r.name} ${r.heal}` } } }
959      $.ui.invalidate('ui.render')
960      return focusOn($, 'tap-amount')
961    }
962    const changes = [test, { op: 'replace', path: `/companions/${p.index}/resources/${j}/used`, value: r.used + 1 }]
963    await write($, entry, { action: 'update', changes }, `sheet pane: ${p.name} ${r.name}`, consent(`use · ${p.name} · ${r.name}`, 'Sheet'))
964    // A heal for another creature: the use is spent here, the roll goes to whoever it heals.
965    if (r.heal) say($, `${r.name}: the target regains ${r.heal}`)
966    return
967  }
968  if (verb === 's') {
969    const to = p.status === 'dismissed' ? 'present' : 'dismissed'
970    const changes = [test, { op: 'add', path: `/companions/${p.index}/status`, value: to }]
971    return write($, entry, { action: 'update', changes }, `sheet pane: ${to === 'present' ? 'summon' : 'dismiss'} ${p.name}`, consent(`${to === 'present' ? 'summon' : 'dismiss'} · ${p.name}`, 'Sheet'))
972  }
973  const changes = [test, { op: 'remove', path: `/companions/${p.index}` }]
974  return write($, entry, { action: 'update', changes }, `sheet pane: remove ${p.name}`, consent(`remove · ${p.name}`, 'Sheet'))
975}
976
977/** Item names in the server's slots (armour, shield, hands). */
978function inSlot(entry: Entry): Set<string> {
979  const eq = entry.derived?.equipment
980  if (!eq) return new Set()
981  return new Set([eq.armor, eq.shield, ...((eq.hands?.items ?? []) as { name: string }[]).map((h) => h.name)].filter((n): n is string => typeof n === 'string'))
982}
983
984/** A companion's damage or healing: temp HP first, then HP; healing up to its derived max. The server downs or removes it at 0. */
985async function petHp($: EngineInterface, entry: Entry, n: number, typed: string) {
986  const c = tap?.companion
987  const p = c ? pets(entry)[c.index] : undefined
988  if (!tap || !c || !p || p.name !== c.name) return say($, 'that companion is gone')
989  const damage = tap.kind === 'damage'
990  const max = p.max ?? Infinity
991  const use = c.use ? p.resources[c.use.index] : undefined
992  if (c.use && (!use || (use.max !== null && use.used >= use.max))) return say($, `no ${use?.name ?? 'uses'} left`)
993  if (n === 0 || (!damage && !use && p.current >= max)) return say($, 'nothing to change')
994  const t = damage ? Math.min(p.temp, n) : 0
995  const hp = damage ? { current: Math.max(0, p.current - (n - t)), temp: p.temp - t } : { current: Math.min(max, p.current + n), temp: p.temp }
996  const changes = [
997    { op: 'test', path: `/companions/${p.index}/id`, value: p.id },
998    { op: 'add', path: `/companions/${p.index}/hp`, value: hp },
999    ...(use ? [{ op: 'replace', path: `/companions/${p.index}/resources/${c.use!.index}/used`, value: use.used + 1 }] : []),
1000  ]
1001  const label = c.use?.label ?? tap.kind
1002  const said = `The user entered "${typed.trim()}" in "${label} · ${p.name}" on the Sheet pane and pressed apply`
1003  return write($, entry, { action: 'update', changes }, `sheet pane: ${p.name} ${use ? use.name + ' ' : ''}${damage ? '−' : '+'}${n} HP`, said)
1004}
1005
1006/** The number field's `n`: damage spends temp HP first, then HP down to 0; healing raises HP up to the max the pane draws. */
1007async function hp($: EngineInterface, n: number, typed: string) {
1008  const entry = focused()
1009  if (!entry || !tap) return
1010  if (tap.companion) return petHp($, entry, n, typed)
1011  const { current, max, temp } = hpOf(entry)
1012  const damage = tap.kind === 'damage'
1013  if (n === 0 || (damage && current <= 0 && temp <= 0) || (!damage && current >= max)) return say($, 'nothing to change')
1014  const t = damage ? Math.min(temp, n) : 0
1015  const changes = damage
1016    ? { hp: { current: Math.max(0, current - (n - t)), ...(t ? { temp: temp - t } : {}) } }
1017    : { hp: { current: Math.min(max, current + n) } }
1018  const said = `The user entered "${typed.trim()}" in "${tap.kind} · ${entry.name}" on the Sheet pane and pressed apply`
1019  return write($, entry, { action: 'update', changes }, `sheet pane: ${damage ? '−' : '+'}${n} HP`, said)
1020}
1021
1022/** The coins field's `+50` or `-5 sp`: one coin of the sheet on show, compare-and-set (sheet.ts `coinChange`). */
1023async function coins($: EngineInterface, typed: string) {
1024  const entry = focused()
1025  if (!entry || !tap) return
1026  const c = parseCoins(typed)
1027  if ('refused' in c) return say($, c.refused)
1028  if (c.delta === 0) return say($, 'nothing to change')
1029  const change = coinChange(entry.sheet, entry.name, c.coin, c.delta)
1030  if ('refused' in change) return say($, change.refused)
1031  const said = `The user entered "${typed}" in "coins · ${entry.name}" on the Sheet pane and pressed apply`
1032  return write($, entry, { action: 'update', changes: change.changes }, `sheet pane: ${c.delta < 0 ? '−' : '+'}${Math.abs(c.delta)} ${c.coin}`, said)
1033}
1034
1035/**
1036 * `[ split gold ]`'s amount: paid out evenly to the PCs the party view shows (tonight's group, or all with `[ all ]`), one write at a
1037 * time, the remainder named. A refusal stops it, naming who was paid; each
1038 * write is its own, so `[ undo ]` on a sheet undoes only the last.
1039 */
1040async function splitGold($: EngineInterface, typed: string) {
1041  if (typed.startsWith('-')) return say($, 'split pays out; spend per row')
1042  const c = parseCoins(typed.startsWith('+') ? typed : '+' + typed)
1043  if ('refused' in c) return say($, c.refused)
1044  const pcs = partyRows()
1045  const each = Math.floor(c.delta / Math.max(1, pcs.length))
1046  if (each < 1) return say($, pcs.length ? `${c.delta} ${c.coin} is less than 1 each` : 'no sheets to pay')
1047  const said = `The user entered "${typed}" in "split gold · party" on the Party pane and pressed apply`
1048  const paid: string[] = []
1049  for (const pc of pcs) {
1050    const change = coinChange(pc.sheet, pc.name, c.coin, each)
1051    if ('refused' in change) return say($, change.refused)
1052    // write() leaves the note empty when it applied, and says why when it did not.
1053    await write($, pc, { action: 'update', changes: change.changes }, `sheet pane: split +${each} ${c.coin}`, said)
1054    if (note) return say($, `paid ${paid.join(', ') || 'nobody'}; stopped at ${pc.name}: ${note}`)
1055    paid.push(pc.name)
1056  }
1057  split = null
1058  say($, `${each} ${c.coin} each to ${pcs.map((p) => p.name).join(', ')} · ${c.delta - each * pcs.length} ${c.coin} left over`)
1059  await syncEsc($)
1060  return park($)
1061}
1062
1063/**
1064 * One tap's `sheet_write`, applied at once at the pane's version: the
1065 * connector's `base_version` guard is the stale check. The watcher caches and
1066 * flashes the result; a refusal or an error is the note, and the field stays.
1067 */
1068async function write($: EngineInterface, entry: Entry, body: Record<string, unknown>, reason: string, said: string) {
1069  const tool = 'mcp__' + entry.server + '__sheet_write'
1070  const from = entry.version
1071  writing = true
1072  try {
1073    // The name is built at run time, so it is no literal the declarations know.
1074    const r = await $.tool.call({ tool, request: { ...body, character: entry.id, base_version: from, reason }, apply: true, consent: said } as ToolCallArgs)
1075    if ('deny' in r) {
1076      $.ui.log(`tap: ${tool} refused: ` + firstLine(r.deny))
1077      return say($, `refused: allow ${tool} (/permissions)`)
1078    }
1079    if (r.isError) {
1080      if (!/sheet changed/i.test(String(r.text))) return say($, firstLine(r.text))
1081      // The watcher re-caches the sheet, so the next Enter recomputes at its version.
1082      const read = 'mcp__' + entry.server + '__sheet_read'
1083      await $.tool.call({ tool: read, request: { action: 'get', character: entry.id }, consent: said } as ToolCallArgs)
1084      return say($, 'the sheet changed · try again')
1085    }
1086    const p = payloadOf(r)
1087    const wrote = p && 'data' in p ? asApplied(p.data) : null
1088    lastTap = body.action !== 'revert' && wrote ? { id: entry.id, from, to: wrote.version } : null
1089  } catch (err) {
1090    return say($, firstLine(message(err)))
1091  } finally {
1092    writing = false
1093  }
1094  tap = null
1095  note = null
1096  $.ui.invalidate('ui.render')
1097  // A split's writes are on the party view, which parks once they are done.
1098  if (split === null) await focusOn($, 'tap-d')
1099}
1100
1101async function saveLog($: EngineInterface, log: TableLog) {
1102  logs.set(log.session, log)
1103  $.ui.invalidate('ui.render')
1104  await $.store.set(TABLE + log.session, log)
1105}
1106
1107/** Keep `entry`, redraw, and save it unless another session already saved a newer version. */
1108async function update($: EngineInterface, entry: Entry) {
1109  sheets.set(entry.id, entry)
1110  $.ui.invalidate('ui.render')
1111  const stored = storedEntry(await $.store.get(KEY + entry.id))
1112  if (!stored || stored.version <= entry.version) await $.store.set(KEY + entry.id, { ...entry, fromStore: false })
1113}
1114
1115/** Keep `entry` and show it: focus it, and open the pane (or toast) the first time. */
1116async function remember($: EngineInterface, entry: Entry) {
1117  // A re-read refreshes the cache only: the sheet on show stays the one the DM picked, even mid-sweep.
1118  const move = !rereading || !focus
1119  if (move) focus = entry.id
1120  seenHere = true
1121  await update($, entry)
1122  if (move) await $.store.set(LAST, entry.id)
1123  if (!paneOpen && !dismissed && !autoTried) {
1124    autoTried = true
1125    // Unasked, so Claude Code places it only where it fits (144 columns, 110 once opened).
1126    // Esc closes it (or steps back to Party), as `/sheet`'s does: a player who never typed `/sheet` needs a way out.
1127    screens = sheetStack()
1128    leave()
1129    shut()
1130    const placed = await openPane($)
1131    if (placed && placed.isPlaced) {
1132      paneOpen = true
1133      await startSync($)
1134    }
1135  }
1136  if (!paneOpen && !toasted) {
1137    toasted = true
1138    await $.ui.toast(`${entry.name}'s sheet is ready: /sheet`)
1139  }
1140}
1141
1142/**
1143 * A watched result: a get replaces the cached sheet; a check sets its counts
1144 * on a sheet already known (a check carries no sheet); an applied write's diff
1145 * updates it and flashes what it changed.
1146 */
1147async function watch($: EngineInterface, e: any, result: unknown) {
1148  const m = /^mcp__(.+)__sheet_(read|write)$/.exec(String(e.tool))
1149  const p = payloadOf(result)
1150  if (!m || !p || !('data' in p)) return
1151  const now = await $.clock.now()
1152  if (m[2] === 'read') {
1153    const got = asGet(p.data)
1154    if (got && !got.sheet.concentration) saves.delete(got.character.id)
1155    if (got) return remember($, entryFromGet(got, m[1] ?? '', now, sheets.get(got.character.id)?.check))
1156    const check = asCheck(p.data)
1157    const known = check ? sheets.get(check.character.id) : undefined
1158    if (!check || !known) return
1159    const warnings = check.findings.filter((f) => f.severity === 'warning').length
1160    const counts = { at: now, version: check.character.version, warnings, infos: check.findings.length - warnings }
1161    return update($, { ...known, check: counts })
1162  }
1163  const wrote = asApplied(p.data)
1164  const request = e.request ?? e.input?.request ?? {}
1165  let old = wrote ? sheets.get(wrote.character) : undefined
1166  if (wrote && !old && request.action === 'create') {
1167    // A new sheet: nothing is cached, and its diff runs from nothing to the whole sheet, so the
1168    // copy is built from it; derived waits for the first get (live sync fetches it when allowed).
1169    old = {
1170      id: wrote.character, name: wrote.name ?? wrote.character, owner: null, version: wrote.version - 1, sheet: {}, derived: null,
1171      unresolved: [], readAt: now, seenAt: now, server: m[1] ?? '', refreshing: false, derivedPending: true, fromStore: false, drift: false, last: null,
1172    }
1173  }
1174  if (!wrote || !old) return
1175  // A write that touches the field answers its saves; one that raises a save adds it.
1176  if (wrote.diff.some((d) => /^\/concentration(\/|$)/.test(d.path))) saves.delete(old.id)
1177  if (wrote.save) saves.set(old.id, [...(saves.get(old.id) ?? []), wrote.save])
1178  flash = { id: old.id, paths: wrote.diff.map((d) => d.path), until: now + FLASH_MS }
1179  $.clock.after(FLASH_MS, () => $.ui.invalidate('ui.render'))
1180  await remember($, entryAfterWrite(old, wrote, typeof request.reason === 'string' ? request.reason : '', now))
1181}
1182
1183/**
1184 * A watched vault result. A manifest is attached to its own session's log and
1185 * never moves `session` (Ingest and Query read other sessions); a Table write
1186 * is applied to its session's log, and that session is the one followed.
1187 */
1188async function watchVault($: EngineInterface, e: any, result: unknown) {
1189  const p = payloadOf(result)
1190  if (!p || !('data' in p)) return
1191  if (e.tool === VAULT_QUERY) {
1192    const m = (e.request ?? {}).action === 'session' ? asManifest(p.data) : null
1193    if (m) await saveLog($, { ...(logs.get(m.session) ?? { session: m.session, entries: [], closedAt: null }), manifest: m })
1194    return
1195  }
1196  const w = asTableWrite(e, p.data)
1197  if (!w) return
1198  await saveLog($, applyWrite(logs.get(w.session) ?? null, w, await $.clock.now()))
1199  session = w.session
1200  await $.store.set(SESSION, session)
hooks/actions.ts 263 lines
1// The Actions tab as a player's turn menu: the sheet's weapons and spells,
2// each looked up in the generated facts table (facts.ts, the rules server's
3// own snapshot) and worded the way a 2024 player reads them. Pure: no mods
4// API. Nothing here computes a rule:
5// - the facts are the snapshot's, copied by facts/build.py;
6// - the attack bonus and save DC are the sheet's `derived` numbers for the
7//   class the spell is listed under, and a weapon's to-hit is the server's
8//   `derived.weapons` row for it;
9// - a cantrip's die is a lookup in the data's own scaling table at
10//   `derived.total_level`.
11// A name with no record is shown as the sheet writes it and flagged, never guessed.
12
13import type { Entry } from './sheet.ts'
14import { SPELL_ALIASES, SPELLS, WEAPONS, type SpellRow, type WeaponRow } from './facts.ts'
15
16export interface ActionRow {
17  key: string
18  /** As the sheet writes it. */
19  name: string
20  /** The class the spell is listed under (its numbers); '' for weapons and other magic. */
21  cls: string
22  /** A DM rule names it: ★. */
23  dm: boolean
24  /** Always prepared (a domain or subclass spell). */
25  always: boolean
26  /** The headline: dice and damage type, healing, or the casting time when it is not an action. */
27  effect: string
28  /**
29   * What the turn needs first, at full strength: a casting time that is not an
30   * action (a bonus action or reaction is another part of the turn), then what
31   * to roll with the sheet's number: `ATK +5`, `CON save DC 11`.
32   */
33  lead: string
34  /** The rest, dim: the level when no heading says it, range, a duration that is not instant; for a weapon, `not proficient`, `sheet says +4`, its mastery. */
35  facts: string[]
36  badges: ('conc' | 'ritual')[]
37  /** A weapon's damage the sheet does not write: the data's dice, marked with an amber `?`. */
38  guess: boolean
39  /** No record in the snapshot: shown plainly and flagged. */
40  missing: boolean
41  /** The book the record came from (`XPHB`). */
42  source: string
43}
44
45export interface ActionGroup {
46  id: string
47  label: string
48  /** A slot level's pips: left and max. */
49  slots: { left: number; max: number; pending: boolean } | null
50  rows: ActionRow[]
51}
52
53// ------------------------------------------------------------------ lookup
54
55/** The server's name normalisation (`norm`): lower case, every run of other characters one space. */
56export const norm = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()
57
58/** Sources by name, for the name-only fallback. */
59function index(table: Record<string, unknown>): Map<string, string[]> {
60  const out = new Map<string, string[]>()
61  for (const k of Object.keys(table)) {
62    const at = k.lastIndexOf('|')
63    const name = k.slice(0, at)
64    out.set(name, [...(out.get(name) ?? []), k.slice(at + 1)])
65  }
66  return out
67}
68const SPELL_NAMES = index(SPELLS)
69const WEAPON_NAMES = index(WEAPONS)
70
71/** A 2024 sheet (or one that does not say) prefers the 2024 books; a 2014 sheet the 2014 ones. */
72const PREFER_2024 = ['xphb', 'efa', 'xdmg', 'phb', 'xge', 'tce', 'eepc', 'dmg', 'toa']
73const PREFER_2014 = ['phb', 'xge', 'tce', 'eepc', 'dmg', 'toa', 'xphb', 'efa', 'xdmg']
74const rank = (order: string[], s: string) => {
75  const i = order.indexOf(s)
76  return i < 0 ? order.length : i
77}
78
79function find<R>(table: Record<string, R>, names: Map<string, string[]>, wanted: string[], source: string | undefined, ruleset: unknown): { row: R; source: string } | null {
80  for (const n of wanted) {
81    if (source) {
82      const row = table[n + '|' + source.toLowerCase()]
83      if (row) return { row, source: source.toUpperCase() }
84    }
85  }
86  const order = ruleset === '2014' ? PREFER_2014 : PREFER_2024
87  for (const n of wanted) {
88    const sources = [...(names.get(n) ?? [])].sort((a, b) => rank(order, a) - rank(order, b))
89    const s = sources[0]
90    const row = s ? table[n + '|' + s] : undefined
91    if (s && row) return { row, source: s.toUpperCase() }
92  }
93  return null
94}
95
96/** A spell by its own name and source; else by name, the edition's books first; else null. */
97export function spellFact(name: string, source?: string, ruleset?: unknown): { row: SpellRow; source: string } | null {
98  const n = norm(name)
99  const alias = SPELL_ALIASES[n]
100  return find(SPELLS, SPELL_NAMES, alias ? [n, alias] : [n], source, ruleset)
101}
102
103/** A weapon by its own name and source, then by name; a plural ("Daggers") also tries the singular. */
104export function weaponFact(name: string, source?: string, ruleset?: unknown): { row: WeaponRow; source: string } | null {
105  const n = norm(name)
106  const wanted = [n, ...(n.endsWith('s') ? [n.slice(0, -1)] : [])]
107  return find(WEAPONS, WEAPON_NAMES, wanted, source, ruleset)
108}
109
110/** A cantrip's dice at this character level, from the data's table ("1:1d10 5:2d10 …"), or ''. */
111export function cantripDice(table: string, level: number | null): string {
112  if (!table.includes(':')) return table
113  if (level === null) return ''
114  let out = ''
115  for (const pair of table.split(' ')) {
116    const [lv, dice] = pair.split(':')
117    if (Number(lv) <= level) out = dice ?? ''
118  }
119  return out
120}
121
122// ------------------------------------------------------------------ wording
123
124const ORDINAL = (l: number) => ({ 1: '1st', 2: '2nd', 3: '3rd' })[l] ?? l + 'th'
125const signed = (n: unknown) => (typeof n === 'number' ? (n >= 0 ? '+' + n : String(n)) : typeof n === 'string' ? n : '?')
126
127/** `1d10 fire`, `5d6 fire/radiant`, `3d8 · 6 types`, `force`. */
128function damageText(dice: string, types: string[]): string {
129  const t = types.length > 2 ? `${types.length} types` : types.join('/')
130  return dice ? (types.length > 2 ? `${dice} · ${t}` : `${dice} ${t}`) : t
131}
132
133interface Caster {
134  dc: string
135  attack: string
136}
137
138/** One spell row: the facts as a 2024 player reads them, the roll with the class's own number. */
139export function spellRow(key: string, name: string, source: string | undefined, e: Entry, opts: { cls: string; caster: Caster | null; dm: boolean; always: boolean; otherLevel?: boolean }): ActionRow {
140  const hit = spellFact(name, source, e.sheet.ruleset)
141  const base = { key, name, cls: opts.cls, dm: opts.dm, always: opts.always, guess: false, badges: [] as ActionRow['badges'] }
142  if (!hit) return { ...base, effect: '', lead: '', facts: ['Not in the rules snapshot'], missing: true, source: source ?? '' }
143  const [level, , time, range, , duration, flagText, damage, save, diceText] = hit.row
144  const flags = flagText ? flagText.split(' ') : []
145  const types = damage ? damage.split(',') : []
146  const total = typeof e.derived?.total_level === 'number' ? e.derived.total_level : null
147  const dice = level === 0 ? cantripDice(diceText, total) : diceText
148  const pend = e.derivedPending ? '?' : ''
149  let effect = types.length ? damageText(dice, types) : flags.includes('heal') && dice ? `heal ${dice}${flags.includes('mod') ? ' + mod' : ''}` : ''
150  if (!effect && time !== 'Action') effect = time
151  const attack = flags.includes('melee') ? 'Melee' : flags.includes('ranged') ? 'Ranged' : ''
152  const roll = attack
153    ? `${attack} ATK${opts.caster ? ' ' + opts.caster.attack + pend : ''}`
154    : save
155      ? `${save} save${opts.caster ? ' DC ' + opts.caster.dc + pend : ''}`
156      : ''
157  const lead = [...(time !== 'Action' && effect !== time ? [time] : []), ...(roll ? [roll] : [])].join(' · ')
158  const facts = [
159    ...(opts.otherLevel ? [level === 0 ? 'Cantrip' : ORDINAL(level)] : []),
160    range,
161    ...(duration && duration !== 'Instant' ? [duration] : []),
162  ].filter(Boolean)
163  const badges: ActionRow['badges'] = [...(flags.includes('conc') ? ['conc' as const] : []), ...(flags.includes('ritual') ? ['ritual' as const] : [])]
164  return { ...base, effect, lead, facts, badges, missing: false, source: hit.source }
165}
166
167/**
168 * Weapon Mastery (a 2024 class feature). Its `choice`, when written, names the
169 * weapons it covers ("Longsword, Handaxe"); without one, every weapon's
170 * mastery property is shown.
171 */
172export function mastery(e: Entry): { all: boolean; names: string[] } | null {
173  const f = [...(e.sheet.features ?? []), ...(e.sheet.feats ?? [])].find((x: any) => norm(String(x.name ?? '')) === 'weapon mastery')
174  if (!f) return null
175  const names = typeof f.choice === 'string' ? f.choice.split(/,|;|\band\b/).map(norm).filter(Boolean) : []
176  return { all: !names.length, names }
177}
178const singular = (n: string) => (n.endsWith('s') ? n.slice(0, -1) : n)
179export const sameWeapon = (a: string, b: string) => singular(norm(a)) === singular(norm(b))
180
181/** The damage a weapon's note writes first ("1d8 bludgeoning; …" → "1d8 bludgeoning"), or ''. */
182export function writtenDamage(note: string): string {
183  const first = (note.split(';')[0] ?? '').trim()
184  return /^\d*d\d+/i.test(first) ? first : ''
185}
186
187/**
188 * A weapon row: the to-hit is the server's (`derived.weapons`, matched by
189 * name), and `sheet says +N` when the sheet writes another; the damage is the
190 * sheet's written one, else the data's dice, marked a guess. Its properties
191 * wait for the detail box; mastery shows only with Weapon Mastery.
192 */
193function weaponRows(e: Entry, dmNames: (name: string) => boolean): ActionRow[] {
194  const wm = mastery(e)
195  const derived: any[] = Array.isArray(e.derived?.weapons) ? e.derived.weapons : []
196  const written: Record<string, unknown> = e.sheet.as_written?.weapon_attack ?? {}
197  const pend = e.derivedPending ? '?' : ''
198  const out: ActionRow[] = []
199  ;(e.sheet.inventory ?? []).forEach((i: any, n: number) => {
200    const name = String(i.name ?? '')
201    const hit = weaponFact(name, i.source, e.sheet.ruleset)
202    const dw = derived.find((w) => sameWeapon(String(w?.name ?? ''), name))
203    if (!hit && !dw) return
204    const base = { key: 'weapon-' + n, name, cls: '', dm: dmNames(name), always: false, badges: [] as ActionRow['badges'] }
205    if (!hit) {
206      out.push({ ...base, effect: '', guess: false, lead: '', facts: ['Not in the rules snapshot'], missing: true, source: String(i.source ?? '') })
207      return
208    }
209    const says = Object.entries(written).find(([k]) => sameWeapon(k, name))?.[1]
210    const attack = dw ? String(dw.attack) : ''
211    const [, , dice, type, , , , masteryName] = hit.row
212    const covered = !!wm && (wm.all || wm.names.some((w) => sameWeapon(w, name)))
213    const own = writtenDamage(String(i.note ?? ''))
214    out.push({
215      ...base,
216      effect: own || [dice, type].filter(Boolean).join(' '),
217      guess: !own,
218      lead: dw ? `ATK ${attack}${pend}` : '',
219      facts: [
220        ...(dw?.proficient === false ? ['not proficient'] : []),
221        ...(dw && says !== undefined && String(says) !== attack ? [`sheet says ${says}`] : []),
222        ...(covered && masteryName ? [masteryName] : []),
223      ],
224      missing: false,
225      source: hit.source,
226    })
227  })
228  return out
229}
230
231/**
232 * The turn menu: Weapons, Cantrips, then each slot level (its pips in the
233 * heading), then Other magic (spells from species, feats or items, and any
234 * spell whose level neither the sheet nor the snapshot gives).
235 */
236export function actionGroups(e: Entry, slots: Map<number, { left: number; max: number; pending: boolean }>, dmNames: (name: string) => boolean): ActionGroup[] {
237  const groups: ActionGroup[] = []
238  const weapons = weaponRows(e, dmNames)
239  if (weapons.length) groups.push({ id: 'weapons', label: 'Weapons', slots: null, rows: weapons })
240  const casters = new Map<string, Caster>(((e.derived?.spellcasting ?? []) as any[]).map((c) => [String(c.class), { dc: String(c.save_dc ?? '?'), attack: signed(c.attack) }]))
241  const byLevel = new Map<number, ActionRow[]>()
242  const other: ActionRow[] = []
243  for (const sc of e.sheet.spellcasting?.by_class ?? []) {
244    const cls = String(sc.class ?? '')
245    const caster = casters.get(cls) ?? null
246    const add = (lvl: number | null, row: ActionRow) => {
247      if (lvl === null) other.push(row)
248      else byLevel.set(lvl, [...(byLevel.get(lvl) ?? []), row])
249    }
250    ;(sc.cantrips ?? []).forEach((c: any, i: number) => add(0, spellRow(`spell-${cls}-c${i}`, c.name, c.source, e, { cls, caster, dm: dmNames(c.name), always: false })))
251    ;(sc.spells ?? []).forEach((sp: any, i: number) => {
252      const level = typeof sp.level === 'number' ? sp.level : spellFact(sp.name, sp.source, e.sheet.ruleset)?.row[0] ?? null
253      add(level, spellRow(`spell-${cls}-${i}`, sp.name, sp.source, e, { cls, caster, dm: dmNames(sp.name), always: !!sp.always, otherLevel: level === null }))
254    })
255  }
256  for (const [lvl, rows] of [...byLevel].sort(([a], [b]) => a - b)) {
257    groups.push({ id: lvl === 0 ? 'cantrips' : 'level-' + lvl, label: lvl === 0 ? 'Cantrips' : `${ORDINAL(lvl)} level`, slots: lvl === 0 ? null : slots.get(lvl) ?? null, rows })
258  }
259  ;(e.sheet.spellcasting?.other ?? []).forEach((x: any, i: number) => other.push(spellRow('other-' + i, x.name, x.source, e, { cls: '', caster: null, dm: dmNames(x.name), always: false, otherLevel: true })))
260  if (other.length) groups.push({ id: 'other', label: 'Other magic', slots: null, rows: other })
261  return groups
262}
263
hooks/fight.ts 333 lines
1// The DM's fight (handoff 18, step A part 1). The store holds the DM's presses
2// (ops); a Fight is their fold. Pure: no mods API. The only arithmetic is the
3// DM's own HP sums and the round count.
4
5export type Side = 'pc' | 'monster'
6/** `working` is the signed changes in order (`22 − 9 = 13`); `zero` is `0?` pending, `dead` is confirmed by `x`. */
7export type Member = { hp: number; max: number; working: number[]; dead: boolean; zero: boolean }
8/** A row with no members has no HP tracked (a PC's is the sheet's); a single monster has one. `added` is its event index; `downs` the rounds `k` put it down in. */
9export type Row = { id: string; side: Side; name: string; init: number | null; ac: number | null; members: Member[]; out: boolean; down: boolean; downs: number[]; added: number }
10/** An op as `describe` renders it; `working` is an HP op's result (`22 − 9 = 13`). */
11export type LogLine = { at: number; text: string; working?: string; reverted?: true }
12/** `packs` names the packs loaded into it, in order (an undone one is not). */
13export type Fight = { id: string; startedAt: number; rows: Row[]; pointer: string | null; round: number; ended: number | null; log: LogLine[]; packs: string[] }
14export type AddOp = { op: 'add'; name: string; count: number; hp: number | null; ac: number | null; init: number | null }
15/** One press. `name` on `init`/`down` is the PC's roster name: its row is made on first mention. A `pack` is a combat pack's adds as one press. */
16export type Op =
17  | AddOp
18  | { op: 'pack'; name: string; rows: AddOp[] }
19  | { op: 'init'; row: string; name: string; value: number }
20  | { op: 'hp'; row: string; member: number; delta: number }
21  | { op: 'kill'; row: string; member: number }
22  | { op: 'out'; row: string }
23  | { op: 'down'; row: string; name: string; value: boolean }
24  | { op: 'point'; row: string }
25  | { op: 'next' }
26  | { op: 'end' }
27/** `undo` names the index of the event it reverts. */
28export type Event = { at: number; op: Op } | { at: number; undo: number }
29
30export const live = (f: Fight | null) => (f && f.ended === null ? f : null)
31const group = (r: Row | undefined) => !!r && r.members.length > 1
32const allDead = (r: Row) => r.members.length > 0 && r.members.every((m) => m.dead)
33
34const undoneOf = (events: Event[]) => new Set(events.flatMap((e) => ('undo' in e ? [e.undo] : [])))
35
36/** The index of the event the next `undo` reverts, or null. */
37export function undoTarget(events: Event[]): number | null {
38  const undone = undoneOf(events)
39  for (let i = events.length - 1; i >= 0; i--) if (!('undo' in events[i]!) && !undone.has(i)) return i
40  return null
41}
42
43/** Can the pointer land here? Not `out`, not a dead group, not a `?` row. */
44const eligible = (r: Row) => !r.out && r.init !== null && !allDead(r)
45
46/** Initiative order: rows with one (highest first, then as added), then `?` rows as added; out and dead rows sink in each. */
47export function orderRows(f: Fight): Row[] {
48  const sunk = (r: Row) => (r.out || allDead(r) ? 1 : 0)
49  const by = (a: Row, b: Row) => sunk(a) - sunk(b) || (b.init ?? 0) - (a.init ?? 0) || a.added - b.added
50  return [...f.rows.filter((r) => r.init !== null).sort(by), ...f.rows.filter((r) => r.init === null).sort(by)]
51}
52
53/** Where `n` moves the pointer, and whether it wraps to a new round. */
54function nextRow(f: Fight): { row: Row; wraps: boolean } | null {
55  const order = orderRows(f)
56  const at = order.findIndex((r) => r.id === f.pointer)
57  const after = f.pointer === null ? order.find(eligible) : order.slice(at + 1).find(eligible)
58  if (after) return { row: after, wraps: false }
59  const first = order.find(eligible)
60  return first ? { row: first, wraps: true } : null
61}
62
63/** The row on deck: where `n` would move the pointer, unless that is the current row. */
64export function onDeck(f: Fight): string | null {
65  const next = nextRow(f)
66  return next && next.row.id !== f.pointer ? next.row.id : null
67}
68
69/** `▶ NUX then DIEGO · ROUND 2`, or `NO POINTER · next turn, or a row's turn` before the first. */
70export function statusText(f: Fight): string {
71  const cur = f.rows.find((r) => r.id === f.pointer)
72  if (!cur) return "NO POINTER · next turn, or a row's turn"
73  const next = nextRow(f)
74  const then = next && next.row !== cur ? ` then ${next.row.name.toUpperCase()}` : ''
75  return `▶ ${cur.name.toUpperCase()}${then}` + (f.round ? ` · ROUND ${f.round}` : '')
76}
77
78/** A member's working as the DM writes it: `22 − 9 = 13 − 8 = 5`. */
79export function working(m: Member): string {
80  let hp = m.max
81  let s = String(hp)
82  for (const d of m.working) {
83    hp += d
84    s += ` ${d < 0 ? '−' : '+'} ${Math.abs(d)} = ${hp}`
85  }
86  return s
87}
88
89/** A row and member as the log names them: the member's number only in a group. */
90function named(f: Fight | null, id: string, member?: number): string {
91  const r = f?.rows.find((x) => x.id === id)
92  const name = r?.name ?? id
93  return member !== undefined && group(r) ? `${name} ${member + 1}` : name
94}
95
96/** An op as the log shows it: `Goblin ×2 · hp 7 · ac 15 · init 14`, `Goblin 2 −9`, `▶ Bati`. */
97export function describe(o: Op, f: Fight | null): string {
98  if (o.op === 'add') {
99    const parts = [o.count > 1 ? `${o.name} ×${o.count}` : o.name]
100    if (o.hp !== null) parts.push(`hp ${o.hp}`)
101    if (o.ac !== null) parts.push(`ac ${o.ac}`)
102    if (o.init !== null) parts.push(`init ${o.init}`)
103    return parts.join(' · ')
104  }
105  if (o.op === 'pack') return `pack ${o.name}: ${o.rows.length} group${o.rows.length === 1 ? '' : 's'}`
106  if (o.op === 'init') return `${o.name} · init ${o.value}`
107  if (o.op === 'hp') return `${named(f, o.row, o.member)} ${o.delta < 0 ? '−' : '+'}${Math.abs(o.delta)}`
108  if (o.op === 'kill') return `${named(f, o.row, o.member)} ✕`
109  if (o.op === 'out') return `${named(f, o.row)} out`
110  if (o.op === 'down') return `${o.name} ${o.value ? 'down' : 'up'}`
111  if (o.op === 'point') return `▶ ${named(f, o.row)}`
112  return o.op === 'next' ? 'next turn' : 'end'
113}
114
115/**
116 * The fight as one Table-note line, for Ingest: what was tracked, in the DM's
117 * words (`out`, never "fled"). Null when no row was tracked. For example
118 * `fight: Smoke mephit ×6, 5 dead, 1 standing · Gout · Slaad out · 9 rounds · Gout down r2, r5`.
119 * Standing counts `0?` members too: only `x` confirms a death.
120 */
121export function summary(f: Fight): string | null {
122  const order = orderRows(f)
123  if (!order.length) return null
124  const rows = order.map((r) => {
125    const n = r.members.length
126    const dead = r.members.filter((m) => m.dead).length
127    const s = (n > 1 ? `${r.name} ×${n}` : r.name) + (dead ? `, ${dead} dead` : '') + (n - dead ? `, ${n - dead} standing` : '')
128    return r.out ? s + ' out' : s
129  })
130  const rounds = f.round ? [f.round === 1 ? '1 round' : `${f.round} rounds`] : []
131  const downs = order.filter((r) => r.downs.length).map((r) => `${r.name} down ${r.downs.map((d) => 'r' + d).join(', ')}`)
132  return 'fight: ' + [...rows, ...rounds, ...downs].join(' · ')
133}
134
135/** An add's row, `id`, from the event at index `i`. */
136function addRow(f: Fight, o: AddOp, id: string, i: number) {
137  const hp = o.hp
138  const members = hp === null ? [] : Array.from({ length: Math.max(1, o.count) }, () => ({ hp, max: hp, working: [], dead: false, zero: false }))
139  f.rows.push({ id, side: 'monster', name: o.name, init: o.init, ac: o.ac, members, out: false, down: false, downs: [], added: i })
140}
141
142/** Apply one op to `f`, the event at index `i`: false when its row or member is not there. Returns the HP working an `hp` op produced. */
143function applyOp(f: Fight, o: Op, i: number, at: number): { working?: string } | false {
144  const r = 'row' in o ? f.rows.find((x) => x.id === o.row) : undefined
145  if (o.op === 'add') addRow(f, o, 'm' + i, i)
146  // A pack's rows share its event index, so one undo takes them all; they order as listed.
147  else if (o.op === 'pack') {
148    o.rows.forEach((a, k) => addRow(f, a, `m${i}.${k}`, i))
149    f.packs.push(o.name)
150  }
151  else if (o.op === 'init' || o.op === 'down') {
152    const row = r ?? { id: o.row, side: 'pc' as const, name: o.name, init: null, ac: null, members: [], out: false, down: false, downs: [], added: i }
153    if (!r) f.rows.push(row)
154    if (o.op === 'init') row.init = o.value
155    else {
156      row.down = o.value
157      if (o.value) row.downs.push(f.round)
158    }
159  } else if (o.op === 'next') {
160    const n = nextRow(f)
161    if (n) {
162      f.round = f.pointer === null ? Math.max(f.round, 1) : n.wraps ? f.round + 1 : f.round
163      f.pointer = n.row.id
164    }
165  } else if (o.op === 'end') f.ended = at
166  else if (!r) return false
167  else if (o.op === 'out') r.out = true
168  else if (o.op === 'point') {
169    // The round stays, except that a fight's first `t` starts round 1, as its first `n` does.
170    f.pointer = r.id
171    f.round = Math.max(f.round, 1)
172  } else {
173    const m = r.members[o.member]
174    if (!m) return false
175    if (o.op === 'kill') Object.assign(m, { dead: true, zero: false })
176    else {
177      m.working.push(o.delta)
178      m.hp += o.delta
179      m.zero = m.hp <= 0 && !m.dead
180      return { working: working(m) }
181    }
182  }
183  return {}
184}
185
186/** Does this op open a new fight when none is live? An add, a pack, or a PC's initiative. */
187const starts = (o: Op) => o.op === 'add' || o.op === 'pack' || o.op === 'init'
188
189/**
190 * Replay the events: undone ops are logged and skipped, an op that has nothing
191 * to act on (no live fight, its row gone) is logged as `? <op>`. An op that
192 * starts a fight while none is live begins a new one, `F` + its time.
193 */
194export function fold(events: Event[]): Fight | null {
195  const undone = undoneOf(events)
196  let f: Fight | null = null
197  events.forEach((e, i) => {
198    if ('undo' in e) return
199    const text = describe(e.op, f)
200    if (undone.has(i)) return void f?.log.push({ at: e.at, text, reverted: true })
201    if (!live(f) && starts(e.op)) f = { id: 'F' + e.at, startedAt: e.at, rows: [], pointer: null, round: 0, ended: null, log: [], packs: [] }
202    const result = live(f) ? applyOp(f!, e.op, i, e.at) : false
203    if (!result) return void f?.log.push({ at: e.at, text: '? ' + text })
204    f!.log.push({ at: e.at, text, ...result })
205  })
206  return f
207}
208
209/** A packet's notes section: its `### ` heading, that line's number, and its lines as written. */
210export type Section = { heading: string; line: number; lines: string[] }
211/** A pack: its `## ` heading and line, the `# ` section it sits under (`S05`, or null), its groups and its notes. */
212export type Pack = { name: string; line: number; section: string | null; rows: AddOp[]; notes: Section[] }
213
214/**
215 * The combat packs in `Prep/Fights.md`. A `# ` heading (`# S05`) opens a
216 * session's section and closes the pack before it. Each `## ` heading is a
217 * pack; each non-blank line under it a group, `<name> [xN|×N] [hp N] [ac N]
218 * [init N]`, with at least one field. From the pack's first `### ` heading on,
219 * its lines are notes, kept as written, never read as groups. Lines outside a
220 * pack are ignored. A pack with a line that does not read is refused whole;
221 * `errors` names the line, `Fights.md L7: …`.
222 */
223export function parsePacks(text: string): { packs: Pack[]; errors: string[] } {
224  const packs: Pack[] = []
225  const errors: string[] = []
226  let section: string | null = null
227  let cur: (Pack & { error: string | null }) | null = null
228  const trimNote = () => {
229    const open = cur?.notes[cur.notes.length - 1]
230    while (open && open.lines.length && !open.lines[open.lines.length - 1]!.trim()) open.lines.pop()
231  }
232  const close = () => {
233    if (!cur) return
234    trimNote()
235    if (!cur.error && !cur.rows.length) cur.error = `Fights.md L${cur.line}: "${cur.name}" has no groups`
236    if (cur.error) errors.push(cur.error)
237    else packs.push({ name: cur.name, line: cur.line, section: cur.section, rows: cur.rows, notes: cur.notes })
238    cur = null
239  }
240  // An HTML comment is not the pack's, however many lines it runs (a pasted
241  // Templates/Fights.md carries its example in one); an unclosed one runs to the
242  // end. Its newlines stay, so line numbers still match the file.
243  const shown = text.replace(/<!--[\s\S]*?(?:-->|$)/g, (c) => c.replace(/[^\n]/g, ''))
244  shown.split(/\r?\n/).forEach((raw, n) => {
245    const line = raw.trim()
246    const head = /^(#{1,3})(?:\s+(.*))?$/.exec(line)
247    const title = (head?.[2] ?? '').trim()
248    if (head?.[1] === '#') {
249      close()
250      section = title || null
251      return
252    }
253    if (head?.[1] === '##') {
254      close()
255      cur = { name: title, line: n + 1, section, rows: [], notes: [], error: null }
256      if (!cur.name) cur.error = `Fights.md L${n + 1}: a pack needs a name`
257      return
258    }
259    if (!cur || cur.error) return
260    if (head?.[1] === '###') {
261      trimNote()
262      cur.notes.push({ heading: title, line: n + 1, lines: [] })
263      return
264    }
265    const note = cur.notes[cur.notes.length - 1]
266    if (note) {
267      if (line || note.lines.length) note.lines.push(raw)
268      return
269    }
270    if (!line) return
271    const read = line.startsWith('#') ? `can't read "${line}"` : readGroup(line)
272    if (typeof read === 'string') cur.error = `Fights.md L${n + 1}: ${read}`
273    else cur.rows.push(read)
274  })
275  close()
276  return { packs, errors }
277}
278
279/** One group line as an add, or why it does not read: a line with no field is no group. */
280function readGroup(line: string): AddOp | string {
281  const bad = `can't read "${line}"`
282  const words = line.replace(/^-\s+/, '').split(/\s+/)
283  const name: string[] = []
284  const got: { count?: number; hp?: number; ac?: number; init?: number } = {}
285  for (let k = 0; k < words.length; k++) {
286    const w = words[k]!
287    const times = /^[x×](\d+)$/i.exec(w)
288    const key = w.toLowerCase()
289    const field = key === 'hp' || key === 'ac' || key === 'init' ? key : null
290    if (!times && !field) {
291      if (Object.keys(got).length) return bad
292      name.push(w)
293      continue
294    }
295    const value = times ? times[1]! : words[++k]
296    if (value === undefined || !/^\d+$/.test(value)) return bad
297    const slot = times ? 'count' : field!
298    if (slot in got) return bad
299    got[slot] = Number(value)
300  }
301  const text = name.join(' ')
302  if (!text || !Object.keys(got).length || got.count === 0) return bad
303  const count = got.count ?? 1
304  if (count > 1 && got.hp === undefined) return 'a group needs HP'
305  return { op: 'add', name: text.charAt(0).toUpperCase() + text.slice(1), count, hp: got.hp ?? null, ac: got.ac ?? null, init: got.init ?? null }
306}
307
308/** The last pack loaded and not undone, over fight logs newest first, or null. */
309export function lastPack(logs: Event[][]): string | null {
310  for (const events of logs) {
311    const undone = undoneOf(events)
312    for (let i = events.length - 1; i >= 0; i--) {
313      const e = events[i]!
314      if ('op' in e && e.op.op === 'pack' && !undone.has(i)) return e.op.name
315    }
316  }
317  return null
318}
319
320/** The packs `[ next ]` walks: the `# ` section named `session`, or the whole file when there is none. */
321export function sessionPacks(packs: Pack[], session: string | null): Pack[] {
322  const s = session?.trim().toUpperCase()
323  const own = s ? packs.filter((p) => p.section?.toUpperCase() === s) : []
324  return own.length ? own : packs
325}
326
327/** The pack `[ next ]` loads: the one after `last` in the session's packs, else their first. */
328export function nextPack(packs: Pack[], session: string | null, last: string | null): Pack | null {
329  const scope = sessionPacks(packs, session)
330  const at = last === null ? -1 : scope.findIndex((p) => p.name === last)
331  return (at >= 0 ? scope[at + 1] : undefined) ?? scope[0] ?? null
332}
333
hooks/detail.ts 542 lines
1// The detail boxes (T0093 Layer 1): a word on the pane (a weapon, a spell, a
2// save, a skill, a resource, a condition, the last-seen value, the requests)
3// opens one box under its row, one at a time. Pure: no mods API. Everything a
4// box says is data the pane already holds (the sheet, `derived`, facts.ts);
5// it applies no rule. A breakdown (`CON +4 = CON +2 · proficient +2`) is the
6// server's numbers taken apart by subtraction, which is display.
7//
8// A word's key names its subject: `w:act:<row key>` (actions.ts's row keys),
9// `w:save:<ability>`, `w:skill:<name>`, `w:res:<index>` on the focused sheet;
10// `w:cond:<entry id>:<condition>`, `w:seen:<entry id>`, `w:req:<entry id>` on
11// any cached sheet. A word is drawn only where `detailOf` has a box for it.
12//
13// Inside a box (Layer 2) a rules term is a word too. `w:n:<target>` nests: its
14// press pushes `w:<target>` onto the open box's path (`w:n:g:heavy` opens the
15// glossary's Heavy in place, `w:n:skill:Athletics` the skill's box), the title
16// becomes the path's breadcrumb and `[ ‹ ]` pops a level. `w:c:<kind>:<name>`
17// opens T0085's card, which the rules server fills: `w:c:spell:<name>`,
18// `w:c:monster:<name>`, `w:c:option:<kind>|<name>|<feature>[|<row>]` (character_option_get).
19
20import type { Elements, RenderElement, RenderNode } from 'claude-code'
21import { cantripDice, mastery, norm, sameWeapon, spellFact, weaponFact, writtenDamage } from './actions.ts'
22import { SKILLS, SKILLS_CITE, SPELL_ALIASES, SPELLS } from './facts.ts'
23import { GLOSSARY } from './glossary.ts'
24import { CONDITIONS, SCHOOLS, type Candidate, type Card } from './lookup.ts'
25import { TOKENS } from './look.ts'
26import { describeChange, type Entry } from './sheet.ts'
27
28/**
29 * The open box: the word it hangs from, and the terms opened inside it, the
30 * anchor first. `above`: a pinned preview (Layer 3), drawn above the word, not under its row.
31 */
32export type Detail = { anchor: string; path: string[]; above?: true }
33
34/**
35 * The hover preview (Layer 3): the word's card above it, and a term's card
36 * above that (one level on hover); `pinned` once a click locked it.
37 */
38export type Preview = { anchor: string; top: Content; nested: Content | null; pinned: boolean }
39
40/** The deepest a box nests: at this depth its words are plain text. */
41const DEPTH = 3
42
43/**
44 * A press on a word: its box opens, replacing any other; a press on the open
45 * one closes it. A term inside the open box (`w:n:`) nests its box on the path,
46 * while the path is shallower than DEPTH and does not hold it already.
47 */
48export const pressWord = (state: Detail | null, key: string): Detail | null => {
49  if (!key.startsWith('w:n:')) return state?.anchor === key ? null : { anchor: key, path: [key] }
50  const to = 'w:' + key.slice('w:n:'.length)
51  return state && state.path.length < DEPTH && !state.path.includes(to) ? { ...state, path: [...state.path, to] } : state
52}
53
54/** A `w:c:` word's card, or null for any other key. */
55export function wordCard(key: string): Candidate | null {
56  const m = /^w:c:(spell|monster|option):(.+)$/.exec(key)
57  if (!m) return null
58  const [, kind, rest] = m as unknown as [string, 'spell' | 'monster' | 'option', string]
59  if (kind === 'option') {
60    // Only a class or subclass takes one feature; any other option opens whole.
61    // A species' card shows the pressed trait (its name the candidate's), from
62    // the one answer. A fourth part, the row, only keeps each word's key its own.
63    const [k, name, feature] = rest.split('|')
64    const one = k === 'class' || k === 'subclass' ? feature : ''
65    return { name: one || (k === 'species' && feature) || name!, kind, key: `${k}|${name}|${one}` }
66  }
67  return { name: rest, kind, key: kind === 'spell' ? norm(rest) + '|xphb' : norm(rest) }
68}
69
70/** A run of a line: values bold, labels faint, a warning amber; with a `key`, a word. */
71export type Piece = { text: string; tone?: 'value' | 'label' | 'warn'; key?: string }
72/** Pieces that never break apart; a line wraps only between units. */
73type Unit = Piece[]
74
75export interface Content {
76  title: string
77  lines: Unit[][]
78  /** Where it comes from: `XPHB · derived`, `derived`, `sheet`. */
79  cite: string
80  /** `[ more ]`: T0085's card for this term. */
81  more: Candidate | null
82  /** `[ re-read ]`: the sheet's re-read. */
83  reread: boolean
84  /** `[ ‹ ]`: the box is nested; it pops a level. */
85  back?: boolean
86  /** Long text: past six rows it ends at a sentence, and `[ more ]` shows the rest (no `[ more ]` when it fits). */
87  cut?: boolean
88}
89
90const val = (text: string): Piece => ({ text, tone: 'value' })
91const lab = (text: string): Piece => ({ text, tone: 'label' })
92const warn = (text: string): Piece => ({ text, tone: 'warn' })
93const plain = (text: string): Piece => ({ text })
94/** Units joined by a faint ` ·` at the end of each but the last. */
95const dots = (units: Unit[]): Unit[] => units.map((u, i) => (i < units.length - 1 ? [...u, lab(' ·')] : u))
96/** Prose as one unit a word, so it wraps between words. */
97const prose = (s: string, tone?: Piece['tone']): Unit[] =>
98  s
99    .split(/\s+/)
100    .filter(Boolean)
101    .map((w) => [{ text: w, ...(tone ? { tone } : {}) }])
102
103const signed = (n: number) => (n >= 0 ? '+' + n : String(n))
104const num = (x: unknown): number | null => {
105  const n = typeof x === 'number' ? x : typeof x === 'string' && x.trim() ? Number(x) : NaN
106  return Number.isFinite(n) ? n : null
107}
108const ORDINAL = (l: number) => ({ 1: '1st', 2: '2nd', 3: '3rd' })[l] ?? l + 'th'
109const pad2 = (n: number) => String(n).padStart(2, '0')
110const clock = (ms: number) => pad2(new Date(ms).getHours()) + ':' + pad2(new Date(ms).getMinutes())
111const MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
112/** `39 min`, `5 h`, `3 d`. */
113const ago = (ms: number) => {
114  const m = Math.max(0, Math.round(ms / 60000))
115  return m < 60 ? `${m} min` : m < 48 * 60 ? `${Math.round(m / 60)} h` : `${Math.round(m / 1440)} d`
116}
117/** The pending number's warning: `derived` is the server's, and a write since may change it. */
118const PENDING: Unit[] = prose('the server has not derived this yet', 'warn')
119
120/** A glossary term, a word that nests its entry; plain where the glossary has none (Ritual). */
121const term = (text: string, tone?: Piece['tone'], key = text.toLowerCase()): Piece => ({ text, ...(tone ? { tone } : {}), ...(GLOSSARY[key] ? { key: 'w:n:g:' + key } : {}) })
122
123/** The fetch kinds a glossary link names (build.py's FETCH_KINDS), as the word each is; `classFeature` names no class, so stays text. */
124const FETCH: Record<string, (name: string) => string> = {
125  spell: (n) => 'w:c:spell:' + n,
126  creature: (n) => 'w:c:monster:' + n,
127  item: (n) => 'w:c:option:item|' + n + '|',
128  feat: (n) => 'w:c:option:feat|' + n + '|',
129  skill: (n) => 'w:n:skill:' + n,
130}
131/** A link in glossary text, `⟦key|shown⟧` or `⟦kind:name|shown⟧`, as its word. */
132function link(target: string, shown: string): Piece {
133  const at = target.indexOf(':')
134  if (at < 0) return { text: shown, key: 'w:n:g:' + target }
135  const to = FETCH[target.slice(0, at)]
136  return to ? { text: shown, key: to(target.slice(at + 1)) } : plain(shown)
137}
138/**
139 * Glossary text as lines of units: words wrap apart; a link and the punctuation
140 * touching it stay one unit. A link to a target already linked is text: a key
141 * is drawn once (Light's three Bonus Actions).
142 */
143const glossLines = (text: string): Unit[][] => {
144  const linked = new Set<string>()
145  return text.split('\n').map((line) => {
146    const units: Unit[] = []
147    let cur: Unit = []
148    const flush = () => (cur.length && units.push(cur), (cur = []))
149    for (const part of line.split(/(⟦[^⟧]*⟧)/)) {
150      const m = /^⟦([^|⟧]*)\|([^⟧]*)⟧$/.exec(part)
151      if (m) cur.push(linked.has(m[1]!) ? plain(m[2]!) : (linked.add(m[1]!), link(m[1]!, m[2]!)))
152      else for (const w of part.split(/(\s+)/)) /^\s+$/.test(w) ? flush() : w && cur.push(plain(w))
153    }
154    flush()
155    return units
156  })
157}
158
159/** A glossary entry (`w:g:<key>`): its SRD 5.2.1 text and page, cut long with `[ more ]` to the whole. */
160function glossaryBox(key: string): Content | null {
161  const g = GLOSSARY[key]
162  if (!g) return null
163  const [title, text, source, page] = g
164  return { title, lines: glossLines(text), cite: `${source} p.${page}`, more: { name: title, kind: 'glossary', key }, reread: false, cut: true }
165}
166
167/**
168 * `ABIL +mod`, then what proficiency adds, then any rest: the server's total
169 * taken apart. `prof` is 0 (none), 1 (proficient) or 2 (expertise).
170 */
171function breakdown(total: number, abil: string, d: Record<string, any>, prof: 0 | 1 | 2): Unit[] {
172  const mod = num(d.modifiers?.[abil])
173  const pb = num(d.proficiency_bonus)
174  if (mod === null || (prof && pb === null)) return []
175  const add = prof ? prof * pb! : 0
176  const rest = total - mod - add
177  return [
178    [lab(abil.toUpperCase() + ' '), val(signed(mod))],
179    ...(prof ? [[lab(prof === 2 ? 'expertise ' : 'proficient '), val(signed(add))]] : []),
180    ...(rest ? [[lab('other '), val(signed(rest))]] : []),
181  ]
182}
183
184// ------------------------------------------------------------------ the boxes
185
186function weaponBox(e: Entry, n: number): Content | null {
187  const item = (e.sheet.inventory ?? [])[n]
188  if (!item) return null
189  const name = String(item.name ?? '')
190  const hit = weaponFact(name, item.source, e.sheet.ruleset)
191  if (!hit) return null
192  const [category, kind, dice, type, versatile, props, range, masteryName] = hit.row
193  const d = e.derived ?? {}
194  const dw = (Array.isArray(d.weapons) ? d.weapons : []).find((w: any) => sameWeapon(String(w?.name ?? ''), name))
195  const lines: Unit[][] = []
196  const attack = num(dw?.attack)
197  if (dw && attack !== null) {
198    const prof = dw.proficient !== false
199    lines.push(dots([[val(signed(attack)), plain(' to hit')], ...breakdown(attack, String(dw.ability ?? ''), d, prof ? 1 : 0), ...(prof ? [] : [[lab('not proficient')]])]))
200  }
201  const own = writtenDamage(String(item.note ?? ''))
202  lines.push(own ? dots([[val(own)], [lab('as written')]]) : dots([[val([dice, type].filter(Boolean).join(' '))], [lab('no damage written'), warn(' ?')]]))
203  // The two-handed dice with the attack's ability modifier, as the design's `two-handed 1d10+2`.
204  const vmod = num(d.modifiers?.[String(dw?.ability ?? '')])
205  if (versatile) lines.push([[lab('two-handed '), val(versatile + (vmod ? signed(vmod) : ''))]])
206  const score = (abil: string) => num(e.sheet.abilities?.[abil])
207  const heavy = kind === 'ranged' ? 'dex' : 'str'
208  lines.push(
209    dots([
210      [val(category)],
211      [val(kind)],
212      ...(props ? props.split(',') : []).map((p): Unit => {
213        if ((p === 'Thrown' || p === 'Ammunition') && range) return [term(p, 'value'), val(' ' + range)]
214        if (p === 'Heavy' && score(heavy) !== null) return [term('Heavy', 'value'), lab(` (your ${heavy.toUpperCase()} ${score(heavy)})`)]
215        return [term(p, 'value')]
216      }),
217    ]),
218  )
219  const wm = mastery(e)
220  if (masteryName && wm && (wm.all || wm.names.some((w) => sameWeapon(w, name)))) lines.push([[lab('mastery '), term(masteryName, 'value')]])
221  const says = Object.entries((e.sheet.as_written?.weapon_attack ?? {}) as Record<string, unknown>).find(([k]) => sameWeapon(k, name))?.[1]
222  if (dw && says !== undefined && String(says) !== String(dw.attack)) lines.push([[lab('the sheet says '), val(String(says))]])
223  if (dw && e.derivedPending) lines.push(PENDING)
224  return { title: name, lines, cite: hit.source + (dw ? ' · derived' : ''), more: null, reread: false }
225}
226
227function spellBox(e: Entry, spell: any, cls: string): Content | null {
228  const name = String(spell?.name ?? '')
229  const hit = spellFact(name, spell?.source, e.sheet.ruleset)
230  if (!hit) return null
231  const [level, school, time, range, comps, duration, flagText, damage, save, diceText] = hit.row
232  const flags = flagText ? flagText.split(' ') : []
233  const d = e.derived ?? {}
234  const lines: Unit[][] = [dots([level === 0 ? 'Cantrip' : ORDINAL(level), SCHOOLS[school] ?? school, time, range, comps, duration].filter(Boolean).map((s) => [val(s)]))]
235  const caster = cls ? ((d.spellcasting ?? []) as any[]).find((c) => String(c.class) === cls) : undefined
236  const q = e.derivedPending ? '?' : ''
237  if (caster && (flags.includes('melee') || flags.includes('ranged'))) {
238    const atk = num(caster.attack)
239    lines.push([[val((atk === null ? String(caster.attack) : signed(atk)) + q), plain(' to hit')], [lab(`(${cls})`)]])
240  } else if (caster && save) lines.push(dots([[val(save), plain(' '), term('save', undefined, 'saving throw')], [lab('DC '), val(String(caster.save_dc) + q), lab(` (${cls})`)]]))
241  const total = num(d.total_level)
242  const dice = level === 0 ? cantripDice(diceText, total) : diceText
243  if (damage) lines.push([[val(dice)], ...prose(damage.split(',').join(', '))].filter((u) => u[0]!.text))
244  else if (flags.includes('heal') && dice) lines.push([[lab('heal '), val(dice + (flags.includes('mod') ? ' + mod' : ''))]])
245  const tags = [...(flags.includes('conc') ? ['Concentration'] : []), ...(flags.includes('ritual') ? ['Ritual'] : [])]
246  if (tags.length) lines.push(dots(tags.map((t) => [term(t, 'value')])))
247  if (caster && e.derivedPending) lines.push(PENDING)
248  // The card fetches the spell by name; the facts row is the one this box read.
249  const n = norm(name)
250  const keyName = SPELLS[n + '|' + hit.source.toLowerCase()] ? n : SPELL_ALIASES[n] ?? n
251  return { title: name, lines, cite: hit.source + (caster ? ' · derived' : ''), more: { name, kind: 'spell', key: keyName + '|' + hit.source.toLowerCase() }, reread: false }
252}
253
254/** `w:act:<row key>`: `weapon-<inventory index>`, `spell-<class>-c<i>` (cantrip), `spell-<class>-<i>`, `other-<i>`. */
255function actionBox(e: Entry, row: string): Content | null {
256  const at = row.lastIndexOf('-')
257  const kind = row.slice(0, row.indexOf('-'))
258  const i = row.slice(at + 1)
259  if (kind === 'weapon') return weaponBox(e, Number(i))
260  if (kind === 'other') return spellBox(e, (e.sheet.spellcasting?.other ?? [])[Number(i)], '')
261  if (kind !== 'spell') return null
262  const cls = row.slice('spell-'.length, at)
263  const sc = (e.sheet.spellcasting?.by_class ?? []).find((c: any) => String(c.class ?? '') === cls)
264  const spell = i.startsWith('c') ? sc?.cantrips?.[Number(i.slice(1))] : sc?.spells?.[Number(i)]
265  return spell ? spellBox(e, spell, cls) : null
266}
267
268function saveBox(e: Entry, abil: string): Content | null {
269  const d = e.derived
270  const total = num(d?.saving_throws?.[abil])
271  if (!d || total === null) return null
272  const prof = (e.sheet.proficiencies?.saves ?? []).includes(abil)
273  const parts = breakdown(total, abil, d, prof ? 1 : 0)
274  const lines: Unit[][] = [[[lab(abil.toUpperCase() + ' '), val(signed(total)), plain(parts.length ? ' =' : '')], ...dots(parts)]]
275  if (e.derivedPending) lines.push(PENDING)
276  return { title: abil.toUpperCase() + ' save', lines, cite: 'derived', more: null, reread: false }
277}
278
279function skillBox(e: Entry, skill: string): Content | null {
280  const d = e.derived
281  const name = Object.keys(d?.skills ?? {}).find((k) => k.toLowerCase() === skill.toLowerCase())
282  const total = name ? num(d!.skills[name]) : null
283  const abil = SKILLS[skill.toLowerCase()]
284  if (!d || !name || total === null || !abil) return null
285  const p = (e.sheet.proficiencies?.skills ?? []).find((k: any) => String(k.name).toLowerCase() === skill.toLowerCase())
286  const parts = breakdown(total, abil, d, p ? (p.expertise ? 2 : 1) : 0)
287  const lines: Unit[][] = [[[lab(name + ' '), val(signed(total)), plain(parts.length ? ' =' : '')], ...dots(parts)]]
288  const says = Object.entries((e.sheet.as_written?.skills ?? {}) as Record<string, unknown>).find(([k]) => k.toLowerCase() === skill.toLowerCase())?.[1]
289  if (says !== undefined && String(says) !== signed(total)) lines.push([[lab('the sheet says '), val(String(says))]])
290  if (e.derivedPending) lines.push(PENDING)
291  return { title: name, lines, cite: SKILLS_CITE + ' · derived', more: null, reread: false }
292}
293
294const RECHARGE: Record<string, string> = { long: 'a Long Rest', short: 'a Short Rest' }
295
296function resourceBox(e: Entry, i: number): Content | null {
297  const r = (e.sheet.resources ?? [])[i]
298  const max = num(r?.max)
299  if (!r || max === null) return null
300  const lines: Unit[][] = [
301    dots([[val(`${Math.max(0, max - (num(r.used) ?? 0))} of ${max}`)], ...(r.recharge ? [[lab('recharges on '), val(RECHARGE[r.recharge] ?? String(r.recharge))]] : [])]),
302  ]
303  if (r.note) lines.push(prose(String(r.note)))
304  return { title: String(r.name), lines, cite: 'sheet', more: null, reread: false }
305}
306
307/** A condition on the sheet: exhaustion's level, then the rule from the glossary (no duration field exists yet). */
308function conditionBox(e: Entry, cond: string): Content | null {
309  const known = CONDITIONS.find((c) => norm(c) === norm(cond))
310  if (!known) return null
311  const level = num(e.sheet.exhaustion) ?? 0
312  const ok = known === 'Exhaustion' ? level > 0 : (e.sheet.conditions ?? []).some((c: unknown) => norm(String(c)) === norm(cond))
313  const rule = ok && glossaryBox(known.toLowerCase())
314  if (!rule) return null
315  return {
316    ...rule,
317    lines: [...(known === 'Exhaustion' ? [[[lab('level '), val(String(level))]]] : []), ...rule.lines],
318    cite: rule.cite + ' · sheet',
319  }
320}
321
322function seenBox(e: Entry, now: number): Content {
323  const today = new Date(e.readAt).toDateString() === new Date(now).toDateString()
324  const at = today ? clock(e.readAt) : `${new Date(e.readAt).getDate()} ${MONTHS[new Date(e.readAt).getMonth()]}, ${clock(e.readAt)}`
325  const lines: Unit[][] = [[[lab('seen '), val(at)], [lab(`(${ago(now - e.readAt)})`)]]]
326  if (e.last) lines.push([[lab('last')], ...prose(describeChange(e.last, e.sheet))])
327  return { title: e.name, lines, cite: 'sheet', more: null, reread: true }
328}
329
330/** The DM's requests on a sheet (T0084): one line each; the pane decides nothing. */
331function requestBox(e: Entry): Content | null {
332  const reqs = Array.isArray(e.sheet.requests) ? e.sheet.requests : []
333  if (!reqs.length) return null
334  // Each field's words wrap apart; a faint ` ·` follows a field's last word.
335  const lines: Unit[][] = reqs.map((r: any) =>
336    [r?.ask, Array.isArray(r?.keys) ? r.keys.join(', ') : r?.keys, r?.by, r?.date]
337      .filter((x) => x !== undefined && x !== null && String(x).trim())
338      .map((x) => prose(String(x)))
339      .flatMap((us, i, all) => (i < all.length - 1 ? [...us.slice(0, -1), [...us.at(-1)!, lab(' ·')]] : us)),
340  )
341  lines.push(prose('decide in chat', 'label'))
342  return { title: `${e.name} · ${reqs.length} request${reqs.length === 1 ? '' : 's'}`, lines, cite: 'sheet', more: null, reread: false }
343}
344
345/** What a word's box holds, or null when it has none (the word is then plain text). */
346export function detailOf(key: string, rows: Entry[], focused: Entry | null, now: number): Content | null {
347  const [w, kind] = key.split(':', 2)
348  if (w !== 'w' || !kind) return null
349  const rest = key.slice(`w:${kind}:`.length)
350  const byId = (id: string) => [...(focused ? [focused] : []), ...rows].find((e) => e.id === id) ?? null
351  switch (kind) {
352    case 'act':
353      return focused ? actionBox(focused, rest) : null
354    case 'save':
355      return focused ? saveBox(focused, rest) : null
356    case 'skill':
357      return focused ? skillBox(focused, rest) : null
358    case 'res':
359      return focused ? resourceBox(focused, Number(rest)) : null
360    case 'cond': {
361      const at = rest.lastIndexOf(':')
362      const e = byId(rest.slice(0, at))
363      return e ? conditionBox(e, rest.slice(at + 1)) : null
364    }
365    case 'seen': {
366      const e = byId(rest)
367      return e ? seenBox(e, now) : null
368    }
369    case 'req': {
370      const e = byId(rest)
371      return e ? requestBox(e) : null
372    }
373    case 'g':
374      return glossaryBox(rest)
375    case 'n':
376      return detailOf('w:' + rest, rows, focused, now)
377    default:
378      return null
379  }
380}
381
382/**
383 * The open box: the top of `path`, titled with the whole path (`Greatsword ›
384 * Heavy › Disadvantage`), `[ ‹ ]` while nested. A word stays a word only once
385 * per box, never to a box already on the path, never at the last depth, and
386 * only where it opens something.
387 */
388export function detailAt(path: string[], rows: Entry[], focused: Entry | null, now: number): Content | null {
389  const all = path.map((k) => detailOf(k, rows, focused, now))
390  const top = all.at(-1)
391  if (!top) return null
392  const taken = new Set(path)
393  const live = (k: string) => {
394    const to = k.startsWith('w:n:') ? 'w:' + k.slice('w:n:'.length) : k
395    if (path.length >= DEPTH || taken.has(to) || !(k.startsWith('w:c:') || detailOf(k, rows, focused, now))) return false
396    taken.add(to)
397    return true
398  }
399  const lines = top.lines.map((l) => l.map((u) => u.map(({ key, ...p }) => (key && live(key) ? { ...p, key } : p))))
400  return { ...top, title: all.map((c) => c?.title ?? '…').join(' › '), lines, back: path.length > 1 }
401}
402
403// ------------------------------------------------------------------ drawing
404
405type El = Pick<Elements['mobile'], 'Box' | 'Text'>
406type Make = (props: { key: string; label: string }) => RenderElement
407/** Draws a keyed piece as its word (view.ts's `word`), which falls back to plain text. */
408type Word = (key: string, label: string, style: { bold?: true; dimColor?: true; color?: string }) => RenderNode
409
410/** A piece's style: values bold, labels faint, a warning amber. */
411const look = (p: Piece): { bold?: true; dimColor?: true; color?: string } =>
412  p.tone === 'value' ? { bold: true } : p.tone === 'label' ? { dimColor: true } : p.tone === 'warn' ? { color: TOKENS.amber } : {}
413
414/** The most body rows a box draws; past it, a faint `and N more`, or long text's sentence cut (never `…`). */
415const MAX_ROWS = 6
416const width = (u: Unit) => u.reduce((n, p) => n + p.text.length, 0)
417const SENTENCE_END = /[.!?]["”’)\]]*$/
418
419/**
420 * Items in rows of at most `w` columns, `gap` between them: the greedy wrap.
421 * Each row is drawn as its own nowrap row (the spike's line layout), since
422 * flex shrink would split a word and `flexWrap` alone hides the columns.
423 */
424export function greedy<T>(items: T[], width: (t: T) => number, w: number, gap = 1): T[][] {
425  const rows: T[][] = []
426  let cur: T[] = []
427  let used = 0
428  for (const t of items) {
429    const tw = width(t)
430    if (cur.length && used + gap + tw > w) {
431      rows.push(cur)
432      cur = []
433      used = 0
434    }
435    used += (cur.length ? gap : 0) + tw
436    cur.push(t)
437  }
438  if (cur.length) rows.push(cur)
439  return rows
440}
441
442/**
443 * The body's rows at `w` columns, at most six: past them long text ends at a
444 * sentence (`cut`), any other drops whole lines and counts them in `more`.
445 */
446function bodyRows(c: Content, w: number): { rows: Unit[][]; more: number; cut: boolean } {
447  const laid = c.lines.map((l) => greedy(l, width, w))
448  if (laid.reduce((n, rs) => n + rs.length, 0) <= MAX_ROWS) return { rows: laid.flat(), more: 0, cut: false }
449  if (c.cut) {
450    // The first six rows, ended after their last sentence; `[ more ]` has the rest.
451    const ends = (u: Unit) => SENTENCE_END.test(u.at(-1)?.text ?? '')
452    const rows = laid.flat().slice(0, MAX_ROWS)
453    const r = rows.findLastIndex((row) => row.some(ends))
454    return { rows: r < 0 ? rows : [...rows.slice(0, r), rows[r]!.slice(0, rows[r]!.findLastIndex(ends) + 1)], more: 0, cut: true }
455  }
456  const rows: Unit[][] = []
457  let k = 0
458  for (; k < laid.length && rows.length + laid[k]!.length <= MAX_ROWS - 1; k++) rows.push(...laid[k]!)
459  return { rows, more: laid.length - k, cut: false }
460}
461
462/**
463 * The box: a round border as wide as the pane's body, the title (the path's
464 * breadcrumb), `[ ‹ ]` while nested and `[ × ]`, up to six rows (each a
465 * nowrap row the wrap laid out), then `[ more ]` or `[ re-read ]` and the
466 * faint cite at the bottom right. A keyed piece is drawn by `word`. Its
467 * Buttons carry no hotkey.
468 */
469export function detailBox(el: El, make: Make, c: Content, columns: number, word: Word): RenderElement {
470  const inner = Math.max(8, columns - 4)
471  const span = (p: Piece) => (p.key ? word(p.key, p.text, look(p)) : el.Text({ children: [p.text], ...look(p) }))
472  const drawRow = (r: Unit[]) =>
473    el.Box({ flexDirection: 'row', columnGap: 1, children: r.map((u) => el.Box({ flexDirection: 'row', flexShrink: 0, children: u.map(span) })) })
474  const { rows, more, cut } = bodyRows(c, inner)
475  const body: RenderNode[] = rows.map(drawRow)
476  if (more) body.push(el.Text({ children: [`and ${more} more`], dimColor: true }))
477  const buttons = [...(c.more && (!c.cut || cut) ? [make({ key: 'detail-more', label: 'more' })] : []), ...(c.reread ? [make({ key: 'detail-reread', label: 're-read' })] : [])]
478  return el.Box({
479    key: 'detail',
480    borderStyle: 'round',
481    width: columns,
482    paddingX: 1,
483    flexDirection: 'column',
484    children: [
485      el.Box({
486        flexDirection: 'row',
487        columnGap: 1,
488        children: [
489          el.Box({ flexGrow: 1, flexShrink: 1, children: [el.Text({ children: [c.title], bold: true, wrap: 'wrap' })] }),
490          ...(c.back ? [el.Box({ flexShrink: 0, children: [make({ key: 'detail-back', label: '‹' })] })] : []),
491          el.Box({ flexShrink: 0, children: [make({ key: 'detail-x', label: '×' })] }),
492        ],
493      }),
494      ...body,
495      el.Box({
496        flexDirection: 'row',
497        justifyContent: buttons.length ? 'space-between' : 'flex-end',
498        columnGap: 1,
499        children: [...(buttons.length ? [el.Box({ flexDirection: 'row', columnGap: 1, children: buttons })] : []), el.Text({ children: [c.cite], dimColor: true })],
500      }),
501    ],
502  })
503}
504
505// ------------------------------------------------------------------ the preview
506
507/** One run of a preview row, as card.tsx draws it: a `key` makes it a term. */
508export type Cell = { text: string; bold?: true; dimColor?: true; color?: string; key?: string }
509
510/**
511 * A box as the preview's rows at `columns` (card.tsx pads a column each side):
512 * the title, the body as the box lays it out, the faint cite. `more`: the box
513 * would draw `[ more ]`, which the preview draws once pinned.
514 */
515export function cardRows(c: Content, columns: number): { rows: Cell[][]; more: boolean } {
516  const inner = Math.max(8, columns - 2)
517  const cell = (p: Piece): Cell => ({ text: p.text, ...look(p), ...(p.key ? { key: p.key } : {}) })
518  const line = (r: Unit[]): Cell[] => r.flatMap((u, i) => [...(i ? [{ text: ' ' }] : []), ...u.map(cell)])
519  const { rows, more, cut } = bodyRows(c, inner)
520  const faint = (text: string): Cell[] => [{ text, dimColor: true }]
521  return {
522    rows: [
523      ...greedy(c.title.split(' '), (w) => w.length, inner).map((ws): Cell[] => [{ text: ws.join(' '), bold: true }]),
524      ...rows.map(line),
525      ...(more ? [faint(`and ${more} more`)] : []),
526      ...(c.cite ? [faint(c.cite)] : []),
527    ],
528    more: !!c.more && (!c.cut || cut),
529  }
530}
531
532/**
533 * A fetch word's preview: hover never fetches, so it is this session's cached
534 * card, or the name, its kind and `click to open`.
535 */
536export function fetchPreview(cand: Candidate, card: Card | null): Content {
537  if (card)
538    return { title: card.title, lines: [...card.meta.map((m) => prose(m, 'label')), ...card.body.map((b) => prose(b))], cite: card.cite ?? '', more: null, reread: false, cut: true }
539  const kind = cand.kind === 'option' ? cand.key.split('|')[0]! : cand.kind
540  return { title: cand.name, lines: [prose(kind, 'label'), prose('click to open', 'label')], cite: '', more: null, reread: false }
541}
542
hooks/look.ts 171 lines
1// The default look: Alien (1979) computer interfaces meet John Provencher.
2// One text system for every surface: readout rules between sections, uppercase
3// readouts for labels, values in ink, gauges as glyph runs, one phosphor accent
4// for what is live. Pure: no mods API, and nothing reads a sheet; view.ts hands
5// in the numbers.
6//
7// The screen is the terminal: the pane paints no background and sets no theme.
8// Ink is the host's foreground (no `color`), dim is `dimColor`; only the raw
9// colours below are set. Dark is the intended look; on a light theme
10// (`useLight`, from the host's `theme` setting) the accents swap to darker
11// shades of the same hues, so they read on a white ground.
12
13import type { TextProps } from 'claude-code'
14
15/**
16 * The raw colours. Phosphor and faint are sampled from the workbench mock the
17 * owner chose (factory T0037, `B-workbench-green.png`), which Studio
18 * (`journal/`) shares, so the two tools have one green.
19 */
20const DARK = {
21  phosphor: '#4af626',
22  amber: '#f0a020',
23  alert: '#ff3b30',
24  cyan: '#3fc8e0',
25  violet: '#a07cff',
26  faint: '#6a6a6a',
27  /** The hover preview's ground (T0093 Layer 3): the pane paints none, and the preview must cover the rows under it. */
28  card: '#2b2b3c',
29  /**
30   * The words on that ground. It is dark on every theme, so its words carry their own
31   * light ink rather than the host's, which is near-black on a light theme.
32   */
33  cardInk: '#ededed',
34  cardDim: '#a8a8b8',
35}
36
37/**
38 * The light theme's accents: the same hues, dark enough for 4.5:1 on white.
39 * The neon originals wash out on a light ground (owner, 2026-10-12: "light
40 * mode for the d&d pane looks bad, hard to read"). The card keeps its own dark
41 * ground and ink on every theme.
42 */
43const LIGHT: typeof DARK = {
44  ...DARK,
45  phosphor: '#1a7f0e',
46  amber: '#9a5700',
47  alert: '#c4231b',
48  cyan: '#00728a',
49  violet: '#6a3fd6',
50  faint: '#767676',
51}
52
53/** The colours in use: dark's until `useLight` says the host's theme is light. */
54export let TOKENS: Readonly<typeof DARK> = DARK
55
56/** Picks the accents for the host's theme; true for any `light*` theme. */
57export function useLight(light: boolean): void {
58  TOKENS = light ? LIGHT : DARK
59}
60
61/** Whether a `theme` setting value is one of the light themes (`light`, `light-daltonized`, `light-ansi`). */
62export const isLightTheme = (value: unknown): boolean => typeof value === 'string' && value.startsWith('light')
63
64/**
65 * Faint words (a class line, `KEEPS`, `seen 13:19`, a readout): the host theme's own
66 * grey, a theme key, so it reads on a dark or a light ground. `TOKENS.faint` is a raw
67 * colour, kept for the pixel art, where a key cannot reach.
68 */
69export const FAINT_TEXT = 'inactive'
70
71/**
72 * A receipt's indent in the transcript: the engine's rows carry a `⏺` and two
73 * columns of indent, a hook's row carries no bullet, so the verb sits in the
74 * text column (probe run 5 showed the detail at column 0 beside an indented
75 * engine block).
76 */
77export const RECEIPT_INDENT = 2
78
79/**
80 * How long a changed value stays inverse after a write. Handoff 17: "one
81 * 'flash' frame on a changed value (step C: redraw it inverse once, then
82 * normal)."
83 */
84export const FLASH_MS = 800
85
86/** One glyph pair for every gauge, and `none` for a number never written (never the spent glyph). `▮`/`▯` wait for a live check of the players' fonts. */
87export const GAUGE = { full: '█', spent: '░', none: '·' } as const
88
89/** HP's state: phosphor above half, amber to a quarter, alert below. */
90export type HpState = 'phosphor' | 'amber' | 'alert'
91/** A gauge's full-glyph colour: an HP state, or ink for slots and resources. */
92export type Tone = HpState | 'ink'
93export type Segment = 'full' | 'spent' | 'temp' | 'none'
94
95export function hpState(current: number, max: number): HpState {
96  const frac = max > 0 ? current / max : 0
97  return frac > 0.5 ? 'phosphor' : frac >= 0.25 ? 'amber' : 'alert'
98}
99
100/**
101 * Segments for current/max plus temp: one per hit point while they fit in
102 * `room`, else each stands for several. Temp HP follows the maximum.
103 */
104export function hpSegments(current: number, max: number, temp: number, room: number): Segment[] {
105  const total = Math.max(1, max) + Math.max(0, temp)
106  const per = Math.max(1, Math.ceil(total / Math.max(1, room)))
107  const n = Math.ceil(total / per)
108  const maxSegs = Math.ceil(Math.max(1, max) / per)
109  const full = Math.min(Math.ceil(Math.max(0, current) / per), maxSegs)
110  return Array.from({ length: n }, (_, i): Segment => (i < full ? 'full' : i < maxSegs ? 'spent' : 'temp'))
111}
112
113/** `n` segments, the first `full` of them full, the rest spent. */
114export const segments = (full: number, n: number): Segment[] =>
115  Array.from({ length: n }, (_, i): Segment => (i < full ? 'full' : 'spent'))
116
117/** The band's HP gauge: `round(current / max × cells)` full, the rest spent. */
118export function bandSegments(current: number, max: number, cells = 10): Segment[] {
119  const frac = max > 0 ? current / max : 0
120  return segments(Math.max(0, Math.min(cells, Math.round(frac * cells))), cells)
121}
122
123/** A gauge for a number the sheet has never held: `cells` empty, faint segments. */
124export const noneSegments = (cells = 10): Segment[] => Array(cells).fill('none')
125
126/** One run of a gauge: the glyphs and the props of the `Text` that draws them. */
127export interface Run {
128  text: string
129  props: TextProps
130}
131
132const toneProps = (tone: Tone): TextProps => (tone === 'ink' ? {} : { color: TOKENS[tone] })
133
134/**
135 * The `Text` runs for one gauge: full glyphs in the tone's colour, spent ones
136 * dim, temp as cyan full glyphs, none as faint dots; empty runs dropped. `spaced` puts a space
137 * between glyphs (slot and resource pips).
138 */
139export function gaugeRuns(segments: Segment[], tone: Tone, opts: { spaced?: boolean } = {}): Run[] {
140  const sep = opts.spaced ? ' ' : ''
141  const runs: Run[] = []
142  const add = (seg: Segment, props: TextProps) => {
143    const n = segments.filter((s) => s === seg).length
144    if (!n) return
145    const glyph = seg === 'spent' ? GAUGE.spent : seg === 'none' ? GAUGE.none : GAUGE.full
146    runs.push({ text: (runs.length ? sep : '') + Array(n).fill(glyph).join(sep), props })
147  }
148  add('full', toneProps(tone))
149  add('spent', { dimColor: true })
150  add('temp', { color: TOKENS.cyan })
151  add('none', { color: TOKENS.faint })
152  return runs
153}
154
155/**
156 * Pips for `left` of `max` in `width` cells: a glyph each with a space between
157 * while they fit, else a meter of `width` glyphs without spaces.
158 */
159export function pipRuns(left: number, max: number, width: number, tone: Tone): Run[] {
160  const spaced = max * 2 - 1 <= width
161  const n = spaced ? max : width
162  const full = spaced ? left : Math.round((width * left) / Math.max(1, max))
163  return gaugeRuns(segments(full, n), tone, { spaced })
164}
165
166/** A readout rule, `── LABEL ───…`, exactly `columns` characters; `── ───…` without a label. */
167export function rule(label: string, columns: number): string {
168  const head = label ? `── ${label.toUpperCase()} ` : '── '
169  return (head + '─'.repeat(Math.max(0, columns - head.length))).slice(0, columns)
170}
171
hooks/lookup.ts 313 lines
1// Lookups (T0085 stage 1): what the DM or a player types into `[ look up ]`,
2// matched against the spells the facts table knows, the 2024 conditions and
3// the fight's monsters; and the card a match opens, drawn from the facts row
4// at once and from the rules server's answer once a press fetched it. Pure:
5// no mods API (register.ts calls the tools, view.ts draws).
6
7import { norm, weaponFact } from './actions.ts'
8import { SPELLS, type SpellRow } from './facts.ts'
9import { GLOSSARY } from './glossary.ts'
10
11export { norm }
12
13/**
14 * A card's subject. `glossary` is drawn from `GLOSSARY` with no fetch; `option`
15 * (a feature, feat, species or item, from the sheet's tabs or a glossary link)
16 * is fetched by `character_option_get`, its key `kind|name|feature`.
17 */
18export type Candidate = { name: string; kind: 'spell' | 'condition' | 'monster' | 'glossary' | 'option'; key: string }
19
20export type Card = { title: string; meta: string[]; body: string[]; cite: string | null }
21
22export const CONDITIONS = [
23  'Blinded', 'Charmed', 'Deafened', 'Exhaustion', 'Frightened', 'Grappled', 'Incapacitated', 'Invisible',
24  'Paralyzed', 'Petrified', 'Poisoned', 'Prone', 'Restrained', 'Stunned', 'Unconscious',
25] as const
26
27const SMALL = new Set(['of', 'the', 'and', 'with', 'to', 'from', 'in', 'on'])
28
29/** A facts key's name as a reader writes it: `tasha s hideous laughter` → "Tasha's Hideous Laughter". */
30export function displayName(keyName: string): string {
31  return keyName
32    .replace(/(\w) s\b/g, "$1's")
33    .split(' ')
34    .map((w, i) => (i > 0 && SMALL.has(w) ? w : w.charAt(0).toUpperCase() + w.slice(1)))
35    .join(' ')
36}
37
38/** One spell per name: its `|xphb` key when there is one (2024, as `spell_get` defaults), else its first. */
39const SPELL_CANDS: Candidate[] = (() => {
40  const keys = new Map<string, string>()
41  for (const k of Object.keys(SPELLS)) {
42    const name = k.slice(0, k.lastIndexOf('|'))
43    const had = keys.get(name)
44    if (!had || (k.endsWith('|xphb') && !had.endsWith('|xphb'))) keys.set(name, k)
45  }
46  return [...keys].map(([name, key]) => ({ name: displayName(name), kind: 'spell' as const, key }))
47})()
48
49const CONDITION_CANDS: Candidate[] = CONDITIONS.map((name) => ({ name, kind: 'condition', key: norm(name) }))
50
51/** Everything a look can open: the spells, the conditions, and `monsters` (deduped by `norm`). */
52export function candidates(monsters: string[]): Candidate[] {
53  const seen = new Set<string>()
54  const mons: Candidate[] = []
55  for (const m of monsters) {
56    const key = norm(m)
57    if (!key || seen.has(key)) continue
58    seen.add(key)
59    mons.push({ name: m.trim(), kind: 'monster', key })
60  }
61  return [...mons, ...SPELL_CANDS, ...CONDITION_CANDS]
62}
63
64const KIND_ORDER = { monster: 0, spell: 1, condition: 2, glossary: 3, option: 4 } as const
65
66/** 0 exact, 1 whole-name prefix, 2 word prefix, 3 substring; -1 no match. */
67function tier(q: string, name: string): number {
68  if (name === q) return 0
69  if (name.startsWith(q)) return 1
70  if ((' ' + name).includes(' ' + q)) return 2
71  if (name.includes(q)) return 3
72  return -1
73}
74
75/** The best `n` candidates for `query`: exact, prefix, word prefix, substring; ties monsters, spells, conditions, then A–Z. */
76export function matches(query: string, cands: Candidate[], n = 5): Candidate[] {
77  const q = norm(query)
78  if (!q) return []
79  return cands
80    .map((c) => ({ c, t: tier(q, norm(c.name)) }))
81    .filter((x) => x.t >= 0)
82    .sort((a, b) => a.t - b.t || KIND_ORDER[a.c.kind] - KIND_ORDER[b.c.kind] || a.c.name.localeCompare(b.c.name))
83    .slice(0, n)
84    .map((x) => x.c)
85}
86
87const ATTACK: Record<string, string> = { m: 'Melee', r: 'Ranged', 'm,r': 'Melee or Ranged', 'r,m': 'Melee or Ranged' }
88
89/**
90 * `{@damage 3d8}` → `3d8`, `{@condition prone|xphb}` → `prone`, a stat
91 * block's `{@atkr m} {@hit 3}` → `Melee Attack Roll: +3` and `{@h}` → `Hit: `;
92 * nested tags from the inside out.
93 */
94const untag = (s: string) => {
95  let out = s
96    .replace(/\{@atkr? ([^{}]*)\}/g, (_, k: string) => `${ATTACK[k.trim()] ?? k} Attack Roll:`)
97    .replace(/\{@hit (-?\d+)\}/g, (_, n: string) => (n.startsWith('-') ? n : '+' + n))
98    .replace(/\{@h\}/g, 'Hit: ')
99    .replace(/\{@dc (\d+)\}/g, 'DC $1')
100  for (let prev = ''; prev !== out; ) {
101    prev = out
102    out = out.replace(/\{@\w+ ([^{}|]*)(?:\|[^{}]*)?\}/g, '$1')
103  }
104  return out
105}
106
107const cellText = (v: unknown): string => (typeof v === 'string' ? untag(v) : flatten([v]).join(' '))
108
109/** 5etools entries as plain lines: strings, named entries (`Name. text`), lists (`• `), tables (cells ` | `); the rest skipped. */
110export function flatten(entries: unknown): string[] {
111  if (!Array.isArray(entries)) return []
112  const out: string[] = []
113  for (const e of entries) {
114    if (typeof e === 'string') {
115      out.push(untag(e))
116      continue
117    }
118    if (!e || typeof e !== 'object') continue
119    const o = e as Record<string, any>
120    if (o.type === 'entries' || o.type === 'item') {
121      const lines = flatten(o.entries ?? (o.entry !== undefined ? [o.entry] : []))
122      if (o.name) {
123        const [first, ...rest] = lines
124        out.push(`${untag(String(o.name))}.` + (first ? ' ' + first : ''), ...rest)
125      } else out.push(...lines)
126    } else if (o.type === 'list') {
127      for (const item of o.items ?? []) for (const line of flatten([item])) out.push('• ' + line)
128    } else if (o.type === 'table') {
129      for (const r of o.rows ?? []) if (Array.isArray(r)) out.push(r.map(cellText).join(' | '))
130    }
131  }
132  return out
133}
134
135export const SCHOOLS: Record<string, string> = {
136  A: 'Abjuration', C: 'Conjuration', D: 'Divination', E: 'Enchantment', V: 'Evocation', I: 'Illusion', N: 'Necromancy', T: 'Transmutation',
137}
138
139/** A cantrip's table (`1:1d10 5:2d10`) as `1d10, 2d10 at 5`; a slot spell's dice as they are. */
140const diceText = (dice: string) =>
141  dice.includes(':')
142    ? dice.split(' ').map((p, i) => {
143        const [lv, d] = p.split(':')
144        return i ? `${d} at ${lv}` : d
145      }).join(', ')
146    : dice
147
148/** A spell's facts row as the card's meta: level and school, time, range, components, duration, the roll, dice, damage types. */
149function spellMeta(row: SpellRow): string[] {
150  const [level, school, time, range, comps, duration, flagText, types, save, dice] = row
151  const flags = flagText.split(' ')
152  const sch = SCHOOLS[school] ?? school
153  const meta = [
154    (level === 0 ? `${sch} cantrip` : `Level ${level} ${sch}`) + (flags.includes('ritual') ? ' (ritual)' : ''),
155    time,
156    range,
157    comps.split('').join(', '),
158    (flags.includes('conc') ? 'Concentration, ' : '') + duration,
159  ]
160  if (flags.includes('ranged')) meta.push('ranged spell attack')
161  else if (flags.includes('melee')) meta.push('melee spell attack')
162  else if (save) meta.push(`${save} save`)
163  if (dice) meta.push(diceText(dice))
164  if (types) meta.push(types.split(',').join(', '))
165  return meta.filter(Boolean)
166}
167
168const mod = (score: unknown) => {
169  const n = Math.floor((Number(score) - 10) / 2)
170  return Number.isFinite(n) ? (n >= 0 ? '+' + n : '−' + -n) : '?'
171}
172
173const acText = (ac: unknown) => {
174  const first = Array.isArray(ac) ? ac[0] : ac
175  return typeof first === 'number' ? String(first) : first && typeof first === 'object' && 'ac' in first ? String((first as any).ac) : '?'
176}
177
178const speedText = (s: unknown) => {
179  if (typeof s === 'number') return `${s} ft`
180  if (!s || typeof s !== 'object') return '?'
181  return Object.entries(s as Record<string, any>)
182    .filter(([, v]) => typeof v === 'number' || (v && typeof v === 'object' && 'number' in v))
183    .map(([k, v]) => `${k === 'walk' ? '' : k + ' '}${typeof v === 'number' ? v : v.number} ft`)
184    .join(', ')
185}
186
187const crText = (cr: unknown) => (typeof cr === 'string' ? cr : cr && typeof cr === 'object' && 'cr' in cr ? String((cr as any).cr) : '?')
188
189/** A monster's answer as meta lines: AC, HP and formula, speed, the six modifiers, CR. */
190function monsterMeta(p: Record<string, any>): string[] {
191  const hp = p.hp && typeof p.hp === 'object' ? (p.hp.average !== undefined ? `HP ${p.hp.average}${p.hp.formula ? ` (${p.hp.formula})` : ''}` : `HP ${p.hp.special ?? '?'}`) : 'HP ?'
192  return [
193    `AC ${acText(p.ac)}`,
194    hp,
195    `Speed ${speedText(p.speed)}`,
196    ['str', 'dex', 'con', 'int', 'wis', 'cha'].map((a) => `${a.toUpperCase()} ${mod(p[a])}`).join(' '),
197    `CR ${crText(p.cr)}`,
198  ]
199}
200
201const ARMOR: Record<string, (ac: unknown) => string> = {
202  LA: (ac) => `Light armor, AC ${ac} + Dex`,
203  MA: (ac) => `Medium armor, AC ${ac} + Dex (max 2)`,
204  HA: (ac) => `Heavy armor, AC ${ac}`,
205  S: (ac) => `Shield, AC +${ac}`,
206}
207
208const coins = (cp: number) => (cp % 100 === 0 ? `${cp / 100} gp` : cp % 10 === 0 ? `${cp / 10} sp` : `${cp} cp`)
209
210/** A base item's answer as meta lines: a weapon's facts row, or armor's AC and needs; then weight and cost. */
211function itemMeta(p: Record<string, any>): string[] {
212  const c = p.citation ?? {}
213  const meta: string[] = []
214  const w = p.weapon && typeof c.name === 'string' ? weaponFact(c.name, c.source, c.edition) : null
215  if (w) {
216    const [category, kind, dice, type, versatile, props, range, mastery] = w.row
217    meta.push(`${category.charAt(0).toUpperCase() + category.slice(1)} ${kind} weapon`, `${dice} ${type}` + (versatile ? ` (${versatile} two-handed)` : ''))
218    if (props) meta.push(props.split(',').join(', '))
219    if (range) meta.push(`Range ${range} ft`)
220    if (mastery) meta.push(`Mastery: ${mastery}`)
221  }
222  const armor = ARMOR[String(p.type ?? '').split('|')[0]!]
223  if (armor) {
224    meta.push(armor(p.ac))
225    if (p.strength) meta.push(`Str ${p.strength}`)
226    if (p.stealth) meta.push('Stealth Disadvantage')
227  }
228  if (typeof p.weight === 'number') meta.push(`${p.weight} lb`)
229  if (typeof p.value === 'number') meta.push(coins(p.value))
230  return meta
231}
232
233/** A monster's traits, then actions, bonus actions and reactions, each `Name. text`. */
234const monsterBody = (p: Record<string, any>) =>
235  ['trait', 'action', 'bonus', 'reaction'].flatMap((k) =>
236    flatten((Array.isArray(p[k]) ? p[k] : []).map((x: any) => ({ type: 'entries', name: x?.name, entries: x?.entries ?? [] }))),
237  )
238
239/** A spell candidate's facts row, for its card's meta before the fetch lands; null for the rest. */
240export const factsRow = (cand: Candidate): SpellRow | null => (cand.kind === 'spell' ? SPELLS[cand.key] ?? null : null)
241
242/** The card: the facts row's meta at once (spells), then the server's answer: its name, body and citation. */
243export function cardOf(cand: Candidate, payload: unknown, row: SpellRow | null): Card {
244  if (cand.kind === 'glossary') {
245    const g = GLOSSARY[cand.key]
246    const body = g ? g[1].replace(/⟦[^|⟧]*\|([^⟧]*)⟧/g, '$1').split('\n') : []
247    return { title: g?.[0] ?? cand.name, meta: [], body, cite: g ? `${g[2]} p${g[3]}, 2024` : null }
248  }
249  const p = payload && typeof payload === 'object' ? (payload as Record<string, any>) : null
250  const c = p?.citation
251  const cite = c && typeof c === 'object' && c.source ? `${c.source} p${c.page ?? '?'}, ${c.edition ?? '?'}` : null
252  const title = typeof p?.name === 'string' ? p.name : cand.name
253  if (cand.kind === 'spell') {
254    return { title, meta: row ? spellMeta(row) : [], body: p ? [...flatten(p.entries), ...flatten(p.entriesHigherLevel)] : [], cite }
255  }
256  if (cand.kind === 'monster') return { title, meta: p ? monsterMeta(p) : [], body: p ? monsterBody(p) : [], cite }
257  if (cand.kind === 'option') {
258    // A class or subclass feature's answer carries `feature.text`; a species', `traits`
259    // (the pressed one, else all of them); an item's, its facts as meta; the rest, `entries`.
260    const text = p?.feature?.text
261    const name = p?.feature?.name ?? c?.name
262    const named = typeof name === 'string' ? name : cand.name
263    const traits = Array.isArray(p?.traits) ? p.traits.filter((t: any) => typeof t?.name === 'string' && typeof t?.text === 'string') : []
264    if (cand.key.startsWith('species|') && traits.length) {
265      const one = traits.find((t: any) => norm(t.name) === norm(cand.name))
266      if (one) return { title: one.name, meta: [], body: one.text.split(/\n+/).filter(Boolean), cite }
267      return { title: named, meta: [], body: traits.map((t: any) => `${t.name}. ${t.text}`), cite }
268    }
269    const meta = p && cand.key.startsWith('item|') ? itemMeta(p) : []
270    return { title: named, meta, body: typeof text === 'string' ? text.split(/\n+/).filter(Boolean) : p ? flatten(p.entries) : [], cite }
271  }
272  return { title, meta: [], body: p ? flatten(p.entries) : [], cite }
273}
274
275/**
276 * Ask Claude's prompt: the subject only (the typed text, or the card's title
277 * and cite), the session, and the pane it came from; and `tail`, the heard
278 * file's last minute of text, when the party pane has a fresh one. Nothing in it logs.
279 */
280export function askText({ subject, pane, session, tail }: { subject: string | { title: string; cite: string | null }; pane: 'Party' | 'Sheet'; session: string | null; tail?: string | null }): string {
281  const s = session ? ` (${session})` : ''
282  const about = typeof subject === 'string' ? `Table question${s}: ${subject}` : `Table question${s} about ${subject.title}` + (subject.cite ? ` (${subject.cite})` : '')
283  const heard = tail ? ` Heard at the table in the last minute (local live transcript; names may be misheard): "${tail}".` : ''
284  return `${about}, from the ${pane} pane.${heard} Answer from the rules server and cite it, in at most four lines. If the text doesn't settle it, say so and give the options; the DM rules.`
285}
286
287// ------------------------------------------------------------------ heard (T0085 stage 2)
288
289/** The live listener's file (capture/live.py): text only, rewritten every few seconds, deleted when it stops. */
290export const HEARD_PATH = '/tmp/toa-live/heard.json'
291/** A heard file not rewritten for this long is treated as absent. */
292const HEARD_STALE_MS = 10 * 60_000
293
294export type HeardItem = { at: number; name: string; kind: 'spell' | 'condition' }
295/** The heard file: its items newest first, and the last minute of heard text. */
296export type Heard = { updated: number; items: HeardItem[]; tail: string }
297
298/** The heard file's text as a Heard; null when there is none, it does not parse, its `v` is not 1, or it is stale. */
299export function asHeard(text: string | null, now: number): Heard | null {
300  if (!text) return null
301  let j: any
302  try {
303    j = JSON.parse(text)
304  } catch {
305    return null
306  }
307  if (!j || j.v !== 1 || typeof j.updated !== 'number' || now - j.updated > HEARD_STALE_MS || !Array.isArray(j.items)) return null
308  const items: HeardItem[] = j.items
309    .filter((x: any) => x && typeof x.at === 'number' && typeof x.name === 'string' && (x.kind === 'spell' || x.kind === 'condition'))
310    .map((x: any) => ({ at: x.at, name: x.name, kind: x.kind }))
311  return { updated: j.updated, items, tail: typeof j.tail === 'string' ? j.tail : '' }
312}
313
hooks/receipt.ts 252 lines
1// A connector call's row in the transcript, as one line of words: a verb
2// readout (`WRITE`, `CHECK`, `SPELL`) and the answer, the citation inline as
3// the server gave it. The verb and shape come from the output, never the
4// input, so a mismatched answer passes; words may come from the input (a
5// preview's reason, a create's action). Anything the shapes below do not
6// match is `null`: the row stays Claude Code's own.
7// Vault receipts describe the request; LOGGED/CLOSED alone are confirmed by
8// the answer. The engine's result block is their detail. Interrupted rows pass.
9//
10// Pure and synchronous: every pane invalidate redraws every connector row
11// (`$.ui.invalidate('ui.render')` is plugin-wide). No mods API here.
12
13import { asApplied, asCheck, asGet, describeChange, payloadOf, textOf, type DiffItem, type Finding } from './sheet.ts'
14
15/** The rules connector's tools that draw a receipt; each has a fixture in tests/fixtures/bati. */
16export const CONNECTOR =
17  /^mcp__.+__(sheet_read|sheet_write|level_up|spell_get|monster_get|character_option_get|condition_search|variantrule_search|book_content_get)$/
18
19/** The vault's tools whose rows draw a receipt during play; `receipt()` draws the Table kinds and the reads. */
20export const VAULT = /^mcp__vault__(vault_query|canon_query|draft_write)$/
21
22export interface Receipt {
23  verb: string
24  body: string
25  state: 'running' | 'done' | 'error'
26  /** Lines the row cannot hold (findings in words), drawn over the result block in ctrl+o. */
27  detail: string[]
28}
29
30/** A `ToolUse` row's props, or a `ToolResult`'s with `isRunning: false` and no input. */
31export interface Row {
32  tool: string
33  input?: unknown
34  isRunning: boolean
35  isErrored: boolean
36  isInterrupted?: boolean
37  output?: unknown
38}
39
40type Sheets = (id: string) => Record<string, any> | undefined
41
42export const isObj = (v: unknown): v is Record<string, any> => !!v && typeof v === 'object' && !Array.isArray(v)
43const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined)
44const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`
45
46const KIND: Record<string, string> = {
47  class: 'CLASS',
48  subclass: 'SUBCLASS',
49  feat: 'FEAT',
50  species: 'SPECIES',
51  background: 'BACKGROUND',
52  item: 'ITEM',
53  optional_feature: 'FEATURE',
54  class_spells: 'SPELLS',
55}
56
57const FIXED: Record<string, string> = {
58  level_up: 'LEVEL UP',
59  spell_get: 'SPELL',
60  monster_get: 'MONSTER',
61  condition_search: 'CONDITION',
62  variantrule_search: 'RULE',
63  book_content_get: 'BOOK',
64}
65
66const READS: Record<string, string> = { get: 'READ', list: 'LIST', history: 'HISTORY', check: 'CHECK', schema: 'SCHEMA' }
67
68const suffix = (tool: string) => tool.match(CONNECTOR)?.[1] ?? tool
69const request = (input: unknown): Record<string, any> => (isObj(input) && isObj(input.request) ? input.request : {})
70const kindVerb = (input: unknown) => (isObj(input) && KIND[input.kind]) || 'OPTION'
71
72/** The verb a call draws while it runs, from its input alone. */
73export function runningVerb(tool: string, input: unknown): string {
74  const t = suffix(tool)
75  const action = request(input).action
76  if (t === 'sheet_read') return READS[action] ?? 'READ'
77  if (t === 'sheet_write') return isObj(input) && input.apply === true ? (action === 'create' ? 'CREATE' : 'WRITE') : 'PREVIEW'
78  if (t === 'character_option_get') return kindVerb(input)
79  return FIXED[t] ?? t.toUpperCase()
80}
81
82/** ` · PHB p.186`: the source, and the page unless its evidence is absent; `''` without a source. */
83export function cite(c: unknown): string {
84  if (!isObj(c) || typeof c.source !== 'string') return ''
85  return ` · ${c.source}` + (typeof c.page === 'number' && c.page_evidence !== 'absent' ? ` p.${c.page}` : '')
86}
87
88/** `PHB p.186 · Resting > Long Rest`: a citation on its own line, with its section. */
89export function citeLine(c: unknown): string {
90  const head = cite(c).slice(3)
91  return head && isObj(c) && typeof c.section === 'string' ? `${head} · ${c.section}` : head
92}
93
94/** Findings in words, warnings first: `⚠ message · PHB p.174 · section`, `· message` for the rest. */
95export function findingLines(findings: Finding[]): string[] {
96  const line = (f: Finding, mark: string) => {
97    const c = citeLine(f.citation)
98    return `${mark} ${f.message}` + (c ? ` · ${c}` : '')
99  }
100  const warn = findings.filter((f) => f.severity === 'warning')
101  return [...warn.map((f) => line(f, '⚠')), ...findings.filter((f) => f.severity !== 'warning').map((f) => line(f, '·'))]
102}
103
104const done = (verb: string, body: string, detail: string[] = []): Receipt => ({ verb, body, state: 'done', detail })
105
106function firstSentence(text: string): string {
107  const m = text.match(/^[\s\S]*?\.(?=\s|$)/)
108  return (m ? m[0] : text).slice(0, 200)
109}
110
111const validDiff = (v: unknown): v is DiffItem[] => Array.isArray(v) && v.every((x) => isObj(x) && typeof x.path === 'string')
112
113/** The change in words plus the first diff item's rule: `HP 12 → 15 · long rest · PHB p.186`. */
114function change(character: string, reason: unknown, diff: DiffItem[], sheetOf: Sheets): string {
115  const body = describeChange({ version: 0, at: 0, reason: str(reason) ?? '', diff }, sheetOf(character) ?? {})
116  return body + cite(diff[0]?.rule)
117}
118
119function sheetRead(d: unknown, sheetOf: Sheets): Receipt | null {
120  const got = asGet(d)
121  if (got) return done('READ', got.sheet.name)
122  const check = asCheck(d)
123  if (check) {
124    const name = sheetOf(check.character.id)?.name ?? check.character.id
125    const w = check.findings.filter((f) => f.severity === 'warning').length
126    const i = check.findings.length - w
127    const counts = check.findings.length ? `${plural(w, 'warning', 'warnings')} · ${plural(i, 'note', 'notes')}` : 'clean'
128    return done('CHECK', `${name} · ${counts}`, findingLines(check.findings))
129  }
130  if (Array.isArray(d) && d.every((x) => isObj(x) && typeof x.id === 'string' && typeof x.name === 'string'))
131    return done('LIST', d.length ? d.map((x) => x.name).join(', ') : 'no sheets')
132  if (isObj(d) && isObj(d.character) && typeof d.character.id === 'string' && Array.isArray(d.versions)) {
133    const name = sheetOf(d.character.id)?.name ?? d.character.id
134    return done('HISTORY', `${name} · ${plural(d.versions.length, 'version', 'versions')}`)
135  }
136  if (isObj(d) && isObj(d.schema) && (d.schema.$schema || d.schema.properties)) return done('SCHEMA', 'sheet')
137  return null
138}
139
140function sheetWrite(d: unknown, input: unknown, sheetOf: Sheets): Receipt | null {
141  const req = request(input)
142  const w = asApplied(d)
143  if (w) {
144    const allAdds = w.diff.every((x) => !('from' in x))
145    if ((allAdds && !sheetOf(w.character)) || req.action === 'create') {
146      const parts = [w.name ?? w.character, str(req.reason), plural(w.diff.length, 'field', 'fields')]
147      return done('CREATE', parts.filter((p) => p !== undefined).join(' · '))
148    }
149    const rules = [...new Set(w.diff.map((x) => citeLine(x.rule)).filter((l) => l))]
150    return done('WRITE', change(w.character, req.reason, w.diff, sheetOf), rules.length > 1 ? rules : [])
151  }
152  if (isObj(d) && d.preview === true && typeof d.character === 'string' && validDiff(d.diff)) {
153    const findings: Finding[] = Array.isArray(d.findings) ? d.findings.filter((f: unknown) => isObj(f) && typeof f.message === 'string') : []
154    const warnings = findings.filter((f) => f.severity === 'warning')
155    const body = change(d.character, req.reason, d.diff, sheetOf)
156    return done('PREVIEW', body + (warnings.length ? ' · ' + plural(warnings.length, 'warning', 'warnings') : ''), findingLines(warnings))
157  }
158  return null
159}
160
161function lookup(t: string, d: unknown, input: unknown): Receipt | null {
162  if (!isObj(d)) return null
163  if (t === 'level_up') {
164    const l = d.level
165    if (!isObj(l) || typeof l.class !== 'string' || typeof l.from !== 'number' || typeof l.to !== 'number') return null
166    const names = Array.isArray(d.features) ? d.features.map((f: any) => str(f?.name)).filter((n: unknown) => n) : []
167    return done(FIXED[t]!, `${l.class} ${l.from} → ${l.to}` + (names.length ? ' · ' + names.join(', ') : '') + cite(d.citation))
168  }
169  if (t === 'condition_search' || t === 'variantrule_search') {
170    const results = Array.isArray(d.results) ? d.results.filter((r: unknown) => isObj(r) && typeof r.name === 'string') : []
171    if (!results.length) return null
172    if (results.length === 1) return done(FIXED[t]!, results[0].name + cite(results[0].citation))
173    return done(FIXED[t]!, results.slice(0, 3).map((r: any) => r.name).join(', ') + ` · ${results.length} results`)
174  }
175  if (t === 'book_content_get') {
176    const c = d.citation
177    if (!isObj(c) || typeof c.source !== 'string') return null
178    if (typeof c.section === 'string') return done('BOOK', c.section + cite(c))
179    return Array.isArray(d.sections) ? done('BOOK', `${c.source} · ${plural(d.sections.length, 'section', 'sections')}`) : null
180  }
181  if (!isObj(d.citation) || typeof d.citation.name !== 'string') return null
182  if (t === 'character_option_get') return done(kindVerb(input), d.citation.name + cite(d.citation))
183  if (t === 'spell_get' || t === 'monster_get') return done(FIXED[t]!, d.citation.name + cite(d.citation))
184  return null
185}
186
187/** Vault reads say what was asked; only a confirmed Table write says LOGGED/CLOSED. */
188function vaultReceipt(t: string, row: Row): Receipt | null {
189  const input = isObj(row.input) ? row.input : {}
190  const req = request(row.input)
191  const write = t === 'draft_write'
192  const note = input.kind === 'table-note'
193  let verb: string
194  let body: string
195  if (write) {
196    if (!note && input.kind !== 'table-close') return null
197    if (typeof input.text !== 'string' || typeof input.session !== 'string') return null
198    verb = note ? 'LOGGED' : 'CLOSED'
199    body = note ? input.text : `${input.session} · ${input.text}`
200  } else if (t === 'vault_query') {
201    if (typeof req.action !== 'string') return null
202    verb = 'VAULT'
203    const arg = [req.id, req.name, req.npc, req.query, req.text, req.since, req.session].find((v) => typeof v === 'string')
204    body = req.action + (arg === undefined ? '' : ` ${arg}`)
205  } else {
206    verb = 'CANON'
207    if (req.action === 'search' && typeof req.query === 'string')
208      body = `search "${req.query}"` + (typeof req.book === 'string' ? ` · ${req.book}` : '')
209    else if (req.action === 'page' && typeof req.book === 'string' && typeof req.printed_page === 'number')
210      body = `${req.book} p.${req.printed_page}`
211    else return null
212  }
213  if (row.isRunning && row.output === undefined)
214    return { verb: write ? (note ? 'LOG' : 'CLOSE') : verb, body: (write ? input.text : body) + ' …', state: 'running', detail: [] }
215  if (row.isErrored) {
216    const text = textOf(row.output)
217    return text ? { verb: write ? 'REFUSED' : 'ERROR', body: firstSentence(text), state: 'error', detail: [] } : null
218  }
219  const p = payloadOf(row.output)
220  if (!p || !('data' in p)) return null
221  if (write && (!isObj(p.data) || p.data.wrote !== true)) return null
222  if (t === 'canon_query' && req.action === 'search' && isObj(p.data) && p.data.total === 0) body += ' · NO HIT'
223  return done(verb, body)
224}
225
226/** The receipt for a connector row, or null when the row should stay Claude Code's. */
227export function receipt(row: Row, sheetOf: Sheets): Receipt | null {
228  const v = row.tool.match(VAULT)
229  if (v && !row.isInterrupted) return vaultReceipt(v[1]!, row)
230  const m = row.tool.match(CONNECTOR)
231  if (!m || row.isInterrupted) return null
232  const t = m[1]!
233  const sheetTool = t === 'sheet_read' || t === 'sheet_write'
234  if (row.isRunning && row.output === undefined) {
235    const req = request(row.input)
236    const i = isObj(row.input) ? row.input : {}
237    const words = [req.reason, req.action, i.name, i.query, i.section, i.source, i.class].find((w) => typeof w === 'string') ?? t
238    return { verb: runningVerb(row.tool, row.input), body: words + ' …', state: 'running', detail: [] }
239  }
240  if (row.isErrored) {
241    const text = textOf(row.output)
242    if (!text) return null
243    const body = firstSentence(text)
244    return { verb: sheetTool ? 'REFUSED' : 'ERROR', body, state: 'error', detail: text.length > body.length ? [text] : [] }
245  }
246  const p = payloadOf(row.output)
247  if (!p || !('data' in p)) return null
248  if (t === 'sheet_read') return sheetRead(p.data, sheetOf)
249  if (t === 'sheet_write') return sheetWrite(p.data, row.input, sheetOf)
250  return lookup(t, p.data, row.input)
251}
252
hooks/sheet.ts 343 lines
1// The sheet the pane draws, built only from the rules connector's own results.
2// `sheet_read get` gives the whole picture; a `sheet_write` result's diff is
3// applied to the cached copy, which then waits for the next get. Nothing here
4// computes a rule: the numbers are the server's `sheet` and `derived`.
5// No mods API here (validation forbids passing `$` to an imported function).
6
7export interface DiffItem {
8  path: string
9  from?: unknown
10  to?: unknown
11  rule?: unknown
12}
13
14export interface Change {
15  version: number
16  at: number
17  reason: string
18  diff: DiffItem[]
19}
20
21export interface Entry {
22  id: string
23  name: string
24  owner: string | null
25  version: number
26  sheet: Record<string, any>
27  derived: Record<string, any> | null
28  unresolved: string[]
29  /** When a get last confirmed this copy. */
30  readAt: number
31  /** When this copy last changed (a get or an applied diff). */
32  seenAt: number
33  /** The tool name's server part, for the record. */
34  server: string
35  /** A write's diff was applied and no get has confirmed it yet. */
36  refreshing: boolean
37  /** That diff touched something `derived` is computed from. */
38  derivedPending: boolean
39  /** Loaded from the store, written by an earlier session. */
40  fromStore: boolean
41  /** A write's diff disagreed with this copy (`applyDiff`'s `matched: false`): it missed a version. A get clears it. */
42  drift: boolean
43  last: Change | null
44  /** The last `sheet_read check` of this sheet, counts only (the findings stay in the transcript). */
45  check?: { at: number; version: number; warnings: number; infos: number }
46}
47
48type Payload = { data: unknown } | { error: string }
49
50function parseText(text: string): Payload | null {
51  try {
52    return { data: JSON.parse(text) }
53  } catch {
54    return null
55  }
56}
57
58/** A result's text as the model read it: a string, or content blocks joined. */
59export function textOf(v: unknown): string {
60  if (typeof v === 'string') return v
61  if (Array.isArray(v)) return v.map(textOf).join('')
62  if (v && typeof v === 'object') {
63    const o = v as Record<string, unknown>
64    if (o.type === 'text' && typeof o.text === 'string') return o.text
65    if (typeof o.text === 'string') return o.text
66    if ('content' in o) return textOf(o.content)
67    if ('result' in o) return textOf(o.result)
68  }
69  return ''
70}
71
72/**
73 * A tool result unwrapped to the server's JSON. From a tool.call hook's
74 * `next(e)` Claude Code (2.1.288 types) gives `{ ref, result, text }`, `text`
75 * being the result as the model reads it, with `isError` on a failure; from
76 * `$.tool.call`, the same shape; MCP's own `{ content, isError }` also parses.
77 * The shape checks below decide whether the JSON is ours.
78 */
79export function payloadOf(result: unknown): Payload | null {
80  if (result === null || result === undefined) return null
81  if (typeof result === 'string') return parseText(result)
82  if (Array.isArray(result)) return parseText(textOf(result))
83  if (typeof result !== 'object') return null
84  const o = result as Record<string, unknown>
85  if ('deny' in o) return null
86  if (o.isError === true) return { error: textOf(o) }
87  if (typeof o.text === 'string') {
88    const p = parseText(o.text)
89    if (p) return p
90  }
91  if (o.structuredContent && typeof o.structuredContent === 'object') return { data: o.structuredContent }
92  if ('content' in o) return payloadOf(o.content)
93  if ('result' in o) return payloadOf(o.result)
94  return null
95}
96
97const isObj = (v: unknown): v is Record<string, any> => !!v && typeof v === 'object' && !Array.isArray(v)
98
99export interface GetPayload {
100  character: { id: string; owner?: string; version: number; updated_at?: string }
101  sheet: Record<string, any>
102  derived: Record<string, any> | null
103  unresolved: string[]
104}
105
106/**
107 * A `sheet_read get` answer of the head, or null when the payload is anything
108 * else. A get of an old version (`character.showing_version` set) is null too:
109 * its sheet is the old one but `character.version` is the head, so caching it
110 * would draw history as current, confirmed by every list after.
111 */
112export function asGet(d: unknown): GetPayload | null {
113  if (!isObj(d) || !isObj(d.character) || !isObj(d.sheet)) return null
114  const c = d.character
115  if (c.showing_version !== undefined) return null
116  if (typeof c.id !== 'string' || !Number.isInteger(c.version) || c.version < 1) return null
117  if (d.sheet.schema !== 1 || typeof d.sheet.name !== 'string') return null
118  if (d.derived !== null && !isObj(d.derived)) return null
119  const unresolved = Array.isArray(d.unresolved) ? d.unresolved.filter((u: unknown) => typeof u === 'string') : []
120  return { character: c as GetPayload['character'], sheet: d.sheet, derived: d.derived ?? null, unresolved }
121}
122
123/** A Constitution save the server raised for damage to a concentrating sheet (patch 19): drawn as sent, never computed here. */
124export interface Save {
125  spell: string
126  dc: number
127  bonus: number
128  damage?: number
129}
130
131export interface AppliedPayload {
132  character: string
133  name?: string
134  version: number
135  diff: DiffItem[]
136  save?: Save
137}
138
139function asSave(v: unknown): Save | undefined {
140  if (!isObj(v) || typeof v.spell !== 'string' || !Number.isInteger(v.dc) || !Number.isInteger(v.bonus)) return undefined
141  return { spell: v.spell, dc: v.dc, bonus: v.bonus, ...(Number.isInteger(v.damage) ? { damage: v.damage } : {}) }
142}
143
144/** A `sheet_write apply=true` answer that wrote a version, or null. */
145export function asApplied(d: unknown): AppliedPayload | null {
146  if (!isObj(d) || d.applied !== true || typeof d.character !== 'string' || !Number.isInteger(d.version)) return null
147  if (!Array.isArray(d.diff) || !d.diff.every((x: unknown) => isObj(x) && typeof x.path === 'string' && x.path.startsWith('/'))) return null
148  const save = asSave(d.concentration_save)
149  return { character: d.character, name: typeof d.name === 'string' ? d.name : undefined, version: d.version, diff: d.diff, ...(save ? { save } : {}) }
150}
151
152export interface Finding {
153  severity: string
154  message: string
155  citation?: unknown
156}
157
158export interface CheckPayload {
159  character: { id: string; version: number }
160  findings: Finding[]
161}
162
163/** A `sheet_read check` answer, or null when the payload is anything else. */
164export function asCheck(d: unknown): CheckPayload | null {
165  if (!isObj(d) || !isObj(d.character) || typeof d.character.id !== 'string' || !Number.isInteger(d.character.version)) return null
166  if (!Array.isArray(d.findings) || !d.findings.every((f: unknown) => isObj(f) && typeof f.severity === 'string' && typeof f.message === 'string')) return null
167  return { character: d.character as CheckPayload['character'], findings: d.findings }
168}
169
170/** `check` is the cached entry's, carried over: a get does not re-check. */
171export function entryFromGet(g: GetPayload, server: string, now: number, check?: Entry['check']): Entry {
172  return {
173    id: g.character.id,
174    name: g.sheet.name,
175    owner: typeof g.character.owner === 'string' ? g.character.owner : null,
176    version: g.character.version,
177    sheet: g.sheet,
178    derived: g.derived,
179    unresolved: g.unresolved,
180    readAt: now,
181    seenAt: now,
182    server,
183    refreshing: false,
184    derivedPending: false,
185    fromStore: false,
186    drift: false,
187    last: null,
188    ...(check ? { check } : {}),
189  }
190}
191
192/** Paths `derived` is not computed from (checked against the server's derive()). Anything else marks it pending. */
193const OUTSIDE_DERIVED = [
194  /^\/hp(\/|$)/,
195  /^\/hit_dice_spent(\/|$)/,
196  /^\/ac(\/|$)/,
197  /^\/speed(\/|$)/,
198  /^\/spellcasting\/(slots_used|pact_slots_used)(\/|$)/,
199  /^\/resources(\/|$)/,
200  /^\/currency(\/|$)/,
201  /^\/conditions(\/|$)/,
202  /^\/concentration(\/|$)/,
203  /^\/exhaustion$/,
204  /^\/house_rules(\/|$)/,
205  /^\/notes$/,
206  /^\/details(\/|$)/,
207  /^\/requests(\/|$)/,
208  // A companion's HP, uses and status: the pane reads them off the sheet, not derived.
209  /^\/companions\/\d+\/(hp|status|notes)(\/|$)/,
210  /^\/companions\/\d+\/resources\/\d+\/used$/,
211]
212
213export const touchesDerived = (path: string) => !OUTSIDE_DERIVED.some((re) => re.test(path))
214
215const tokens = (path: string) => path.split('/').slice(1).map((t) => t.replace(/~1/g, '/').replace(/~0/g, '~'))
216const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
217
218/**
219 * The server's diff (store/sheets.ts `diff`, rest changes): `{path, from, to}`
220 * replaces, `{path, to}` adds, `{path, from}` removes. Applied to a copy.
221 * `matched` is false when a `from` disagrees with the cache, i.e. the cache
222 * missed a version.
223 */
224export function applyDiff(sheet: Record<string, any>, diff: DiffItem[]): { sheet: Record<string, any>; matched: boolean } {
225  const out = JSON.parse(JSON.stringify(sheet))
226  let matched = true
227  const removals: { parent: any; key: string }[] = []
228  for (const item of diff) {
229    const keys = tokens(item.path)
230    if (!keys.length) continue
231    let parent: any = out
232    for (const k of keys.slice(0, -1)) {
233      if (!parent[k] || typeof parent[k] !== 'object') parent[k] = {}
234      parent = parent[k]
235    }
236    const key = keys[keys.length - 1] ?? ''
237    if ('from' in item && !same(parent[key], item.from)) matched = false
238    if ('to' in item) parent[key] = JSON.parse(JSON.stringify(item.to))
239    else removals.push({ parent, key })
240  }
241  // Array removals last and highest index first, so earlier indexes stay put.
242  removals.sort((a, b) => Number(b.key) - Number(a.key))
243  for (const { parent, key } of removals) {
244    if (Array.isArray(parent)) parent.splice(Number(key), 1)
245    else delete parent[key]
246  }
247  return { sheet: out, matched }
248}
249
250/** The cached entry after a write: diff applied, waiting for a get. */
251export function entryAfterWrite(entry: Entry, w: AppliedPayload, reason: string, now: number): Entry {
252  const { sheet, matched } = applyDiff(entry.sheet, w.diff)
253  return {
254    ...entry,
255    sheet,
256    drift: entry.drift || !matched,
257    name: typeof sheet.name === 'string' ? sheet.name : entry.name,
258    version: w.version,
259    seenAt: now,
260    refreshing: true,
261    derivedPending: entry.derivedPending || w.diff.some((d) => touchesDerived(d.path)),
262    last: { version: w.version, at: now, reason, diff: w.diff },
263  }
264}
265
266/** The character a `/sheet <name>` means, by id or name, ignoring case. */
267export function matchEntry(entries: Entry[], query: string): Entry | null {
268  const q = query.trim().toLowerCase()
269  if (!q) return null
270  return entries.find((e) => e.id === q || e.name.toLowerCase() === q) ?? entries.find((e) => e.name.toLowerCase().startsWith(q)) ?? null
271}
272
273/** A diff path in words: `/hp/current` → `HP`, `/resources/0/used` → `Wrath of the Storm used`. */
274export function pathLabel(path: string, sheet: Record<string, any>): string {
275  const [a = '', b, c] = tokens(path)
276  const t = [a, b, c]
277  if (t[0] === 'hp') return t[1] === 'current' || !t[1] ? 'HP' : 'HP ' + t[1]
278  if (t[0] === 'resources' && t[1] !== undefined) {
279    const r = sheet.resources?.[Number(t[1])]
280    return (r?.name ?? 'resource ' + t[1]) + (t[2] ? ' ' + t[2] : '')
281  }
282  if (t[0] === 'spellcasting' && t[1] === 'slots_used') return 'slot ' + (t[2] ?? '') + ' used'
283  if (t[0] === 'hit_dice_spent') return (t[1] ?? '') + ' spent'
284  return t.join(' ').replace(/_/g, ' ')
285}
286
287/** One line for the last change: `HP 12 → 15 · long rest`. */
288export function describeChange(c: Change, sheet: Record<string, any>): string {
289  const v = (x: unknown) => (x === undefined ? '∅' : x !== null && typeof x === 'object' ? '…' : String(x))
290  // A key the write created has no `from`: `slot 1 used → 1`, not `∅ → 1`.
291  const parts = c.diff.slice(0, 3).map((d) => pathLabel(d.path, sheet) + (d.from === undefined ? '' : ' ' + v(d.from)) + ' → ' + v(d.to))
292  if (c.diff.length > 3) parts.push('+' + (c.diff.length - 3) + ' more')
293  return parts.join(', ') + (c.reason ? ' · ' + c.reason : '')
294}
295
296/**
297 * What a `sheet_read list` means for the cache: `fetch` the ids whose version
298 * moved or that were never got, `confirm` the ids it already holds at that
299 * version. A copy known wrong (`drift`) or missing its `derived` is fetched
300 * even at the same version. An id cached but not listed is left alone: a
301 * player's list holds only their own sheet.
302 */
303export function moved(entries: Entry[], listed: { id: string; version: number }[]): { fetch: string[]; confirm: string[] } {
304  const byId = new Map(entries.map((e) => [e.id, e]))
305  const fetch: string[] = []
306  const confirm: string[] = []
307  for (const { id, version } of listed) {
308    const e = byId.get(id)
309    if (!e || e.version !== version || e.drift || e.derivedPending) fetch.push(id)
310    else confirm.push(id)
311  }
312  return { fetch, confirm }
313}
314
315export type Coin = 'cp' | 'sp' | 'ep' | 'gp' | 'pp'
316
317/** `+50`, `-12`, `+5 sp`, `-3PP`: a signed amount of one coin, gp when unnamed. Unsigned is refused: a guessed direction moves money silently. */
318export function parseCoins(text: string): { coin: Coin; delta: number } | { refused: string } {
319  const t = text.trim()
320  const m = /^([+-])\s*(\d+)\s*(cp|sp|ep|gp|pp)?$/i.exec(t)
321  if (!m) return { refused: /^\d+\s*(cp|sp|ep|gp|pp)?$/i.test(t) ? '+ or −?' : 'an amount like +50 or -5 sp' }
322  const n = Number(m[2])
323  return { coin: (m[3]?.toLowerCase() ?? 'gp') as Coin, delta: m[1] === '-' ? -n : n }
324}
325
326/** A coin's amount on a sheet, 0 when the sheet has none. */
327export const coinsOf = (sheet: Record<string, any>, coin: Coin): number => {
328  const n = sheet.currency?.[coin]
329  return typeof n === 'number' ? n : 0
330}
331
332/**
333 * One coin moved by `delta`, as a JSON Patch compare-and-set on the cached
334 * amount: the server refuses it if anyone moved that coin since. Never makes
335 * change between coins; below zero is refused.
336 */
337export function coinChange(sheet: Record<string, any>, name: string, coin: Coin, delta: number): { changes: Record<string, unknown>[] } | { refused: string } {
338  const old = coinsOf(sheet, coin)
339  if (old + delta < 0) return { refused: `${name} has ${old} ${coin}` }
340  const path = '/currency/' + coin
341  return { changes: [{ op: 'test', path, value: old }, { op: 'replace', path, value: old + delta }] }
342}
343
hooks/table.ts 69 lines
1// The DM's party view's data, from the vault server's own answers: the session
2// manifest (`vault_query session`) and the Table operation's log as this mod saw
3// it written (`draft_write table-note | table-close`). The log is what was seen
4// here, not the vault's file: the mod never reads the vault's files.
5// No mods API here (validation forbids passing `$` to an imported function).
6
7import type { Entry } from './sheet.ts'
8import { isObj } from './receipt.ts'
9
10export interface Manifest {
11  session: string
12  status: string
13  title: string | null
14  tableExists: boolean
15}
16
17export interface TableEntry {
18  at: number
19  text: string
20}
21
22export interface TableLog {
23  session: string
24  entries: TableEntry[]
25  closedAt: number | null
26  manifest: Manifest | null
27}
28
29export interface TableWrite {
30  kind: 'note' | 'close'
31  session: string
32  text: string
33}
34
35/**
36 * A `vault_query {action: 'session'}` answer, or null. `registry` is the
37 * registry row (or null), its `title` `""` when the note has none.
38 */
39export function asManifest(d: unknown): Manifest | null {
40  if (!isObj(d) || typeof d.session !== 'string' || typeof d.status !== 'string') return null
41  if (d.registry !== null && d.registry !== undefined && !isObj(d.registry)) return null
42  const title = d.registry?.title
43  return {
44    session: d.session,
45    status: d.status,
46    title: typeof title === 'string' && title ? title : null,
47    tableExists: Array.isArray(d.sources) && d.sources.some((s: any) => isObj(s) && s.kind === 'table' && s.exists === true),
48  }
49}
50
51/** A `draft_write` call `e` (its arguments) that wrote a table note or the close, or null. A dry run answers `wrote: false`. */
52export function asTableWrite(e: any, d: unknown): TableWrite | null {
53  if (!e || (e.kind !== 'table-note' && e.kind !== 'table-close')) return null
54  if (typeof e.session !== 'string' || typeof e.text !== 'string') return null
55  if (!isObj(d) || d.wrote !== true) return null
56  return { kind: e.kind === 'table-note' ? 'note' : 'close', session: e.session, text: e.text }
57}
58
59/** The log after a seen write: a note appends, a close sets `closedAt`. */
60export function applyWrite(log: TableLog | null, w: TableWrite, now: number): TableLog {
61  const base: TableLog = log ?? { session: w.session, entries: [], closedAt: null, manifest: null }
62  return w.kind === 'note' ? { ...base, entries: [...base.entries, { at: now, text: w.text }] } : { ...base, closedAt: now }
63}
64
65export const isSessionId = (s: string) => /^S\d\d$/.test(s)
66
67/** The party's rows, by name. (The DM's own roster order arrives with `party:roster`, handoff 18 step A.) */
68export const rosterRows = (entries: Entry[]): Entry[] => [...entries].sort((a, b) => a.name.localeCompare(b.name))
69
hooks/roster.ts 142 lines
1// Tonight's group for the party view: who is at the table for one session, and
2// which cached sheets they are. Read from the vault (register.ts does the
3// reading): the session note's `present:` (Sessions/Sxx.md), else the prep doc
4// whose `sessions:` lists Sxx, its `party:`, else the names typed after
5// `/party Sxx`, else nobody, which shows every sheet as before.
6// No mods API here (validation forbids passing `$` to an imported function).
7
8import type { Entry } from './sheet.ts'
9
10/** Where the group came from: `note` and `prep` name the file in `from`. */
11export type Source = 'note' | 'prep' | 'args'
12
13export interface Roster {
14  source: Source
15  /** The file the names came from (`Sessions/S05.md`), or null for typed names. */
16  from: string | null
17  /** The names as written: `Billy (Bati)`, `Diego Valmorra`, `nux`. */
18  names: string[]
19  /** Why the roster is not the whole story (prep docs that disagree), or null. */
20  warning: string | null
21}
22
23/** A PC's note in the vault (Lore/Party/<name>.md): its name and `aliases:`. */
24export interface PcNote {
25  name: string
26  aliases: string[]
27}
28
29export interface Group {
30  /** The sheets the group names, by id. */
31  ids: Set<string>
32  /** The names no sheet answers to, or more than one does, each with why. */
33  unmatched: string[]
34}
35
36/** The frontmatter's `key: value` lines, comments cut. A `[a, b]` value is a list; any other value is its text. */
37export function frontmatter(md: string): Record<string, string | string[]> {
38  const lines = md.replace(/^/, '').split(/\r?\n/)
39  const out: Record<string, string | string[]> = {}
40  if (lines[0]?.trim() !== '---') return out
41  for (const line of lines.slice(1)) {
42    if (line.trim() === '---') return out
43    const m = /^([A-Za-z_][\w-]*):(.*)$/.exec(line)
44    if (!m) continue
45    const raw = m[2]!.replace(/\s+#.*$/, '').trim()
46    const bare = (s: string) => s.trim().replace(/^(["'])(.*)\1$/, '$2').trim()
47    out[m[1]!] = raw.startsWith('[') && raw.endsWith(']') ? raw.slice(1, -1).split(',').map(bare).filter(Boolean) : bare(raw)
48  }
49  return {} // no closing `---`: not frontmatter
50}
51
52/** A frontmatter value as a list: a list as is, a text split at commas, absent as empty. */
53export const listOf = (v: string | string[] | undefined): string[] =>
54  Array.isArray(v) ? v : v ? v.split(',').map((s) => s.trim()).filter(Boolean) : []
55
56/** A `present:` item that says the PC was not there (`Almuth (Cubbas), absent`): not tonight's group. */
57const ABSENT = /\b(not present|absent)\b/i
58
59/** The session note's `present:` names, the absent ones left out; empty when the note lists nobody. */
60export const presentOf = (md: string) => listOf(frontmatter(md).present).filter((n) => !ABSENT.test(n))
61
62/** A prep doc's `party:` when its `sessions:` lists `session`; else null. */
63export function prepParty(md: string, session: string): string[] | null {
64  const fm = frontmatter(md)
65  if (!listOf(fm.sessions).some((s) => s.toUpperCase() === session)) return null
66  const party = listOf(fm.party)
67  return party.length ? party : null
68}
69
70/**
71 * The roster, in the order the sources are tried: the note's `present:`, the
72 * prep docs' `party:` (the first by path; a second that names others is a
73 * warning, never merged), the typed names. Null when none names anyone.
74 */
75export function pickRoster(note: { path: string; md: string } | null, preps: { path: string; md: string }[], typed: string[], session: string): Roster | null {
76  const present = note ? presentOf(note.md) : []
77  if (note && present.length) return { source: 'note', from: note.path, names: present, warning: null }
78  const found = [...preps]
79    .sort((a, b) => a.path.localeCompare(b.path))
80    .map((p) => ({ path: p.path, party: prepParty(p.md, session) }))
81    .filter((p): p is { path: string; party: string[] } => p.party !== null)
82  const first = found[0]
83  if (first) {
84    const key = (ns: string[]) => ns.map(fold).sort().join('|')
85    const other = found.find((p) => key(p.party) !== key(first.party))
86    return { source: 'prep', from: first.path, names: first.party, warning: other ? `${other.path} names others` : null }
87  }
88  if (typed.length) return { source: 'args', from: null, names: typed, warning: null }
89  return null
90}
91
92/** Lower case, accents off, anything but letters and digits a space, single-spaced. */
93export const fold = (s: string) =>
94  s
95    .normalize('NFD')
96    .replace(/[̀-ͯ]/g, '')
97    .toLowerCase()
98    .replace(/[^a-z0-9]+/g, ' ')
99    .trim()
100
101const firstWord = (s: string) => fold(s).split(' ')[0] ?? ''
102
103/**
104 * What a sheet answers to, folded: its id, its name, its first name, and, when
105 * a PC note is that sheet (the same name or first name), the note's name and
106 * its aliases.
107 */
108export function keysOf(e: Entry, notes: PcNote[]): Set<string> {
109  const keys = new Set([fold(e.id), fold(e.name), firstWord(e.name)])
110  for (const n of notes) {
111    if (fold(n.name) === fold(e.name) || firstWord(n.name) === firstWord(e.name)) {
112      keys.add(fold(n.name))
113      for (const a of n.aliases) keys.add(fold(a))
114    }
115  }
116  keys.delete('')
117  return keys
118}
119
120/**
121 * The sheets the roster names. A name is matched as whole words: `Billy (Bati)`
122 * is Bati, and only the part in brackets is read when there is one (the
123 * player's name stays out of it). A name no sheet answers to, or two do, is
124 * unmatched, never guessed.
125 */
126export function matchGroup(entries: Entry[], names: string[], notes: PcNote[]): Group {
127  const keyed = entries.map((e) => ({ e, keys: keysOf(e, notes) }))
128  const ids = new Set<string>()
129  const unmatched: string[] = []
130  for (const name of names) {
131    const inner = /\(([^)]+)\)/.exec(name)?.[1]
132    const words = ` ${fold(inner ?? name)} `
133    const hits = keyed.filter(({ keys }) => [...keys].some((k) => words.includes(` ${k} `)))
134    if (hits.length === 1) ids.add(hits[0]!.e.id)
135    else unmatched.push(hits.length ? `${name} (${hits.map((h) => h.e.name).join(' or ')}?)` : name)
136  }
137  return { ids, unmatched }
138}
139
140/** The rows the party view draws: the group's, or all of them when `all` or there is no roster. */
141export const shownRows = (rows: Entry[], group: Group | null, all: boolean) => (group && !all ? rows.filter((e) => group.ids.has(e.id)) : rows)
142
hooks/view.ts 1621 lines
1// The element trees: the pane and the band strip, one tree for every surface.
2// Everything shown is the server's `sheet` and `derived`; the only arithmetic
3// is "left = max − used" for slots, pips and Hit Dice. Pure: the elements come
4// in from register.ts, which owns every mods API call and handles the presses.
5//
6// The pane is built around a player's turn, not the sheet's sections. The top
7// is a HUD, always visible and as wide as the body: the level badge, name and
8// classes; conditions when there are any; one row of vitals, labels over values
9// (AC, HP and its gauge, INIT, SPD, PP); the taps; spell DC and attack per
10// caster; the six saves; slots and resources as pips. Under it, the tab rule:
11// one tab open at a time, by the player's question: act (what do I roll?),
12// skills, feats, gear, notes. A faint `seen 13:19 · [ re-read ]` only when the
13// HP is not confirmed, and the last check while it warns.
14// It draws with look.ts: uppercase readouts, values in ink, gauges as glyph
15// runs. One tree, two drawings: the terminal draws gauges as glyph runs, the
16// surfaces that have `Svg` draw them, the HP and the glance values as pixel
17// instruments (pixel.ts), never a word. The surface is read only by those sites.
18//
19// The party view (`/party`, the DM's) is a second tree in the same pane: a row
20// per cached sheet, the Table log as seen here, the session, the re-read. While
21// a fight is on (fight.ts), its order is drawn above the party; the DM runs it
22// by clicks: a row, then a button under it.
23//
24// The pane is a stack of screens (register.ts owns it): the top one is drawn,
25// and `[ ‹ back ]`, top left, pops it. Every action is a drawn Button; a letter
26// hotkey is a shortcut for one, never the only way.
27//
28// `[ look up ]` (T0085) pushes the look: a field whose matches narrow as the
29// DM types, then a match's card (lookup.ts), each one more screen on the stack.
30
31import type { ButtonProps, Elements, RenderElement, RenderNode, TextProps } from 'claude-code'
32import { actionGroups, norm, type ActionRow } from './actions.ts'
33import { cardRows, detailAt, detailBox, detailOf, greedy, type Content, type Detail, type Preview } from './detail.ts'
34import { describe, live, onDeck, orderRows, statusText, type Fight, type Member, type Pack, type Row } from './fight.ts'
35import type { Candidate, Card, Heard, HeardItem } from './lookup.ts'
36import { coinsOf, type Entry, type Save } from './sheet.ts'
37import { bandSegments, FAINT_TEXT, gaugeRuns, hpSegments, hpState, noneSegments, pipRuns, RECEIPT_INDENT, rule, TOKENS, type HpState, type Run, type Segment, type Tone } from './look.ts'
38import { badgeSvg, cellsSvg, hpSvg, pipsSvg, readoutSvg, type Art } from './pixel.ts'
39import type { Receipt } from './receipt.ts'
40import type { TableLog } from './table.ts'
41
42/** What `$.ui.resolve(e)` hands out, on any surface. */
43export type Els = Elements[keyof Elements]
44
45/** The elements every surface has, which the pane draws with. */
46type Base = Pick<Elements['mobile'], 'Box' | 'Text' | 'Button' | 'Markdown'>
47
48/**
49 * The tabs, by the player's question. They are words on the tab rule, frameless,
50 * so they carry no hotkey (a plain Button draws its hotkey as `a: act`): a click,
51 * the focus ring or `/sheet <tab>` opens one; `m` still opens the DM's rules.
52 */
53export const TABS = [
54  { id: 'actions', label: 'act', words: ['actions', 'action', 'act', 'spells', 'attacks'] },
55  { id: 'skills', label: 'skills', words: ['skills', 'skill', 'saves', 'save', 'checks'] },
56  { id: 'features', label: 'feats', words: ['features', 'feats', 'traits'] },
57  { id: 'gear', label: 'gear', words: ['gear', 'inventory', 'items', 'money', 'equipment', 'equipped'] },
58  { id: 'companions', label: 'pets', words: ['companions', 'companion', 'summons', 'summon', 'pets', 'pet', 'creatures', 'familiar'] },
59  { id: 'notes', label: 'notes', words: ['notes', 'rules', 'character', 'details'] },
60] as const
61export type TabId = (typeof TABS)[number]['id']
62
63/** The tab a word names (`spells`, `saves`), or null. */
64export function tabOf(word: string): TabId | null {
65  const w = word.trim().toLowerCase()
66  return TABS.find((t) => t.id === w || (t.words as readonly string[]).includes(w))?.id ?? null
67}
68
69/** The key of the DM-rules badge, which opens the Notes tab. */
70export const RULES_KEY = 'dm-rules'
71export const tabKey = (id: TabId) => 'tab-' + id
72
73/**
74 * The last re-read: `sheets` the sheets it holds current, `listed` the list answer's length. `off` names the tool
75 * `$.tool.check` would ask about: live sync is off until it is allowed. Module state, never stored.
76 */
77export type Reread = { at: number; sheets: number; listed: number } | { refused: string } | { failed: string } | { off: string }
78/** The number field's question: which number, for which row and member, and its text so far. */
79export type Ask = { kind: 'damage' | 'heal' | 'init'; row: string; member: number; text: string }
80/** The sheet view's number field: damage, healing or coins for the focused sheet, and its text so far. */
81/** `companion`: the index of the companion it hits or heals (the pets tab), with its name for the field. */
82export type Tap = { kind: 'damage' | 'heal' | 'coins'; text: string; companion?: { index: number; name: string; use?: { index: number; label: string } } }
83/** The add form's five fields, as the DM has filled them so far. */
84export type Adding = { name: string; count: string; hp: string; ac: string; init: string }
85
86/** The pane's screens; register.ts keeps them as a stack and draws the top one. `look` is the look's field, `card` a match's card, `log` the whole Table log, `packet` the loaded pack's notes. */
87export type Screen = 'party' | 'sheet' | 'packs' | 'look' | 'card' | 'log' | 'packet'
88
89/** The look as drawn: the field's text and its matches, or the open card, its fetch and its page. */
90export type LookView = { text: string; matches: Candidate[]; card: Card | null; loading: boolean; error: string | null; page: number }
91
92export type GroupView = {
93  source: 'note' | 'prep' | 'args'
94  from: string | null
95  warning: string | null
96  ids: Set<string>
97  unmatched: string[]
98  all: boolean
99  payees: string[]
100}
101
102export interface PaneView {
103  screen: Screen
104  /** There is a screen under this one: `[ ‹ back ]` is drawn. */
105  canBack: boolean
106  /** Every cached sheet, in roster order. */
107  rows: Entry[]
108  /** The session's Table log as seen here, or null. */
109  log: TableLog | null
110  /** The log entry drawn whole (its index in the log), or null: every entry is one line. */
111  logOpen: number | null
112  session: string | null
113  reread: Reread | null
114  entry: Entry | null
115  surface: string
116  columns: number
117  tab: TabId
118  /** Milliseconds since the epoch, for the `seen 13:19` readout (a day's date once it is not today). */
119  now: number
120  /** This machine's last tap is on this sheet and still its version: `[ undo ]` is drawn. */
121  undo: boolean
122  /**
123   * Buttons kept from this surface's last drawing. An unchanged Button is
124   * handed back as the same element, so its press handle survives the redraw
125   * (each new Button gets a new handle, and the old one is retired).
126   */
127  memo: Map<string, RenderElement>
128  /** The diff paths of the last applied write, while its flash lasts; else null. */
129  flash: string[] | null
130  /** The DM's fight, or null; drawn on the party view until it ends. */
131  fight: Fight | null
132  /** The picked row (by id) and, in a group, its member. */
133  sel: { row: string; member: number } | null
134  /** The open number field, with the row's name for its label. */
135  ask: (Ask & { name: string }) | null
136  /** The open add form. */
137  adding: Adding | null
138  /** Why the last press did nothing, until an op applies. */
139  note: string | null
140  /** The packs read from Prep/Fights.md, for the packs screen; null when there are none. */
141  packs: Pack[] | null
142  /** The fight on show has a pack loaded: `[ packet ]` is drawn. */
143  canPacket: boolean
144  /** The pack `[ next ]` loads while no fight is live, or null. */
145  nextPack: string | null
146  /** The packet screen's pack (null when it is gone from the file) and page. */
147  packet: { pack: Pack | null; page: number } | null
148  /** The sheet view's open number field, for a tap. */
149  tap: Tap | null
150  /** The look, while `look` or `card` is on show; else null. */
151  look: LookView | null
152  /** The Concentration saves the server raised and nobody has answered, by sheet id (register.ts, never stored). */
153  saves: Map<string, Save[]>
154  /** The live listener's fresh heard file (T0085 stage 2), on the party view; else null. */
155  heard: Heard | null
156  /** The party's open split field, its text so far; else null. */
157  split: string | null
158  /**
159   * Tonight's group (roster.ts), or null when the vault and `/party` name
160   * nobody: where it came from, the sheets it names, the names no sheet
161   * answers to, `[ all ]` pressed, and who `[ split gold ]` pays.
162   */
163  group: GroupView | null
164  /** The open detail box (T0093): the word it hangs from; else null. */
165  detail: Detail | null
166  /** The hover preview (T0093 Layer 3), shown or pinned; else null. */
167  preview: Preview | null
168}
169
170/** The fight bar's buttons: [element key, hotkey, label]. The letters are shortcuts. */
171const BAR = [['next', 'n', 'next turn'], ['undo', 'u', 'undo'], ['act-a', 'a', 'add'], ['act-c', 'c', 'packs'], ['act-f', 'f', 'end fight']] as const
172/** With no fight: add and packs, and undo while the last fight's end can be undone. */
173const IDLE = [BAR[2], BAR[3]]
174const ENDED = [...IDLE, BAR[1]]
175/** The targeted row's buttons, drawn under it in two rows: what changes HP (and the turn), then its state. `sheet` only for a PC with a sheet. */
176const STRIP_HP = [['act-d', 'd', 'dmg'], ['act-h', 'h', 'heal'], ['act-t', 't', 'turn']] as const
177const STRIP_STATE = [['act-i', 'i', 'init'], ['act-o', 'o', 'out'], ['act-k', 'k', 'down'], ['act-x', 'x', 'kill']] as const
178const SHEET = ['act-s', 's', 'sheet'] as const
179/** A monster row's card (T0085); no hotkey. */
180const STATS = ['act-stats', '', 'stats'] as const
181const ADD_FIELDS = [
182  ['name', ''], ['count', '1'], ['hp', 'blank: no HP tracked'], ['ac', ''], ['init', ''],
183] as const
184
185const signed = (n: unknown) => (typeof n === 'number' ? (n >= 0 ? '+' + n : String(n)) : '?')
186const pad2 = (n: number) => String(n).padStart(2, '0')
187const clock = (ms: number) => {
188  const d = new Date(ms)
189  return pad2(d.getHours()) + ':' + pad2(d.getMinutes())
190}
191const MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
192const day = (ms: number) => {
193  const d = new Date(ms)
194  return `${d.getDate()} ${MONTHS[d.getMonth()]}, ${clock(ms)}`
195}
196const sameDay = (a: number, b: number) => new Date(a).toDateString() === new Date(b).toDateString()
197const ORDINAL = (l: string) => ({ '1': '1st', '2': '2nd', '3': '3rd' })[l] ?? l + 'th'
198const ABILITIES = ['str', 'dex', 'con', 'int', 'wis', 'cha'] as const
199
200// ------------------------------------------------------------------ facts (read off the entry)
201
202const unresolvedName = (name: string, unresolved: string[]) =>
203  unresolved.some((u) => u.toLowerCase() === name.toLowerCase() || u.toLowerCase().endsWith(' ' + name.toLowerCase()))
204
205function level(e: Entry): string {
206  const total = e.derived?.total_level
207  return (typeof total === 'number' ? String(total) : '?') + (e.derivedPending && typeof total === 'number' ? '?' : '')
208}
209
210interface Caster {
211  cls: string
212  dc: string
213  attack: string
214}
215
216function casters(e: Entry): Caster[] {
217  return ((e.derived?.spellcasting ?? []) as any[]).map((c) => ({ cls: String(c.class), dc: String(c.save_dc ?? '?'), attack: String(c.attack ?? '?') }))
218}
219
220interface Pips {
221  label: string
222  left: number
223  max: number
224  pending: boolean
225  /** A slot row's tap: the label is then a Button with this key and hotkey. */
226  key?: string
227  hotkey?: string
228}
229
230/** Slot rows by level, `1` → `{label: '1st', key: 'slot-1', hotkey: '1'}`; pact slots last (`slot-pact`, `p`). */
231export function slotRows(e: Entry): (Pips & { level: number })[] {
232  const used = e.sheet.spellcasting?.slots_used ?? {}
233  const pending = e.derivedPending
234  const rows = Object.entries((e.derived?.spell_slots ?? {}) as Record<string, number>)
235    .sort(([a], [b]) => Number(a) - Number(b))
236    .map(([lvl, max]) => ({ label: ORDINAL(lvl), level: Number(lvl), max, left: Math.max(0, max - (used[lvl] ?? 0)), pending, key: 'slot-' + lvl, hotkey: lvl }))
237  const pact = e.derived?.pact_slots
238  if (pact && typeof pact.slots === 'number') {
239    const left = Math.max(0, pact.slots - (e.sheet.spellcasting?.pact_slots_used ?? 0))
240    rows.push({ label: 'Pact', level: Number(pact.level), max: pact.slots, left, pending, key: 'slot-pact', hotkey: 'p' })
241  }
242  return rows
243}
244
245function resources(e: Entry): Pips[] {
246  return (e.sheet.resources ?? []).map((r: any) => ({
247    label: String(r.name),
248    max: r.max,
249    left: Math.max(0, r.max - r.used),
250    pending: false,
251  }))
252}
253
254
255/** Speeds other than walking: `swim 30`. Walking speed is the SPD stat. */
256function otherSpeeds(s: any): string[] {
257  const sp = s.speed ?? {}
258  return ['swim', 'fly', 'climb', 'burrow'].filter((k) => typeof sp[k] === 'number').map((k) => `${k} ${sp[k]}`)
259}
260
261/** The DM's rules that name this thing (a spell, a feature), by whole word. */
262function rulesNaming(e: Entry, name: string): number {
263  const re = new RegExp('\\b' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b', 'i')
264  return (e.sheet.house_rules ?? []).filter((r: any) => re.test(String(r.rule ?? ''))).length
265}
266/** ★ marks a DM ruling, the same symbol as the header badge. */
267const dmMark = (e: Entry, name: string) => (rulesNaming(e, name) ? ' ★' : '')
268
269// ------------------------------------------------------------------ parts
270
271const text = (el: Base, children: string, props: TextProps = {}) => el.Text({ ...props, children: [children] })
272const row = (el: Base, children: RenderNode[], gap = 1) => el.Box({ flexDirection: 'row', columnGap: gap, children })
273const wrapRow = (el: Base, children: RenderNode[], gap = 2) => el.Box({ flexDirection: 'row', flexWrap: 'wrap', columnGap: gap, children })
274const col = (el: Base, children: RenderNode[]) => el.Box({ flexDirection: 'column', children })
275const md = (el: Base, lines: string[]) => el.Markdown({ text: lines.join('\n').slice(0, 10000) })
276const dim = (el: Base, s: string) => text(el, s, { dimColor: true })
277/** `s` cut with `…` to `n` cells, as `wrap: 'truncate-end'` would draw it. */
278const cut = (s: string, n: number) => (s.length <= n ? s : s.slice(0, Math.max(1, n - 1)) + '…')
279/** A gauge: its runs side by side, no gap. */
280const gauge = (el: Base, runs: Run[]) => row(el, runs.map((r) => text(el, r.text, r.props)), 0)
281/** The surfaces that draw pixel instruments: every one whose table has `Svg`. */
282const pixel = (surface: string) => surface !== 'terminal'
283/** A pixel instrument, centred on its row. */
284const svg = (el: Base, art: Art) => el.Box({ alignSelf: 'center', children: [(el as Elements['desktop']).Svg({ source: art.source, alt: art.alt })] })
285/** A gauge (the band's HP): glyph runs on the terminal, cells elsewhere. */
286const gaugeNode = (el: Base, surface: string, segs: Segment[], tone: Tone, alt: string) =>
287  pixel(surface) ? svg(el, cellsSvg(segs, tone, 4, 4, alt)) : gauge(el, gaugeRuns(segs, tone))
288/** Pips for `left` of `max` in `width` columns: glyph runs on the terminal, cells elsewhere. */
289const pipsNode = (el: Base, surface: string, left: number, max: number, width: number, tone: Tone, alt: string) =>
290  pixel(surface) ? svg(el, pipsSvg(left, max, tone, alt)) : gauge(el, pipRuns(left, max, width, tone))
291const of = (left: number, max: number) => `${left} of ${max}`
292/**
293 * A run of `─` that fills what its row leaves, clipped to one line: a hard-wrapped
294 * run cut by its Box, where a truncated one would end in `…`.
295 */
296const fill = (el: Base, n: number, style: TextProps, marginLeft = 0) =>
297  el.Box({ flexGrow: 1, width: 0, height: 1, overflow: 'hidden', marginLeft, children: [text(el, '─'.repeat(Math.max(1, n)), { ...style, wrap: 'wrap' })] })
298/** A readout rule across the pane's body: its label, then a fill to the edge. */
299function ruleLine(el: Base, label: string, columns: number): RenderNode {
300  const r = rule(label, columns)
301  const head = r.slice(0, r.lastIndexOf(' ') + 1)
302  return el.Box({ flexDirection: 'row', children: [el.Box({ flexShrink: 0, children: [text(el, head, { dimColor: true })] }), fill(el, columns - head.length, { dimColor: true })] })
303}
304/** A readout rule with a control at its right end; the rule gives way. */
305const ruleWith = (el: Base, label: string, columns: number, node: RenderNode) =>
306  el.Box({ flexDirection: 'row', columnGap: 1, children: [el.Box({ flexGrow: 1, flexShrink: 1, children: [ruleLine(el, label, columns)] }), el.Box({ flexShrink: 0, children: [node] })] })
307/** A section heading inside a tab: a dim uppercase readout, with anything beside it. */
308const heading = (el: Base, label: string, extra: RenderNode[] = []) =>
309  el.Box({ flexDirection: 'row', columnGap: 2, children: [dim(el, label.toUpperCase()), ...extra] })
310/** A section of a tab: its heading, then its lines, no space between. */
311const section = (el: Base, head: RenderNode, lines: RenderNode[]) => col(el, [head, ...lines])
312/** A number that may change on the next read: amber with a `?`. Otherwise bold ink. Inverse while it flashes. */
313const value = (el: Base, s: string, pending = false, flash = false) =>
314  text(el, pending ? s + '?' : s, { ...(pending ? { color: TOKENS.amber } : { bold: true }), ...(flash ? { inverse: true } : {}) })
315const stat = (el: Base, label: string, s: string, pending = false) => row(el, [dim(el, label), value(el, s, pending)])
316
317/** Does nothing: register.ts's `ui.press` hook acts on every press, with a fresh `$`. */
318const NOOP = () => {}
319
320/** Builds the pane's Buttons through the memo, so an unchanged Button is the same element as last time. */
321function buttons(el: Base, memo: Map<string, RenderElement>) {
322  const used = new Map<string, RenderElement>()
323  /** `color` draws the label in that colour (a Text child), as `HOLDING` is violet. */
324  const make = (props: Omit<ButtonProps, 'onPress'> & { key: string; label: string; color?: string }): RenderElement => {
325    const sig = JSON.stringify(props)
326    const { color, ...rest } = props
327    const kept = used.get(sig) ?? memo.get(sig) ?? el.Button({ ...rest, ...(color ? { children: [text(el, rest.label, { color })] } : {}), onPress: NOOP })
328    used.set(sig, kept)
329    return kept
330  }
331  const done = () => {
332    memo.clear()
333    for (const [k, v] of used) memo.set(k, v)
334  }
335  return { make, done }
336}
337type Make = ReturnType<typeof buttons>['make']
338
339/** A word's look: as the Text it replaces. */
340type WordStyle = { bold?: boolean; dimColor?: boolean; color?: string; inverse?: boolean }
341
342/** `detailOf` once per word per render (a view is one render's): the word and its open box share the answer. */
343const boxes = new WeakMap<PaneView, Map<string, Content | null>>()
344function boxOf(v: PaneView, key: string): Content | null {
345  const seen = boxes.get(v) ?? new Map<string, Content | null>()
346  boxes.set(v, seen)
347  if (!seen.has(key)) seen.set(key, detailOf(key, v.rows, v.entry, v.now))
348  return seen.get(key)!
349}
350
351/**
352 * A word with a box (T0093), `w:<kind>:<subject>`; detail.ts says what its box
353 * holds. On the terminal and the desktop it is the word Client (word.tsx), its
354 * label underlined; elsewhere a plain Button. A press opens or closes its box;
355 * while it is open the word is inverse. A `w:c:` word opens its card instead.
356 * With no box it is the Text it replaces (`plain` adds that Text's own props),
357 * never underlined. `hover` (Layer 3, a word off the HUD, the header rows and
358 * /party): the Client also dwells, and its row hangs the preview (`hang`).
359 */
360function word(el: Base, v: PaneView, make: Make, key: string, label: string, style: WordStyle = {}, plain: TextProps = {}, hover = false): RenderNode {
361  if (!key.startsWith('w:c:') && !boxOf(v, key)) return text(el, label, { ...style, ...plain })
362  const s = v.detail?.anchor === key ? { ...style, inverse: !style.inverse } : style
363  if (v.surface === 'terminal' || v.surface === 'desktop')
364    return (el as Elements['terminal']).Client({ key, module: './word.tsx', props: { id: key, label, ...(hover ? { hover } : {}), ...s } })
365  return make({ key, label, plain: true, ...(s.dimColor ? { dimColor: true } : {}) })
366}
367
368/** The open box, as wide as the body, where `owns` claims its word; else nothing. A pinned preview is drawn by `preview`. */
369function openBox(el: Base, v: PaneView, make: Make, owns: (anchor: string) => boolean): RenderNode[] {
370  const d = v.detail
371  const c = d && !d.above && owns(d.anchor) ? detailAt(d.path, v.rows, v.entry, v.now) : null
372  return c ? [detailBox(el, make, c, v.columns, (k, l, st) => word(el, v, make, k, l, st))] : []
373}
374
375/**
376 * The hover preview (Layer 3) where `owns` claims its word: an absolute Box
377 * its own height above the row, so it covers the rows above and never shoves
378 * them, as wide as the body, on the card's ground. A term's card on top, then
379 * while pinned `[ ‹ ]`, `[ × ]` and the box's buttons, then the word's card
380 * (card.tsx). Only where Clients draw: elsewhere a word stays a pin Button.
381 */
382function preview(el: Base, v: PaneView, make: Make, owns: (anchor: string) => boolean): RenderNode[] {
383  const p = v.preview
384  if (!p || !owns(p.anchor) || (v.surface !== 'terminal' && v.surface !== 'desktop')) return []
385  const card = (c: Content, depth: number) => {
386    const { rows, more } = cardRows(c, v.columns)
387    const node = (el as Elements['terminal']).Client({
388      key: `card-${depth}:${c.title}`,
389      module: './card.tsx',
390      width: v.columns,
391      height: rows.length,
392      props: { depth, width: v.columns, rows, bg: TOKENS.card, ink: TOKENS.cardInk, dim: TOKENS.cardDim },
393    })
394    return { node, h: rows.length, more }
395  }
396  const top = card(p.top, 1)
397  const nested = p.nested ? [card(p.nested, 2)] : []
398  // The pins row is padded as a card line is: a ground colour does not blank the cells behind it.
399  const ground = { backgroundColor: TOKENS.card }
400  const pins = p.pinned
401    ? [
402        row(
403          el,
404          [
405            ...[
406              ...(p.top.back ? [make({ key: 'detail-back', label: '‹', color: TOKENS.cardInk })] : []),
407              make({ key: 'detail-x', label: '×', color: TOKENS.cardInk }),
408              ...(top.more ? [make({ key: 'detail-more', label: 'more', color: TOKENS.cardInk })] : []),
409              ...(p.top.reread ? [make({ key: 'detail-reread', label: 're-read', color: TOKENS.cardInk })] : []),
410            ].flatMap((b) => [text(el, ' ', ground), b]),
411            el.Box({ flexGrow: 1, width: 0, height: 1, overflow: 'hidden', children: [text(el, ' '.repeat(v.columns), { ...ground, wrap: 'truncate-end' })] }),
412          ],
413          0,
414        ),
415      ]
416    : []
417  const h = top.h + nested.reduce((n, c) => n + c.h, 0) + pins.length
418  return [
419    el.Box({
420      position: 'absolute',
421      top: -h,
422      left: 0,
423      width: v.columns,
424      flexDirection: 'column',
425      backgroundColor: TOKENS.card,
426      children: [...nested.map((c) => c.node), ...pins, top.node],
427    }),
428  ]
429}
430
431/** A row a preview hangs above: always the one Box, so the row's words keep their place in the tree. */
432const hang = (el: Base, v: PaneView, make: Make, node: RenderNode, owns: (anchor: string) => boolean) => col(el, [node, ...preview(el, v, make, owns)])
433
434/** A list line: `- `, its word, then the rest wrapping beside it. */
435const wordLine = (el: Base, w: RenderNode, rest: string) =>
436  el.Box({ flexDirection: 'row', children: [el.Box({ flexShrink: 0, flexDirection: 'row', children: [text(el, '- '), w] }), el.Box({ flexShrink: 1, children: [text(el, rest, { wrap: 'wrap' })] })] })
437
438/**
439 * The top line of every screen: `[ ‹ back ]` while there is a screen to go
440 * back to, then `[ look up ]` but on the look's own screens, and only where its
441 * field can be typed (the phone's table has no Input; see partyTree).
442 */
443function navLine(el: Base, v: PaneView, make: Make): RenderNode[] {
444  const look = v.screen !== 'look' && v.screen !== 'card' && 'Input' in el && v.surface !== 'mobile'
445  const kids = [
446    ...(v.canBack ? [make({ key: 'back', label: '‹ back', hotkey: '0' })] : []),
447    ...(look ? [make({ key: 'look', label: 'look up', hotkey: 'l' })] : []),
448    ...(v.screen === 'party' && v.canPacket ? [make({ key: 'act-packet', label: 'packet' })] : []),
449  ]
450  return kids.length ? [wrapRow(el, kids, 1)] : []
451}
452
453/** A field's submit and cancel, under it: `[ apply ]` does what Enter does. */
454const goCancel = (el: Base, make: Make, field: string, go: string) =>
455  wrapRow(el, [make({ key: field + '-go', label: go }), make({ key: field + '-cancel', label: 'cancel', dimColor: true })])
456
457/** The sheet's Concentration spell is this row's: the name, and the source when the field names one, ignoring case. */
458export const holding = (e: Entry, r: ActionRow) => {
459  const c = e.sheet.concentration
460  const same = (a: unknown, b: string) => String(a).toLowerCase() === b.toLowerCase()
461  return !!c && same(c.spell, r.name) && (!c.source || same(c.source, r.source))
462}
463
464/**
465 * Actions: the turn menu. Weapons, cantrips, each slot level (its pips beside the heading), other magic; a row per action.
466 * A Concentration spell's `CONC` is a press (`conc-<i>`, the row's index across the groups): `HOLDING`, violet, on the held one.
467 */
468function actionsTab(el: Base, e: Entry, v: PaneView, make: Make): RenderNode[] {
469  const slots = new Map(slotRows(e).map((s) => [s.level, s]))
470  const groups = actionGroups(e, slots, (name) => rulesNaming(e, name) > 0)
471  // The class leads a row only when more than one class casts, so a reader knows whose DC it is.
472  const showCls = new Set(groups.flatMap((g) => g.rows.map((r) => r.cls)).filter(Boolean)).size > 1
473  let index = 0
474  const badge = (r: ActionRow, i: number, b: ActionRow['badges'][number]) =>
475    b !== 'conc'
476      ? dim(el, b.toUpperCase())
477      : holding(e, r)
478        ? make({ key: 'conc-' + i, label: 'HOLDING', color: TOKENS.violet })
479        : make({ key: 'conc-' + i, label: 'CONC', dimColor: true })
480  const actionRow = (r: ActionRow, i = index++) =>
481    col(el, [
482      el.Box({
483        flexDirection: 'row',
484        justifyContent: 'space-between',
485        columnGap: 1,
486        children: [
487          wrapRow(
488            el,
489            [
490              ...(r.missing
491                ? [text(el, r.name + (r.dm ? ' ★' : ''), { bold: true, wrap: 'wrap' })]
492                : [word(el, v, make, 'w:act:' + r.key, r.name, { bold: true }, { wrap: 'wrap' }, true), ...(r.dm ? [text(el, '★', { bold: true })] : [])]),
493              ...(r.always ? [dim(el, 'always')] : []),
494              ...r.badges.map((b) => badge(r, i, b)),
495            ],
496            1,
497          ),
498          // Damage the sheet does not write is the data's dice: an amber `?` says so.
499          ...(r.effect
500            ? [el.Box({ flexShrink: 0, flexDirection: 'row', children: [text(el, r.effect, { bold: true }), ...(r.guess ? [text(el, '?', { color: TOKENS.amber })] : [])] })]
501            : []),
502        ],
503      }),
504      el.Box({
505        paddingLeft: 2,
506        children: [
507          wrapRow(
508            el,
509            [
510              ...(showCls && r.cls ? [dim(el, r.cls + ' ·')] : []),
511              // The lead carries the server's number; while that number may change, amber as `value` draws it.
512              ...(r.lead ? [text(el, r.lead, e.derivedPending && r.lead.endsWith('?') ? { color: TOKENS.amber } : {})] : []),
513              ...(r.facts.length ? [dim(el, r.facts.join(' · '))] : []),
514            ],
515          ),
516        ],
517      }),
518      ...openBox(el, v, make, (a) => a === 'w:act:' + r.key),
519      ...preview(el, v, make, (a) => a === 'w:act:' + r.key),
520    ])
521  const out = groups.map((g) => {
522    const s = g.slots
523    const pipW = s ? Math.min(17, Math.max(1, s.max * 2 - 1)) : 0
524    const pips = s ? [pipsNode(el, v.surface, s.left, s.max, pipW, 'ink', of(s.left, s.max)), value(el, `${s.left}/${s.max}`, s.pending)] : []
525    return section(el, heading(el, g.label, pips), g.rows.map((r) => actionRow(r)))
526  })
527  if (!out.length) out.push(dim(el, 'No weapons or spells on this sheet.'))
528  return out
529}
530
531const mark = (el: Base, m: string) => text(el, m, { color: TOKENS.phosphor })
532
533/** Skills: checks, skills (proficiency marked), Hit Dice. The saves and passive Perception are on the HUD. */
534function skillsTab(el: Base, e: Entry, v: PaneView, make: Make): RenderNode[] {
535  const d = e.derived ?? {}
536  const s = e.sheet
537  const pend = e.derivedPending
538  const checks = wrapRow(el, [dim(el, 'CHECKS'), ...ABILITIES.map((a) => stat(el, a.toUpperCase(), signed(d.modifiers?.[a]), pend))])
539  const skillProf = new Map<string, boolean>((s.proficiencies?.skills ?? []).map((k: any) => [String(k.name).toLowerCase(), !!k.expertise]))
540  const cells = Object.entries((d.skills ?? {}) as Record<string, number>)
541    .sort(([a], [b]) => a.localeCompare(b))
542    .map(([name, n]): [string, RenderNode] => {
543      const p = skillProf.get(name.toLowerCase())
544      return [
545        name,
546        el.Box({
547          width: '50%',
548          flexDirection: 'row',
549          justifyContent: 'space-between',
550          paddingRight: 2,
551          children: [row(el, [word(el, v, make, 'w:skill:' + name, name, p === undefined ? { dimColor: true } : {}, {}, true), ...(p === undefined ? [] : [mark(el, p ? '◆' : '●')])]), value(el, signed(n), pend)],
552        }),
553      ]
554    })
555  // Two to a row, each row hanging its own words' preview.
556  const pairs = Array.from({ length: Math.ceil(cells.length / 2) }, (_, i) => cells.slice(2 * i, 2 * i + 2))
557  const skills = col(
558    el,
559    pairs.map((pr) => hang(el, v, make, el.Box({ flexDirection: 'row', children: pr.map(([, c]) => c) }), (a) => pr.some(([name]) => a === 'w:skill:' + name))),
560  )
561  const hd = Object.entries((d.hit_dice ?? {}) as Record<string, number>).map(([die, n]) => `${die} ${Math.max(0, n - (s.hit_dice_spent?.[die] ?? 0))}/${n}`)
562  return [
563    checks,
564    section(el, heading(el, 'Skills'), [
565      skills,
566      ...openBox(el, v, make, (a) => a.startsWith('w:skill:')),
567      ...(hd.length ? [text(el, `Hit Dice ${hd.join(', ')}`, { wrap: 'wrap' })] : []),
568      dim(el, '● proficient · ◆ expertise'),
569    ]),
570  ]
571}
572
573/**
574 * A feature's word, by what it comes from: a feat, the sheet's species or
575 * background (the whole option: they take no feature), or a class or subclass
576 * on the sheet (the one feature); `class` names the sheet's class when it has
577 * one only. Plain where `from` names none of these.
578 */
579function featureKey(s: any, f: any): string | null {
580  const from = norm(String(f.from ?? ''))
581  if (from === 'feat') return `w:c:option:feat|${f.name}|`
582  for (const k of ['species', 'background'] as const) if (s[k]?.name && (from === k || from === norm(s[k].name))) return `w:c:option:${k}|${s[k].name}|${f.name}`
583  if (from === 'class' && s.classes?.length === 1 && s.classes[0].name) return `w:c:option:class|${s.classes[0].name}|${f.name}`
584  for (const c of s.classes ?? []) {
585    if (c.subclass?.name && from === norm(c.subclass.name)) return `w:c:option:subclass|${c.subclass.name}|${f.name}`
586    if (c.name && from === norm(c.name)) return `w:c:option:class|${c.name}|${f.name}`
587  }
588  return null
589}
590
591function featuresTab(el: Base, e: Entry, v: PaneView, make: Make): RenderNode[] {
592  const s = e.sheet
593  // Each word's key ends in its row, so a feat taken twice draws two words.
594  const feat = (f: any, i: number) => {
595    const key = featureKey(s, f)
596    const name = key ? word(el, v, make, `${key}|${i}`, f.name, { bold: true }, {}, true) : text(el, f.name, { bold: true })
597    const line = wordLine(el, name, (f.from ? ` (${f.from})` : '') + (f.choice ? `: ${f.choice}` : '') + (f.note ? ` — ${f.note}` : '') + dmMark(e, f.name))
598    return hang(el, v, make, line, (a) => a === `${key}|${i}`)
599  }
600  const features = [...(s.feats ?? []).map((f: any) => ({ ...f, from: f.from ?? 'feat' })), ...(s.features ?? [])].map(feat)
601  const subclasses = (s.classes ?? []).filter((c: any) => c.subclass?.name).map((c: any) => `- **${c.subclass.name}** (${c.name} ${c.level})`)
602  const pr = s.proficiencies ?? {}
603  const prof = (
604    [
605      ['Armour', pr.armor],
606      ['Weapons', pr.weapons],
607      ['Tools', pr.tools],
608      ['Languages', pr.languages],
609    ] as [string, unknown][]
610  )
611    .filter(([, v]) => Array.isArray(v) && v.length)
612    .map(([k, v]) => `- **${k}:** ${(v as string[]).join(', ')}`)
613  return [
614    ...(subclasses.length ? [section(el, heading(el, 'Subclasses'), [md(el, subclasses)])] : []),
615    section(el, heading(el, 'Features'), features.length ? features : [md(el, ['_None._'])]),
616    ...(prof.length ? [section(el, heading(el, 'Proficiencies'), [md(el, prof)])] : []),
617  ]
618}
619
620/**
621 * Gear: the slots first (armour, shield, hands, attunement), each filled or
622 * free, where AC comes from, and any conflict; then every item, worn or held
623 * ones marked, each with `[ equip ]` or `[ unequip ]` (`eq-<row>`). The slots
624 * are the server's (`derived.equipment`, patch 21); the pane only draws them.
625 */
626function gearTab(el: Base, e: Entry, v: PaneView, make: Make): RenderNode[] {
627  const s = e.sheet
628  const eq = e.derived?.equipment as
629    | { armor: string | null; shield: string | null; hands: { used: number; max: number; items: { name: string; hands: number }[] }; attunement: { used: number; max: number; items: string[] }; carried: string[]; conflicts: { key: string; message: string }[] }
630    | undefined
631  const pending = e.derivedPending
632  const out: RenderNode[] = []
633  const free = (el2: Base) => text(el2, 'free', { color: FAINT_TEXT })
634  const slotLine = (label: string, filled: RenderNode | null) => row(el, [dim(el, label.padEnd(10)), filled ?? free(el)])
635  const named = (n: string) => value(el, n, pending)
636  if (eq) {
637    const lines: RenderNode[] = [
638      slotLine('Armor', eq.armor ? named(eq.armor) : null),
639      slotLine('Shield', eq.shield ? named(eq.shield) : null),
640      row(el, [dim(el, `Hands ${eq.hands.used}/${eq.hands.max}`.padEnd(10)), ...(eq.hands.items.length ? [named(eq.hands.items.map((h) => (h.hands > 1 ? `${h.name} (both)` : h.name)).join(' · '))] : [free(el)])]),
641      row(el, [dim(el, `Attuned ${eq.attunement.used}/${eq.attunement.max}`.padEnd(10)), ...(eq.attunement.items.length ? [named(eq.attunement.items.join(' · '))] : [free(el)])]),
642    ]
643    const ac = e.derived?.ac as { value: number; from: string[] } | null | undefined
644    if (ac) lines.push(text(el, `AC ${ac.value} = ${ac.from.join(' + ')}${pending ? '?' : ''}`, { color: pending ? TOKENS.amber : FAINT_TEXT, wrap: 'wrap' }))
645    for (const c of eq.conflicts) lines.push(text(el, c.message, { color: TOKENS.amber, wrap: 'wrap' }))
646    out.push(section(el, heading(el, 'Worn and held'), lines))
647  }
648  const inSlot = new Set<string>(eq ? [eq.armor, eq.shield, ...eq.hands.items.map((h) => h.name)].filter((n): n is string => !!n) : [])
649  // Each item's name as written: the server answers only a name it prints.
650  // The key ends in the row, so an item listed twice draws two words.
651  const items = (s.inventory ?? []).map((i: any, n: number) => {
652    const key = `w:c:option:item|${i.name}||${n}`
653    const worn = inSlot.has(i.name) && i.equipped !== false
654    const tag = worn ? '▸ ' : '  '
655    const line = row(el, [
656      text(el, tag, { color: TOKENS.phosphor }),
657      wordLine(el, word(el, v, make, key, i.name, worn ? { bold: true } : {}, {}, true), (i.quantity !== 1 ? ` ×${i.quantity}` : '') + (i.attuned ? ' (attuned)' : '') + (i.note ? ` — ${i.note}` : '')),
658      make({ key: `eq-${n}`, label: worn ? 'unequip' : 'equip' }),
659    ])
660    return hang(el, v, make, line, (a) => a === key)
661  })
662  const coins = Object.entries((s.currency ?? {}) as Record<string, number>)
663    .filter(([, n]) => n > 0)
664    .map(([k, n]) => `${n} ${k}`)
665  out.push(section(el, heading(el, 'Inventory'), items.length ? items : [md(el, ['_Nothing written._'])]), text(el, `Money  ${coins.join(', ') || 'none'}`, { bold: true }))
666  return out
667}
668
669/** A companion as the server derives it (patch 21), with the stored HP and status read off the sheet. */
670interface Pet {
671  index: number
672  id: string
673  name: string
674  group?: string
675  status: 'present' | 'dismissed' | 'down'
676  lifetime: { kind: string; spell?: string; hours?: number; elapsed_hours?: number }
677  official: boolean
678  max: number | null
679  current: number
680  temp: number
681  ac: number | null
682  speed: Record<string, number>
683  attacks: { name: string; attack?: string; damage?: string; damage_type?: string }[]
684  /** `heal`: the use's dice as the server works them out (Repair `2d8+3`); `self`: it can heal the companion itself. */
685  resources: { name: string; max: number | null; used: number; heal?: string; self?: boolean }[]
686  errors: string[]
687  origin: string
688}
689
690/** The sheet's companions, in its order: the server's numbers, the sheet's HP, uses and status (a tap's diff lands there first). */
691export function pets(e: Entry): Pet[] {
692  const stored = (e.sheet.companions ?? []) as any[]
693  const derived = (e.derived?.companions ?? []) as any[]
694  return stored.map((c, index) => {
695    const d = derived.find((x) => x.id === c.id) ?? derived[index] ?? {}
696    const hp = c.hp ?? {}
697    return {
698      index,
699      id: String(c.id ?? d.id ?? index),
700      name: String(c.name),
701      ...(c.group ? { group: String(c.group) } : {}),
702      status: (c.status ?? d.status ?? 'present') as Pet['status'],
703      lifetime: (c.lifetime ?? d.lifetime ?? { kind: 'permanent' }) as Pet['lifetime'],
704      official: d.official !== false,
705      max: typeof d.hp?.max === 'number' ? d.hp.max : null,
706      current: typeof hp.current === 'number' ? hp.current : typeof d.hp?.current === 'number' ? d.hp.current : 0,
707      temp: typeof hp.temp === 'number' ? hp.temp : 0,
708      ac: typeof d.ac === 'number' ? d.ac : null,
709      speed: d.speed ?? {},
710      attacks: d.attacks ?? [],
711      resources: ((c.resources ?? []) as any[]).map((r, j) => {
712        const dr = d.resources?.[j]
713        return {
714          name: String(r.name), used: Number(r.used ?? 0), max: typeof dr?.max === 'number' ? dr.max : typeof r.max === 'number' ? r.max : null,
715          ...(typeof dr?.heal === 'string' ? { heal: dr.heal, self: dr.heals_self === true } : {}),
716        }
717      }),
718      errors: d.errors ?? [],
719      origin: [c.creature?.name && c.creature.name !== c.name ? c.creature.name : null, c.origin?.name ?? c.origin?.kind].filter(Boolean).join(' · '),
720    }
721  })
722}
723
724/** `CONC Summon Beast`, `16/24 H`, `UNTIL RECAST`, `KEEPS`. */
725export function lifetimeBadge(l: Pet['lifetime']): string {
726  if (l.kind === 'concentration') return `CONC ${l.spell ?? ''}`.trim()
727  if (l.kind === 'timed') return `${l.elapsed_hours ?? 0}/${l.hours ?? '?'} H`
728  if (l.kind === 'until_replaced') return 'UNTIL RECAST'
729  return 'KEEPS'
730}
731
732/**
733 * Pets: every companion, grouped by its casting, each a card: name, status
734 * and lifetime, the unofficial reminder, the HP gauge, AC and speed, attacks,
735 * uses as pips, and its buttons (`comp-d-<i>` damage, `comp-h-<i>` heal,
736 * `comp-u-<i>-<j>` spend a use, `comp-s-<i>` dismiss or summon back,
737 * `comp-x-<i>` remove). Numbers the server has not re-derived since a write are amber.
738 */
739function companionsTab(el: Base, e: Entry, v: PaneView, make: Make): RenderNode[] {
740  const list = pets(e)
741  if (!list.length) return [dim(el, 'No companions. Ask Claude to add one: a summon, a familiar or steed, a creature the DM gives, or a custom one.')]
742  const pending = e.derivedPending
743  const out: RenderNode[] = []
744  const card = (p: Pet): RenderNode => {
745    const down = p.status === 'down'
746    const away = p.status === 'dismissed'
747    const head = row(el, [
748      text(el, p.name, { bold: !away, dimColor: away, ...(down ? { color: TOKENS.alert } : {}) }),
749      ...(down ? [text(el, 'DOWN', { color: TOKENS.alert, inverse: true })] : away ? [text(el, 'DISMISSED', { color: FAINT_TEXT })] : []),
750      text(el, lifetimeBadge(p.lifetime), { color: p.lifetime.kind === 'concentration' ? TOKENS.violet : FAINT_TEXT }),
751    ])
752    const lines: RenderNode[] = [head]
753    if (p.origin) lines.push(text(el, p.origin, { color: FAINT_TEXT, wrap: 'truncate-end' }))
754    if (!p.official) lines.push(text(el, 'not in the published rules for this character: get the DM\'s ok', { color: TOKENS.amber, wrap: 'wrap' }))
755    if (p.max !== null) {
756      const segs = hpSegments(p.current, p.max, p.temp, Math.max(4, Math.min(20, v.columns - 20)))
757      lines.push(row(el, [gaugeNode(el, v.surface, segs, away ? 'ink' : hpState(p.current, p.max), `HP ${p.current} of ${p.max}`), value(el, `${p.current}/${p.max}${p.temp ? ` +${p.temp}` : ''}`, pending)]))
758    } else lines.push(row(el, [dim(el, 'HP'), value(el, String(p.current), true)]))
759    const walk = p.speed.walk
760    const speeds = Object.entries(p.speed).filter(([k]) => k !== 'walk').map(([k, n]) => `${k} ${n}`)
761    lines.push(wrapRow(el, [stat(el, 'AC', p.ac === null ? '—' : String(p.ac), pending), ...(typeof walk === 'number' ? [stat(el, 'SPD', String(walk))] : []), ...speeds.map((sp) => dim(el, sp))]))
762    for (const a of p.attacks) {
763      lines.push(row(el, [text(el, a.name), ...(a.attack ? [stat(el, 'ATK', a.attack, pending)] : []), ...(a.damage ? [value(el, `${a.damage}${a.damage_type ? ' ' + a.damage_type : ''}`, pending)] : [])]))
764    }
765    for (const [j, r] of p.resources.entries()) {
766      const max = r.max ?? 0
767      const left = Math.max(0, max - r.used)
768      lines.push(row(el, [
769        dim(el, r.name),
770        pipsNode(el, v.surface, left, max, Math.max(1, max), 'phosphor', `${r.name} ${of(left, max)}`),
771        ...(r.heal ? [text(el, `heals ${r.heal}${r.self ? '' : ' (another)'}`, { color: FAINT_TEXT })] : []),
772        make({ key: `comp-u-${p.index}-${j}`, label: 'use' }),
773      ]))
774    }
775    for (const err of p.errors) lines.push(text(el, err, { color: TOKENS.amber, wrap: 'wrap' }))
776    lines.push(row(el, [
777      make({ key: `comp-d-${p.index}`, label: 'dmg' }),
778      make({ key: `comp-h-${p.index}`, label: 'heal' }),
779      ...(down ? [] : [make({ key: `comp-s-${p.index}`, label: away ? 'summon' : 'dismiss' })]),
780      make({ key: `comp-x-${p.index}`, label: 'remove' }),
781    ]))
782    return el.Box({ flexDirection: 'column', marginTop: 1, children: lines })
783  }
784  const groups = new Map<string, Pet[]>()
785  for (const p of list) groups.set(p.group ?? '', [...(groups.get(p.group ?? '') ?? []), p])
786  for (const [g, members] of groups) {
787    if (g) out.push(section(el, heading(el, `${g} · ${members.length}`), members.map(card)))
788    else out.push(...members.map(card))
789  }
790  return out
791}
792
793/** Notes: the DM's rules first, then who the character is, with unresolved names flagged beside them. */
794function notesTab(el: Base, e: Entry): RenderNode[] {
795  const s = e.sheet
796  const out: RenderNode[] = []
797  const rules = (s.house_rules ?? []).map((r: any) => `- ${r.rule}` + (r.by || r.date ? ` _(${[r.by, r.date].filter(Boolean).join(', ')})_` : ''))
798  if (rules.length) out.push(section(el, heading(el, '★ DM rules'), [md(el, rules)]))
799  const flag = (n: string) => (unresolvedName(n, e.unresolved) ? ' — _not in the rules snapshot_' : '')
800  const who: string[] = []
801  if (s.species?.name) who.push(`- **Species:** ${s.species.name}${flag(s.species.name)}` + (s.species.note ? ` — ${s.species.note}` : ''))
802  if (s.background?.name) who.push(`- **Background:** ${s.background.name}${flag(s.background.name)}`)
803  const named = [s.species?.name, s.background?.name].filter(Boolean) as string[]
804  const otherUnresolved = e.unresolved.filter((u) => !named.some((n) => unresolvedName(n, [u])))
805  if (otherUnresolved.length) who.push(`- **Not in the rules snapshot:** ${otherUnresolved.join(', ')}`)
806  for (const [k, v] of Object.entries((s.details ?? {}) as Record<string, string>)) who.push(`- **${k.replace(/_/g, ' ')}:** ${v}`)
807  if (who.length) out.push(section(el, heading(el, 'Character'), [md(el, who)]))
808  if (s.notes) out.push(section(el, heading(el, 'Sheet notes'), [md(el, [String(s.notes)])]))
809  if (!out.length) out.push(dim(el, 'No notes on this sheet.'))
810  return out
811}
812
813function tabBody(el: Base, e: Entry, tab: TabId, v: PaneView, make: Make): RenderNode[] {
814  switch (tab) {
815    case 'skills':
816      return skillsTab(el, e, v, make)
817    case 'features':
818      return featuresTab(el, e, v, make)
819    case 'gear':
820      return gearTab(el, e, v, make)
821    case 'companions':
822      return companionsTab(el, e, v, make)
823    case 'notes':
824      return notesTab(el, e)
825    default:
826      return actionsTab(el, e, v, make)
827  }
828}
829
830/** Does the flash touch a path this pattern names? */
831const flashes = (v: PaneView, re: RegExp) => !!v.flash?.some((p) => re.test(p))
832const slotPath = (s: { label: string; level: number }) =>
833  s.label === 'Pact' ? /^\/spellcasting\/pact_slots_used(\/|$)/ : new RegExp(`^/spellcasting/slots_used/${s.level}(/|$)`)
834
835/** `CHECK 13:19 · 3 WARNINGS · 5 NOTES`. */
836function checkText(c: NonNullable<Entry['check']>): string {
837  const n = (k: number, word: string) => `${k} ${word}${k === 1 ? '' : 'S'}`
838  return `CHECK ${clock(c.at)} · ${n(c.warnings, 'WARNING')} · ${n(c.infos, 'NOTE')}`
839}
840
841/**
842 * How far the pane trusts a sheet's HP. Time passing is no evidence: `seen`
843 * when the copy came from an earlier session or a write's diff showed it had
844 * missed a version; `never` when the sheet holds no current HP; else confirmed.
845 */
846export type HpTruth = 'confirmed' | 'seen' | 'never'
847export const hpTruth = (e: Entry): HpTruth =>
848  typeof e.sheet.hp?.current !== 'number' ? 'never' : e.fromStore || e.drift ? 'seen' : 'confirmed'
849
850export const hpOf = (e: Entry) => {
851  const hp = e.sheet.hp ?? {}
852  return { current: Number(hp.current ?? 0), max: Number(hp.max ?? 0), temp: Number(hp.temp ?? 0) }
853}
854
855// ------------------------------------------------------------------ the HUD (the sheet's top)
856
857/** CSS px a column on the surfaces that draw Svg: the owner's 330 px body is about 46 columns. */
858const PX = 7
859
860/** A cell of the vitals row: its dim label over its value, `width` columns; a glance cell grows to share the slack. */
861const cell = (el: Base, label: string, width: number, node: RenderNode, grow: boolean) =>
862  el.Box({ flexDirection: 'column', width, flexShrink: 0, ...(grow ? { flexGrow: 1 } : {}), children: [dim(el, label), node] })
863/** An Svg left in its slot (`svg` centres). */
864const art = (el: Base, a: Art) => el.Box({ children: [(el as Elements['desktop']).Svg({ source: a.source, alt: a.alt })] })
865
866/** `CONC BLESS`: the spell the sheet concentrates on, violet words. */
867const concTag = (el: Base, e: Entry) => text(el, 'CONC ' + String(e.sheet.concentration.spell).toUpperCase(), { color: TOKENS.violet, wrap: 'truncate-end' })
868
869/**
870 * A line per Concentration save the server raised for this sheet, due now:
871 * `CON SAVE DC 11 · +5 · BLESS · 4 dmg`, alert, inverse and bold, every number
872 * the server's. `[ held ]` drops the line here; `[ lost ]` ends Concentration.
873 */
874function saveLines(el: Base, v: PaneView, e: Entry, make: Make): RenderNode[] {
875  return (v.saves.get(e.id) ?? []).map((s, k) =>
876    wrapRow(el, [
877      text(el, `CON SAVE DC ${s.dc} · ${signed(s.bonus)} · ${s.spell.toUpperCase()}` + (s.damage !== undefined ? ` · ${s.damage} dmg` : ''), { color: TOKENS.alert, inverse: true, bold: true, wrap: 'wrap' }),
878      row(el, [make({ key: `held-${e.id}-${k}`, label: 'held' }), make({ key: `lost-${e.id}-${k}`, label: 'lost' })]),
879    ], 1),
880  )
881}
882
883/**
884 * The header: the level badge, the name bold beside it, the classes under the
885 * name, and the DM-rules badge (a press away from the notes tab). On Svg
886 * surfaces the badge is pixel art, a frame round `LV` and a 4× level; on the
887 * terminal an inverse block between half-block caps, `▐LV 2▌`. The schema holds no XP, so no XP bar.
888 */
889function header(el: Base, v: PaneView, e: Entry, make: Make): RenderNode {
890  const lv = level(e)
891  const tone: HpState = lv.endsWith('?') ? 'amber' : 'phosphor'
892  const classes = (e.sheet.classes ?? []).map((c: any) => `${c.name} ${c.level}`).join(' · ')
893  const rules = (e.sheet.house_rules ?? []).length
894  const pix = pixel(v.surface)
895  const c = TOKENS[tone]
896  const badge = pix
897    ? art(el, badgeSvg(lv, tone, `Level ${lv}`))
898    : row(el, [text(el, '▐', { color: c }), text(el, `LV ${lv}`, { color: c, inverse: true, bold: true }), text(el, '▌', { color: c })], 0)
899  return el.Box({
900    flexDirection: 'row',
901    columnGap: pix ? 2 : 1,
902    alignItems: pix ? 'center' : 'flex-start',
903    children: [
904      el.Box({ flexShrink: 0, children: [badge] }),
905      el.Box({
906        flexDirection: 'column',
907        flexShrink: 1,
908        children: [
909          text(el, e.name, { bold: true, wrap: 'truncate-end' }),
910          ...(classes ? [dim(el, classes)] : []),
911          ...(e.sheet.concentration ? [concTag(el, e)] : []),
912          ...(rules ? [row(el, [make({ key: RULES_KEY, label: `★ ${rules} dm rule${rules === 1 ? '' : 's'}`, hotkey: 'm' })])] : []),
913        ],
914      }),
915    ],
916  })
917}
918
919/**
920 * The vitals row, labels over values, one strip as wide as the body: AC, HP
921 * and its gauge, INIT, SPD, PP. Each glance cell is as wide as its label or
922 * value; HP's gauge takes what is left (one cell an HP while they fit), and
923 * any room the gauge cannot use is shared evenly by the glance cells. On the
924 * terminal HP digits are ink, inverse in alert or while flashing, and the
925 * state colour is on the gauge. On Svg surfaces every value is a pixel
926 * readout: AC at 4×, the HP's size; INIT, SPD and PP at 4× while HP keeps its
927 * smallest gauge (4 cells), else at 2×. A value that may change is amber
928 * with a `?`.
929 */
930function vitals(el: Base, v: PaneView, e: Entry): RenderNode {
931  const d = e.derived
932  const pend = e.derivedPending || !d
933  const { current, max, temp } = hpOf(e)
934  const state = hpState(current, max)
935  const flash = flashes(v, /^\/hp(\/|$)/)
936  const truth = hpTruth(e)
937  const glance = [
938    { label: 'AC', s: String(e.sheet.ac?.value ?? '?'), pending: false },
939    { label: 'INIT', s: signed(d?.initiative), pending: pend },
940    { label: 'SPD', s: String(e.sheet.speed?.walk ?? '?'), pending: false },
941    { label: 'PP', s: String(d?.passive_perception ?? '?'), pending: pend },
942  ].map((g) => ({ ...g, s: g.pending ? g.s + '?' : g.s }))
943  const C = v.columns
944  // Two columns between the cells on Svg surfaces: readouts end at their last pixel, so one column lets AC and HP touch.
945  const gap = pixel(v.surface) ? 2 : 1
946  const room = (ws: number[]) => C - gap * glance.length - ws.reduce((n, w) => n + w, 0)
947  const row5 = (hp: RenderNode, cells: RenderNode[]) => el.Box({ flexDirection: 'row', columnGap: gap, children: [cells[0]!, hp, ...cells.slice(1)] })
948
949  if (!pixel(v.surface)) {
950    const ws = glance.map((g) => Math.max(g.label.length, g.s.length))
951    const lead = truth === 'seen' ? [text(el, '~', { color: FAINT_TEXT })] : []
952    const digits = truth === 'never' ? [text(el, '—', { color: FAINT_TEXT }), dim(el, `/${max}`)] : [text(el, `${current}/${max}`, { bold: true, ...(state === 'alert' || flash ? { inverse: true } : {}) })]
953    const tempText = temp > 0 && truth !== 'never' ? `+${temp}` : ''
954    const used = (truth === 'seen' ? 2 : 0) + (truth === 'never' ? 1 + `/${max}`.length : `${current}/${max}`.length) + 1 + (tempText ? tempText.length + 1 : 0)
955    const n = Math.max(4, room(ws) - used)
956    const segs = truth === 'never' ? noneSegments(n) : hpSegments(current, max, temp, n)
957    const hp = row(el, [
958      row(el, [...lead, ...digits], truth === 'seen' ? 1 : 0),
959      ...(tempText ? [text(el, tempText, { color: TOKENS.cyan, bold: true })] : []),
960      gauge(el, gaugeRuns(segs, state)),
961    ])
962    const cells = glance.map((g, i) => cell(el, g.label, ws[i]!, text(el, g.s, g.pending ? { color: TOKENS.amber } : { bold: true }), true))
963    return row5(cell(el, 'HP', used + segs.length, hp, false), cells)
964  }
965
966  // Svg surfaces: INIT, SPD and PP at the largest scale that leaves HP its smallest gauge.
967  const hpBase = hpSvg(current, max, temp, state, { flash, truth, width: 0 }).width - 38
968  const fit = (scale: 2 | 4) =>
969    glance.map((g, i) => {
970      const a = readoutSvg(g.s, i === 0 ? 4 : scale, g.pending ? 'amber' : 'ink', `${g.label} ${g.s}`)
971      return { g, a, w: Math.max(g.label.length + 1, Math.ceil(a.width / PX)) }
972    })
973  const big = fit(4)
974  const cs = room(big.map((c) => c.w)) * PX >= hpBase + 38 ? big : fit(2)
975  const hpArt = hpSvg(current, max, temp, state, { flash, truth, width: room(cs.map((c) => c.w)) * PX })
976  const cells = cs.map((c) => cell(el, c.g.label, c.w, art(el, c.a), true))
977  return row5(cell(el, 'HP', Math.ceil(hpArt.width / PX), art(el, hpArt), false), cells)
978}
979
980/**
981 * The six saves in a grid: the abilities over their bonuses, a `SAVE` label at
982 * the left. A proficient save is bold with a phosphor `●`, its ability in ink;
983 * the others plain, their ability dim.
984 */
985function saveGrid(el: Base, v: PaneView, e: Entry, make: Make): RenderNode {
986  const d = e.derived
987  const pend = e.derivedPending || !d
988  const prof = new Set<string>(e.sheet.proficiencies?.saves ?? [])
989  const w = Math.max(4, Math.floor((v.columns - 6) / 6))
990  const lead = (s: string) => el.Box({ width: 6, flexShrink: 0, children: [dim(el, s)] })
991  const at = (node: RenderNode) => el.Box({ width: w, flexShrink: 0, children: [node] })
992  return col(el, [
993    row(el, [lead(''), ...ABILITIES.map((a) => at(word(el, v, make, 'w:save:' + a, a.toUpperCase(), prof.has(a) ? {} : { dimColor: true })))], 0),
994    row(
995      el,
996      [
997        lead('SAVE'),
998        ...ABILITIES.map((a) => {
999          const s = signed(d?.saving_throws?.[a])
1000          const val = pend ? text(el, s + '?', { color: TOKENS.amber }) : text(el, s, prof.has(a) ? { bold: true } : {})
1001          return at(row(el, [val, ...(prof.has(a) ? [mark(el, '●')] : [])], 0))
1002        }),
1003      ],
1004      0,
1005    ),
1006  ])
1007}
1008
1009/** Pips as glyphs: available a phosphor `●`, spent a faint `○`; past 10, a bold `left/max`. Inverse while flashing. */
1010function pipGlyphs(el: Base, left: number, max: number, flash: boolean): RenderNode {
1011  const inv = flash ? { inverse: true } : {}
1012  if (max > 10) return text(el, `${left}/${max}`, { bold: true, ...inv })
1013  return row(
1014    el,
1015    [
1016      ...(left ? [text(el, '●'.repeat(left), { color: TOKENS.phosphor, ...inv })] : []),
1017      ...(max - left ? [text(el, '○'.repeat(max - left), { color: FAINT_TEXT, ...inv })] : []),
1018    ],
1019    0,
1020  )
1021}
1022
1023/**
1024 * Slots and resources inline, two to a line: a slot is its tap (`[ 1st ]`, its
1025 * digit a silent shortcut) and its pips; a resource its name and pips, the name
1026 * faint once all of it is spent. A slot count that may change gets an amber `?`.
1027 */
1028function pipCells(el: Base, v: PaneView, e: Entry, make: Make): RenderNode[] {
1029  const w = Math.max(12, Math.floor((v.columns - 2) / 2))
1030  const at = (children: RenderNode[]) => el.Box({ width: w, flexShrink: 0, flexDirection: 'row', columnGap: 1, children })
1031  const slots = slotRows(e).map((s) =>
1032    at([
1033      make({ key: s.key!, label: s.label, hotkey: s.hotkey! }),
1034      pipGlyphs(el, s.left, s.max, flashes(v, slotPath(s))),
1035      ...(s.pending ? [text(el, '?', { color: TOKENS.amber })] : []),
1036    ]),
1037  )
1038  // A resource's name is a word, cut beforehand to what its cell leaves beside the pips (a Client has no truncation of its own).
1039  const res = resources(e).map((r, i) =>
1040    at([
1041      el.Box({
1042        flexShrink: 1,
1043        children: [word(el, v, make, 'w:res:' + i, cut(r.label, w - 1 - (r.max > 10 ? `${r.left}/${r.max}`.length : r.max)), r.left ? {} : { color: FAINT_TEXT }, { wrap: 'truncate-end' })],
1044      }),
1045      el.Box({ flexShrink: 0, children: [pipGlyphs(el, r.left, r.max, flashes(v, new RegExp(`^/resources/${i}(/|$)`)))] }),
1046    ]),
1047  )
1048  return [...slots, ...res]
1049}
1050
1051/**
1052 * The tab rule: the section rule, its words the tabs, one row that never
1053 * wraps. The open tab is inverse text (pressing it would do nothing); the
1054 * others are plain, dim Buttons with no hotkey.
1055 */
1056function tabRule(el: Base, v: PaneView, make: Make): RenderNode {
1057  const faint = (s: string) => el.Box({ flexShrink: 0, children: [text(el, s, { color: FAINT_TEXT })] })
1058  const kids: RenderNode[] = [faint('─ ')]
1059  TABS.forEach((t, i) => {
1060    if (i) kids.push(faint(' ─ '))
1061    kids.push(
1062      el.Box({
1063        flexShrink: 0,
1064        children: [t.id === v.tab ? text(el, ` ${t.label} `, { inverse: true, bold: true }) : make({ key: tabKey(t.id), label: t.label, plain: true, dimColor: true })],
1065      }),
1066    )
1067  })
1068  kids.push(fill(el, v.columns, { color: FAINT_TEXT }, 1))
1069  return el.Box({ flexDirection: 'row', marginTop: 1, overflow: 'hidden', children: kids })
1070}
1071
1072// ------------------------------------------------------------------ entry points
1073
1074/** The pane: the top screen. The sheet: the HUD, the tab rule, the open tab, the readouts. */
1075export function paneTree(el: Els, v: PaneView): RenderElement {
1076  if (v.screen === 'party') return partyTree(el, v)
1077  if (v.screen === 'packs') return packsTree(el, v)
1078  if (v.screen === 'packet') return packetTree(el, v)
1079  if (v.screen === 'log') return logTree(el, v)
1080  if (v.screen === 'look' || v.screen === 'card') return lookTree(el, v)
1081  const { make, done } = buttons(el, v.memo)
1082  const kids: RenderNode[] = navLine(el, v, make)
1083  const e = v.entry
1084  if (!e) {
1085    kids.push(
1086      row(el, [text(el, 'AWAITING SHEET'), text(el, '█', { color: TOKENS.phosphor })]),
1087      text(el, 'Ask Claude to show your sheet; the pane fills in from its sheet_read result.', { dimColor: true, wrap: 'wrap' }),
1088    )
1089    done()
1090    return col(el, kids)
1091  }
1092  kids.push(header(el, v, e, make))
1093  // The alert field, `⚠ POISONED · EXHAUSTION 1`: inverse amber, the MU-TH-UR highlight. The words are the signal,
1094  // the colour the second one. Each condition is a word with its box; the line is laid out here, a nowrap row a line.
1095  const ex = Number(e.sheet.exhaustion ?? 0)
1096  const alerts = [
1097    ...(e.sheet.conditions ?? []).map((c: unknown) => ({ key: String(c).toLowerCase(), label: String(c).toUpperCase() })),
1098    ...(ex > 0 ? [{ key: 'exhaustion', label: `EXHAUSTION ${ex}` }] : []),
1099  ]
1100  const alertFlash = flashes(v, /^\/(conditions(\/|$)|exhaustion$)/)
1101  const loud = { color: TOKENS.amber, inverse: true, bold: true }
1102  const flashed = alertFlash ? { underline: true } : {}
1103  const units = alerts.map((a, i) => {
1104    const head = i ? '' : '⚠ '
1105    const tail = i < alerts.length - 1 ? ' · ' : ''
1106    const nodes = [
1107      ...(head ? [text(el, head, { ...loud, ...flashed })] : []),
1108      word(el, v, make, `w:cond:${e.id}:${a.key}`, a.label, loud, flashed),
1109      ...(tail ? [text(el, tail, { ...loud, ...flashed })] : []),
1110    ]
1111    return { width: head.length + a.label.length + tail.length, node: el.Box({ flexDirection: 'row', flexShrink: 0, children: nodes }) }
1112  })
1113  for (const line of greedy(units, (u) => u.width, v.columns, 0)) kids.push(el.Box({ flexDirection: 'row', children: line.map((u) => u.node) }))
1114  kids.push(...openBox(el, v, make, (a) => a.startsWith(`w:cond:${e.id}:`)))
1115  kids.push(...saveLines(el, v, e, make))
1116  kids.push(vitals(el, v, e))
1117  const speeds = otherSpeeds(e.sheet)
1118  if (speeds.length) kids.push(text(el, speeds.join(' · '), { color: FAINT_TEXT }))
1119
1120  // The taps (register.ts): damage and heal at the left; at the right, undo while
1121  // there is a tap of this machine's to undo, then coins; the number field while one asks,
1122  // with its apply and cancel. The phone has no Input (see partyTree), so the surface is asked too.
1123  kids.push(
1124    el.Box({
1125      flexDirection: 'row',
1126      justifyContent: 'space-between',
1127      children: [
1128        row(el, [make({ key: 'tap-d', label: 'dmg', hotkey: 'd' }), make({ key: 'tap-h', label: 'heal', hotkey: 'h' })]),
1129        row(el, [...(v.undo ? [make({ key: 'tap-u', label: 'undo', hotkey: 'u' })] : []), make({ key: 'tap-c', label: 'coins' })]),
1130      ],
1131    }),
1132  )
1133  if (v.note) kids.push(text(el, v.note, { color: TOKENS.amber, wrap: 'wrap' }))
1134  if (v.tap && 'Input' in el && v.surface !== 'mobile') {
1135    kids.push(
1136      el.Input({ key: 'tap-amount', label: `${v.tap.companion?.use?.label ?? v.tap.kind} · ${v.tap.companion?.name ?? e.name}`, value: v.tap.text, autoFocus: true, submitLabel: 'apply', onSubmit: NOOP }),
1137      // No number: the server raises the save and its DC after the write (patch 19).
1138      ...(v.tap.kind === 'damage' && !v.tap.companion && e.sheet.concentration ? [text(el, 'CON save due unless this drops them to 0', { color: TOKENS.violet, wrap: 'wrap' })] : []),
1139      goCancel(el, make, 'tap', 'apply'),
1140    )
1141  }
1142  const cs = casters(e)
1143  if (cs.length) kids.push(wrapRow(el, cs.map((c) => row(el, [dim(el, c.cls), stat(el, 'DC', c.dc, e.derivedPending), stat(el, 'ATK', c.attack, e.derivedPending)]))))
1144  kids.push(saveGrid(el, v, e, make), ...openBox(el, v, make, (a) => a.startsWith('w:save:')))
1145  const pips = pipCells(el, v, e, make)
1146  if (pips.length) kids.push(el.Box({ flexDirection: 'row', flexWrap: 'wrap', columnGap: 2, children: pips }), ...openBox(el, v, make, (a) => a.startsWith('w:res:')))
1147
1148  // The tab rule, the open tab, and the readouts: when HP is not confirmed, when
1149  // it was seen and a re-read; the last check's count while it warns.
1150  const c = e.check
1151  const truth = hpTruth(e)
1152  kids.push(tabRule(el, v, make), ...tabBody(el, e, v.tab, v, make))
1153  const off = v.reread && !('at' in v.reread) ? rereadText(v) : null
1154  const foot: RenderNode[] = [
1155    ...(off ? [text(el, off, { color: FAINT_TEXT, wrap: 'wrap' })] : []),
1156    ...(truth !== 'confirmed'
1157      ? [
1158          hang(
1159            el,
1160            v,
1161            make,
1162            row(el, [
1163              word(el, v, make, 'w:seen:' + e.id, `seen ${sameDay(e.readAt, v.now) ? clock(e.readAt) : day(e.readAt)}`, { color: FAINT_TEXT }, {}, true),
1164              text(el, '·', { color: FAINT_TEXT }),
1165              make({ key: 'reread', label: 're-read', hotkey: 'e' }),
1166            ]),
1167            (a) => a === 'w:seen:' + e.id,
1168          ),
1169        ]
1170      : []),
1171    ...(c && c.warnings > 0 && c.version === e.version ? [text(el, checkText(c), { color: FAINT_TEXT, wrap: 'wrap' })] : []),
1172  ]
1173  if (foot.length) kids.push(el.Box({ flexDirection: 'column', marginTop: 1, children: foot }))
1174  kids.push(...openBox(el, v, make, (a) => a === 'w:seen:' + e.id))
1175  done()
1176  return col(el, kids)
1177}
1178
1179/** The log's entries a party view shows: the last 3 in a fight, else the last 8; `[ all ]` shows the rest. */
1180const LOG_FIGHT = 3
1181const LOG_IDLE = 8
1182/** The clock's fixed column: `22:31`. */
1183const CLOCK_W = 5
1184
1185/**
1186 * The log's entries from `from` on: a faint clock in a fixed column, top-aligned,
1187 * and the entry as one plain Button cut with `…`; a press draws it whole in place.
1188 */
1189function logRows(el: Base, v: PaneView, make: Make, from: number): RenderNode[] {
1190  const entries = v.log?.entries ?? []
1191  const w = Math.max(8, v.columns - CLOCK_W - 1)
1192  return entries.slice(from).map((t, k) => {
1193    const i = from + k
1194    const label = v.logOpen === i || t.text.length <= w ? t.text : t.text.slice(0, w - 1) + '…'
1195    return el.Box({
1196      flexDirection: 'row',
1197      columnGap: 1,
1198      alignItems: 'flex-start',
1199      children: [
1200        el.Box({ width: CLOCK_W, flexShrink: 0, children: [text(el, clock(t.at), { color: FAINT_TEXT })] }),
hooks/facts.ts 1022 lines
1// GENERATED by tools/toa-sheet/facts/build.py: do not edit. Regenerate after a
2// rules data refresh (tools/rules/README.md, "Refresh the data").
3// Source: 5etools-mirror-3/5etools-src @ 3a09c05a3a3be94423cd2b3c33936034eeae02f2,
4// the rules server's own pinned snapshot (tools/rules/pins.env), every file checked
5// against tools/rules/data-manifest.json. Facts only: no descriptions, no prose.
6//
7// Keys are `name|source`, the name lower-cased with every run of other characters
8// a space (the server's `norm`). Values are positional (SpellRow, WeaponRow).
9
10export const DATA_REV = '3a09c05a3a3be94423cd2b3c33936034eeae02f2'
11
12/**
13 * [level, school letter, casting time, range or area, components (VSM), duration,
14 *  flags (conc ritual melee ranged heal mod), damage types, save ability, dice].
15 * Dice: a slot spell's base ("2d8"); a cantrip's table by character level
16 * ("1:1d10 5:2d10 11:3d10 17:4d10"; "/" between alternatives); "" when the data
17 * gives no single base.
18 */
19export type SpellRow = readonly [number, string, string, string, string, string, string, string, string, string]
20
21/** [category, melee or ranged, damage dice, damage type, versatile dice, properties, range, mastery]. */
22export type WeaponRow = readonly [string, string, string, string, string, string, string, string]
23
24export const SPELLS: Record<string, SpellRow> = {
25"abi dalzim s horrid wilting|xge":[8,"N","Action","150 ft","VSM","Instant","","necrotic","CON",""],
26"absorb elements|xge":[1,"A","Reaction","Self","S","1 round","","","",""],
27"acid splash|phb":[0,"C","Action","60 ft","VS","Instant","","acid","DEX","1:1d6 5:2d6 11:3d6 17:4d6"],
28"acid splash|xphb":[0,"V","Action","60 ft","VS","Instant","","acid","DEX","1:1d6 5:2d6 11:3d6 17:4d6"],
29"aganazzar s scorcher|xge":[2,"V","Action","30 ft","VSM","Instant","","fire","DEX","3d8"],
30"aid|phb":[2,"A","Action","30 ft","VSM","8 hr","heal","","",""],
31"aid|xphb":[2,"A","Action","30 ft","VSM","8 hr","heal","","",""],
32"alarm|phb":[1,"A","1 min","30 ft","VSM","8 hr","ritual","","",""],
33"alarm|xphb":[1,"A","1 min","30 ft","VSM","8 hr","ritual","","",""],
34"alter self|phb":[2,"T","Action","Self","VS","1 hr","conc","bludgeoning,piercing,slashing","",""],
35"alter self|xphb":[2,"T","Action","Self","VS","1 hr","conc","bludgeoning,piercing,slashing","",""],
36"animal friendship|phb":[1,"E","Action","30 ft","VSM","24 hr","","","WIS",""],
37"animal friendship|xphb":[1,"E","Action","30 ft","VSM","24 hr","","","WIS",""],
38"animal messenger|phb":[2,"E","Action","30 ft","VSM","24 hr","ritual","","",""],
39"animal messenger|xphb":[2,"E","Action","30 ft","VSM","24 hr","ritual","","CHA",""],
40"animal shapes|phb":[8,"T","Action","30 ft","VS","24 hr","conc","","",""],
41"animal shapes|xphb":[8,"T","Action","30 ft","VS","24 hr","","","",""],
42"animate dead|phb":[3,"N","1 min","10 ft","VSM","Instant","","","",""],
43"animate dead|xphb":[3,"N","1 min","10 ft","VSM","Instant","","","",""],
44"animate objects|phb":[5,"T","Action","120 ft","VS","1 min","conc","bludgeoning,piercing,slashing","",""],
45"animate objects|xphb":[5,"T","Action","120 ft","VS","1 min","conc","bludgeoning,piercing,slashing","",""],
46"antilife shell|phb":[5,"A","Action","10 ft radius","VS","1 hr","conc","","",""],
47"antilife shell|xphb":[5,"A","Action","10 ft emanation","VS","1 hr","conc","","",""],
48"antimagic field|phb":[8,"A","Action","10 ft sphere","VSM","1 hr","conc","","",""],
49"antimagic field|xphb":[8,"A","Action","10 ft emanation","VSM","1 hr","conc","","",""],
50"antipathy sympathy|phb":[8,"E","1 hr","60 ft","VSM","10 days","","","WIS",""],
51"antipathy sympathy|xphb":[8,"E","1 hr","60 ft","VSM","10 days","","","WIS",""],
52"arcane eye|phb":[4,"D","Action","30 ft","VSM","1 hr","conc","","",""],
53"arcane eye|xphb":[4,"D","Action","30 ft","VSM","1 hr","conc","","",""],
54"arcane gate|phb":[6,"C","Action","500 ft","VS","10 min","conc","","",""],
55"arcane gate|xphb":[6,"C","Action","500 ft","VS","10 min","conc","","",""],
56"arcane lock|phb":[2,"A","Action","Touch","VSM","Until dispelled","","","",""],
57"arcane lock|xphb":[2,"A","Action","Touch","VSM","Until dispelled","","","",""],
58"arcane vigor|xphb":[2,"A","Bonus Action","Self","VS","Instant","heal","","",""],
59"armor of agathys|phb":[1,"A","Action","Self","VSM","1 hr","","cold","",""],
60"armor of agathys|xphb":[1,"A","Bonus Action","Self","VSM","1 hr","","cold","",""],
61"arms of hadar|phb":[1,"C","Action","10 ft radius","VS","Instant","","necrotic","STR","2d6"],
62"arms of hadar|xphb":[1,"C","Action","10 ft emanation","VS","Instant","","necrotic","STR","2d6"],
63"astral projection|phb":[9,"N","1 hr","10 ft","VSM","Special","","","",""],
64"astral projection|xphb":[9,"N","1 hr","10 ft","VSM","Until dispelled","","","",""],
65"augury|phb":[2,"D","1 min","Self","VSM","Instant","ritual","","",""],
66"augury|xphb":[2,"D","1 min","Self","VSM","Instant","ritual","","",""],
67"aura of life|phb":[4,"A","Action","30 ft radius","V","10 min","conc heal","","",""],
68"aura of life|xphb":[4,"A","Action","30 ft emanation","V","10 min","conc heal","","",""],
69"aura of purity|phb":[4,"A","Action","30 ft radius","V","10 min","conc","","",""],
70"aura of purity|xphb":[4,"A","Action","30 ft emanation","V","10 min","conc","","",""],
71"aura of vitality|phb":[3,"V","Action","30 ft radius","V","1 min","conc heal","","",""],
72"aura of vitality|xphb":[3,"A","Action","30 ft emanation","V","1 min","conc heal","","",""],
73"awaken|phb":[5,"T","8 hr","Touch","VSM","Instant","","","",""],
74"awaken|xphb":[5,"T","8 hr","Touch","VSM","Instant","","","",""],
75"bane|phb":[1,"E","Action","30 ft","VSM","1 min","conc","","CHA",""],
76"bane|xphb":[1,"E","Action","30 ft","VSM","1 min","conc","","CHA",""],
77"banishing smite|phb":[5,"A","Bonus Action","Self","V","1 min","conc","force","",""],
78"banishing smite|xphb":[5,"C","Bonus Action","Self","V","1 min","conc","force","",""],
79"banishment|phb":[4,"A","Action","60 ft","VSM","1 min","conc","","CHA",""],
80"banishment|xphb":[4,"A","Action","30 ft","VSM","1 min","conc","","CHA",""],
81"barkskin|phb":[2,"T","Action","Touch","VSM","1 hr","conc","","",""],
82"barkskin|xphb":[2,"T","Bonus Action","Touch","VSM","1 hr","","","",""],
83"beacon of hope|phb":[3,"A","Action","30 ft","VS","1 min","conc heal","","",""],
84"beacon of hope|xphb":[3,"A","Action","30 ft","VS","1 min","conc heal","","",""],
85"beast bond|xge":[1,"D","Action","Touch","VSM","10 min","conc","","",""],
86"beast sense|phb":[2,"D","Action","Touch","S","1 hr","conc ritual","","",""],
87"beast sense|xphb":[2,"D","Action","Touch","S","1 hr","conc ritual","","",""],
88"befuddlement|xphb":[8,"E","Action","150 ft","VSM","Instant","","psychic","INT",""],
89"bestow curse|phb":[3,"N","Action","Touch","VS","1 min","conc","necrotic","WIS",""],
90"bestow curse|xphb":[3,"N","Action","Touch","VS","1 min","conc","necrotic","WIS",""],
91"bigby s hand|phb":[5,"V","Action","120 ft","VSM","1 min","conc melee","bludgeoning,force","",""],
92"bigby s hand|xphb":[5,"V","Action","120 ft","VSM","1 min","conc melee","bludgeoning,force","DEX/STR",""],
93"blade barrier|phb":[6,"V","Action","90 ft","VS","10 min","conc","slashing","DEX",""],
94"blade barrier|xphb":[6,"V","Action","90 ft","VS","10 min","conc","force","DEX",""],
95"blade of disaster|tce":[9,"C","Bonus Action","60 ft","VS","1 min","conc melee","force","",""],
96"blade ward|phb":[0,"A","Action","Self","VS","1 round","","","",""],
97"blade ward|xphb":[0,"A","Action","Self","VS","1 min","conc","","",""],
98"bless|phb":[1,"E","Action","30 ft","VSM","1 min","conc","","",""],
99"bless|xphb":[1,"E","Action","30 ft","VSM","1 min","conc","","",""],
100"blight|phb":[4,"N","Action","30 ft","VS","Instant","","necrotic","CON","8d8"],
101"blight|xphb":[4,"N","Action","30 ft","VS","Instant","","necrotic","CON","8d8"],
102"blinding smite|phb":[3,"V","Bonus Action","Self","V","1 min","conc","radiant","CON",""],
103"blinding smite|xphb":[3,"V","Bonus Action","Self","V","1 min","","radiant","CON","3d8"],
104"blindness deafness|phb":[2,"N","Action","30 ft","V","1 min","","","CON",""],
105"blindness deafness|xphb":[2,"T","Action","120 ft","V","1 min","","","CON",""],
106"blink|phb":[3,"T","Action","Self","VS","1 min","","","",""],
107"blink|xphb":[3,"T","Action","Self","VS","1 min","","","",""],
108"blur|phb":[2,"I","Action","Self","V","1 min","conc","","",""],
109"blur|xphb":[2,"I","Action","Self","V","1 min","conc","","",""],
110"bones of the earth|xge":[6,"T","Action","120 ft","VS","Instant","","bludgeoning","DEX",""],
111"booming blade|tce":[0,"V","Action","5 ft radius","SM","1 round","melee","thunder","","1:1d8/ 5:2d8/1d8 11:3d8/2d8 17:4d8/3d8"],
112"branding smite|phb":[2,"V","Bonus Action","Self","V","1 min","conc","radiant","","2d6"],
113"burning hands|phb":[1,"V","Action","15 ft cone","VS","Instant","","fire","DEX","3d6"],
114"burning hands|xphb":[1,"V","Action","15 ft cone","VS","Instant","","fire","DEX","3d6"],
115"call lightning|phb":[3,"C","Action","120 ft","VS","10 min","conc","lightning","DEX","3d10"],
116"call lightning|xphb":[3,"C","Action","120 ft","VS","10 min","conc","lightning","DEX","3d10"],
117"calm emotions|phb":[2,"E","Action","60 ft","VS","1 min","conc","","CHA",""],
118"calm emotions|xphb":[2,"E","Action","60 ft","VS","1 min","conc","","CHA",""],
119"catapult|xge":[1,"T","Action","60 ft","S","Instant","","bludgeoning","DEX","3d8"],
120"catnap|xge":[3,"E","Action","30 ft","SM","10 min","","","",""],
121"cause fear|xge":[1,"N","Action","60 ft","V","1 min","conc","","WIS",""],
122"ceremony|xge":[1,"A","1 hr","Touch","VSM","Instant","ritual","","",""],
123"chain lightning|phb":[6,"V","Action","150 ft","VSM","Instant","","lightning","DEX",""],
124"chain lightning|xphb":[6,"V","Action","150 ft","VSM","Instant","","lightning","DEX",""],
125"chaos bolt|xge":[1,"V","Action","120 ft","VS","Instant","ranged","acid,cold,fire,force,lightning,poison,psychic,thunder","","2d8 + 1d6"],
126"charm monster|xge":[4,"E","Action","30 ft","VS","1 hr","","","WIS",""],
127"charm monster|xphb":[4,"E","Action","30 ft","VS","1 hr","","","WIS",""],
128"charm person|phb":[1,"E","Action","30 ft","VS","1 hr","","","WIS",""],
129"charm person|xphb":[1,"E","Action","30 ft","VS","1 hr","","","WIS",""],
130"chill touch|phb":[0,"N","Action","120 ft","VS","1 round","ranged","necrotic","","1:1d8 5:2d8 11:3d8 17:4d8"],
131"chill touch|xphb":[0,"N","Action","Touch","VS","Instant","melee","necrotic","","1:1d10 5:2d10 11:3d10 17:4d10"],
132"chromatic orb|phb":[1,"V","Action","90 ft","VSM","Instant","ranged","acid,cold,fire,lightning,poison,thunder","","3d8"],
133"chromatic orb|xphb":[1,"V","Action","90 ft","VSM","Instant","ranged","acid,cold,fire,lightning,poison,thunder","","3d8"],
134"circle of death|phb":[6,"N","Action","150 ft","VSM","Instant","","necrotic","CON","8d6"],
135"circle of death|xphb":[6,"N","Action","150 ft","VSM","Instant","","necrotic","CON","8d8"],
136"circle of power|phb":[5,"A","Action","30 ft radius","V","10 min","conc","","",""],
137"circle of power|xphb":[5,"A","Action","30 ft emanation","V","10 min","conc","","",""],
138"clairvoyance|phb":[3,"D","10 min","1 mile","VSM","10 min","conc","","",""],
139"clairvoyance|xphb":[3,"D","10 min","1 mile","VSM","10 min","conc","","",""],
140"clone|phb":[8,"N","1 hr","Touch","VSM","Instant","","","",""],
141"clone|xphb":[8,"N","1 hr","Touch","VSM","Instant","","","",""],
142"cloud of daggers|phb":[2,"C","Action","60 ft","VSM","1 min","conc","slashing","","4d4"],
143"cloud of daggers|xphb":[2,"C","Action","60 ft","VSM","1 min","conc","slashing","","4d4"],
144"cloudkill|phb":[5,"C","Action","120 ft","VS","10 min","conc","poison","CON","5d8"],
145"cloudkill|xphb":[5,"C","Action","120 ft","VS","10 min","conc","poison","CON","5d8"],
146"color spray|phb":[1,"I","Action","15 ft cone","VSM","1 round","","","",""],
147"color spray|xphb":[1,"I","Action","15 ft cone","VSM","Instant","","","CON",""],
148"command|phb":[1,"E","Action","60 ft","V","1 round","","","WIS",""],
149"command|xphb":[1,"E","Action","60 ft","V","Instant","","","WIS",""],
150"commune with nature|phb":[5,"D","1 min","Self","VS","Instant","ritual","","",""],
151"commune with nature|xphb":[5,"D","1 min","Self","VS","1 min","ritual","","",""],
152"commune|phb":[5,"D","1 min","Self","VSM","1 min","ritual","","",""],
153"commune|xphb":[5,"D","1 min","Self","VSM","1 min","ritual","","",""],
154"compelled duel|phb":[1,"E","Bonus Action","30 ft","V","1 min","conc","","WIS",""],
155"compelled duel|xphb":[1,"E","Bonus Action","30 ft","V","1 min","conc","","WIS",""],
156"comprehend languages|phb":[1,"D","Action","Self","VSM","1 hr","ritual","","",""],
157"comprehend languages|xphb":[1,"D","Action","Self","VSM","1 hr","ritual","","",""],
158"compulsion|phb":[4,"E","Action","30 ft","VS","1 min","conc","","WIS",""],
159"compulsion|xphb":[4,"E","Action","30 ft","VS","1 min","conc","","WIS",""],
160"cone of cold|phb":[5,"V","Action","60 ft cone","VSM","Instant","","cold","CON","8d8"],
161"cone of cold|xphb":[5,"V","Action","60 ft cone","VSM","Instant","","cold","CON","8d8"],
162"confusion|phb":[4,"E","Action","90 ft","VSM","1 min","conc","","WIS",""],
163"confusion|xphb":[4,"E","Action","90 ft","VSM","1 min","conc","","WIS",""],
164"conjure animals|phb":[3,"C","Action","60 ft","VS","1 hr","conc","","",""],
165"conjure animals|xphb":[3,"C","Action","60 ft","VS","10 min","conc","slashing","DEX","3d10"],
166"conjure barrage|phb":[3,"C","Action","60 ft cone","VSM","Instant","","","DEX",""],
167"conjure barrage|xphb":[3,"C","Action","60 ft cone","VSM","Instant","","force","DEX","5d8"],
168"conjure celestial|phb":[7,"C","1 min","90 ft","VS","1 hr","conc","","",""],
169"conjure celestial|xphb":[7,"C","Action","90 ft","VS","10 min","conc","radiant","DEX","6d12"],
170"conjure elemental|phb":[5,"C","1 min","90 ft","VSM","1 hr","conc","","",""],
171"conjure elemental|xphb":[5,"C","Action","60 ft","VS","10 min","conc","lightning,thunder,fire,cold","DEX",""],
172"conjure fey|phb":[6,"C","1 min","90 ft","VS","1 hr","conc","","",""],
173"conjure fey|xphb":[6,"C","Action","60 ft","VS","10 min","conc","psychic","","3d12"],
174"conjure minor elementals|phb":[4,"C","1 min","90 ft","VS","1 hr","conc","","",""],
175"conjure minor elementals|xphb":[4,"C","Action","15 ft emanation","VS","10 min","conc","acid,cold,fire,lightning","","2d8"],
176"conjure volley|phb":[5,"C","Action","150 ft","VSM","Instant","","","DEX",""],
177"conjure volley|xphb":[5,"C","Action","150 ft","VSM","Instant","","force","DEX",""],
178"conjure woodland beings|phb":[4,"C","Action","60 ft","VSM","1 hr","conc","","",""],
179"conjure woodland beings|xphb":[4,"C","Action","10 ft emanation","VS","10 min","conc","force","WIS","5d8"],
180"contact other plane|phb":[5,"D","1 min","Self","V","1 min","ritual","psychic","INT",""],
181"contact other plane|xphb":[5,"D","1 min","Self","V","1 min","ritual","psychic","INT",""],
182"contagion|phb":[5,"N","Action","Touch","VS","7 days","melee","","CON",""],
183"contagion|xphb":[5,"N","Action","Touch","VS","7 days","","necrotic","CON",""],
184"contingency|phb":[6,"V","10 min","Self","VSM","10 days","","","",""],
185"contingency|xphb":[6,"A","10 min","Self","VSM","10 days","","","",""],
186"continual flame|phb":[2,"V","Action","Touch","VSM","Until dispelled","","","",""],
187"continual flame|xphb":[2,"V","Action","Touch","VSM","Until dispelled","","","",""],
188"control flames|xge":[0,"T","Action","60 ft","S","Instant or 1 hr","","","",""],
189"control water|phb":[4,"T","Action","300 ft","VSM","10 min","conc","bludgeoning","STR",""],
190"control water|xphb":[4,"T","Action","300 ft","VSM","10 min","conc","bludgeoning","STR",""],
191"control weather|phb":[8,"T","10 min","5 miles radius","VSM","8 hr","conc","","",""],
192"control weather|xphb":[8,"T","10 min","5 miles sphere","VSM","8 hr","conc","","",""],
193"control winds|xge":[5,"T","Action","300 ft","VS","1 hr","conc","","STR",""],
194"cordon of arrows|phb":[2,"T","Action","5 ft","VSM","8 hr","","piercing","DEX",""],
195"cordon of arrows|xphb":[2,"T","Action","Touch","VSM","8 hr","","piercing","DEX",""],
196"counterspell|phb":[3,"A","Reaction","60 ft","S","Instant","","","",""],
197"counterspell|xphb":[3,"A","Reaction","60 ft","S","Instant","","","CON",""],
198"create bonfire|xge":[0,"C","Action","60 ft","VS","1 min","conc","fire","DEX","1:1d8 5:2d8 11:3d8 17:4d8"],
199"create food and water|phb":[3,"C","Action","30 ft","VS","Instant","","","",""],
200"create food and water|xphb":[3,"C","Action","30 ft","VS","Instant","","","",""],
201"create homunculus|xge":[6,"T","1 hr","Touch","VSM","Instant","","","",""],
202"create or destroy water|phb":[1,"T","Action","30 ft","VSM","Instant","","","",""],
203"create or destroy water|xphb":[1,"T","Action","30 ft","VSM","Instant","","","",""],
204"create undead|phb":[6,"N","1 min","10 ft","VSM","Instant","","","",""],
205"create undead|xphb":[6,"N","1 min","10 ft","VSM","Instant","","","",""],
206"creation|phb":[5,"I","1 min","30 ft","VSM","Special","","","",""],
207"creation|xphb":[5,"I","1 min","30 ft","VSM","Special","","","",""],
208"crown of madness|phb":[2,"E","Action","120 ft","VS","1 min","conc","","WIS",""],
209"crown of madness|xphb":[2,"E","Action","120 ft","VS","1 min","conc","","WIS",""],
210"crown of stars|xge":[7,"V","Action","Self","VS","1 hr","ranged","radiant","",""],
211"crusader s mantle|phb":[3,"V","Action","30 ft radius","V","1 min","conc","radiant","",""],
212"crusader s mantle|xphb":[3,"V","Action","30 ft emanation","V","1 min","conc","radiant","",""],
213"cure wounds|phb":[1,"V","Action","Touch","VS","Instant","heal mod","","","1d8"],
214"cure wounds|xphb":[1,"A","Action","Touch","VS","Instant","heal mod","","","2d8"],
215"dancing lights|phb":[0,"V","Action","120 ft","VSM","1 min","conc","","",""],
216"dancing lights|xphb":[0,"I","Action","120 ft","VSM","1 min","conc","","",""],
217"danse macabre|xge":[5,"N","Action","60 ft","VS","1 hr","conc","","",""],
218"darkness|phb":[2,"V","Action","60 ft","VM","10 min","conc","","",""],
219"darkness|xphb":[2,"V","Action","60 ft","VM","10 min","conc","","",""],
220"darkvision|phb":[2,"T","Action","Touch","VSM","8 hr","","","",""],
221"darkvision|xphb":[2,"T","Action","Touch","VSM","8 hr","","","",""],
222"dawn|xge":[5,"V","Action","60 ft","VSM","1 min","conc","radiant","CON",""],
223"daylight|phb":[3,"V","Action","60 ft","VS","1 hr","","","",""],
224"daylight|xphb":[3,"V","Action","60 ft","VS","1 hr","","","",""],
225"death ward|phb":[4,"A","Action","Touch","VS","8 hr","","","",""],
226"death ward|xphb":[4,"A","Action","Touch","VS","8 hr","","","",""],
227"delayed blast fireball|phb":[7,"V","Action","150 ft","VSM","1 min","conc","fire","DEX","12d6"],
228"delayed blast fireball|xphb":[7,"V","Action","150 ft","VSM","1 min","conc","fire","DEX","12d6"],
229"demiplane|phb":[8,"C","Action","60 ft","S","1 hr","","","",""],
230"demiplane|xphb":[8,"C","Action","60 ft","S","1 hr","","","",""],
231"destructive wave|phb":[5,"V","Action","30 ft radius","V","Instant","","necrotic,radiant,thunder","CON",""],
232"destructive wave|xphb":[5,"V","Action","30 ft emanation","V","Instant","","necrotic,radiant,thunder","CON",""],
233"detect evil and good|phb":[1,"D","Action","Self","VS","10 min","conc","","",""],
234"detect evil and good|xphb":[1,"D","Action","30 ft sphere","VS","10 min","conc","","",""],
235"detect magic|phb":[1,"D","Action","Self","VS","10 min","conc ritual","","",""],
236"detect magic|xphb":[1,"D","Action","30 ft sphere","VS","10 min","conc ritual","","",""],
237"detect poison and disease|phb":[1,"D","Action","Self","VSM","10 min","conc ritual","","",""],
238"detect poison and disease|xphb":[1,"D","Action","30 ft sphere","VSM","10 min","conc ritual","","",""],
239"detect thoughts|phb":[2,"D","Action","Self","VSM","1 min","conc","","WIS",""],
240"detect thoughts|xphb":[2,"D","Action","Self","VSM","1 min","conc","","WIS",""],
241"dimension door|phb":[4,"C","Action","500 ft","V","Instant","","force","",""],
242"dimension door|xphb":[4,"C","Action","500 ft","V","Instant","","force","",""],
243"disguise self|phb":[1,"I","Action","Self","VS","1 hr","","","",""],
244"disguise self|xphb":[1,"I","Action","Self","VS","1 hr","","","",""],
245"disintegrate|phb":[6,"T","Action","60 ft","VSM","Instant","","force","DEX","10d6 + 40"],
246"disintegrate|xphb":[6,"T","Action","60 ft","VSM","Instant","","force","DEX","10d6 + 40"],
247"dispel evil and good|phb":[5,"A","Action","Self","VSM","1 min","conc melee","","CHA",""],
248"dispel evil and good|xphb":[5,"A","Action","Self","VSM","1 min","conc","","CHA",""],
249"dispel magic|phb":[3,"A","Action","120 ft","VS","Instant","","","",""],
250"dispel magic|xphb":[3,"A","Action","120 ft","VS","Instant","","","",""],
251"dissonant whispers|phb":[1,"E","Action","60 ft","V","Instant","","psychic","WIS","3d6"],
252"dissonant whispers|xphb":[1,"E","Action","60 ft","V","Instant","","psychic","WIS","3d6"],
253"divination|phb":[4,"D","Action","Self","VSM","Instant","ritual","","",""],
254"divination|xphb":[4,"D","Action","Self","VSM","Instant","ritual","","",""],
255"divine favor|phb":[1,"V","Bonus Action","Self","VS","1 min","conc","radiant","",""],
256"divine favor|xphb":[1,"T","Bonus Action","Self","VS","1 min","","radiant","",""],
257"divine smite|xphb":[1,"V","Bonus Action","Self","V","Instant","","radiant","","2d8"],
258"divine word|phb":[7,"V","Bonus Action","30 ft","V","Instant","","","CHA",""],
259"divine word|xphb":[7,"V","Bonus Action","30 ft","V","Instant","","","CHA",""],
260"dominate beast|phb":[4,"E","Action","60 ft","VS","1 min","conc","","WIS",""],
261"dominate beast|xphb":[4,"E","Action","60 ft","VS","1 min","conc","","WIS",""],
262"dominate monster|phb":[8,"E","Action","60 ft","VS","1 hr","conc","","WIS",""],
263"dominate monster|xphb":[8,"E","Action","60 ft","VS","1 hr","conc","","WIS",""],
264"dominate person|phb":[5,"E","Action","60 ft","VS","1 min","conc","","WIS",""],
265"dominate person|xphb":[5,"E","Action","60 ft","VS","1 min","conc","","WIS",""],
266"dragon s breath|xge":[2,"T","Bonus Action","Touch","VSM","1 min","conc","acid,cold,fire,lightning,poison","DEX","3d6"],
267"dragon s breath|xphb":[2,"T","Bonus Action","Touch","VSM","1 min","conc","acid,cold,fire,lightning,poison","DEX","3d6"],
268"drawmij s instant summons|phb":[6,"C","1 min","Touch","VSM","Until dispelled","ritual","","",""],
269"drawmij s instant summons|xphb":[6,"C","1 min","Touch","VSM","Until dispelled","ritual","","",""],
270"dream of the blue veil|tce":[7,"C","10 min","20 ft","VSM","6 hr","","","",""],
271"dream|phb":[5,"I","1 min","Special","VSM","8 hr","","psychic","WIS",""],
272"dream|xphb":[5,"I","1 min","Self","VSM","8 hr","","psychic","WIS",""],
273"druid grove|xge":[6,"A","10 min","Touch","VSM","24 hr","","","",""],
274"druidcraft|phb":[0,"T","Action","30 ft","VS","Instant","","","",""],
275"druidcraft|xphb":[0,"T","Action","30 ft","VS","Instant","","","",""],
276"dust devil|xge":[2,"C","Action","60 ft","VSM","1 min","conc","bludgeoning","STR","1d8"],
277"earth tremor|xge":[1,"V","Action","10 ft","VS","Instant","","bludgeoning","DEX","1d6"],
278"earthbind|xge":[2,"T","Action","300 ft","V","1 min","conc","","STR",""],
279"earthquake|phb":[8,"V","Action","500 ft","VSM","1 min","conc","bludgeoning","CON/DEX",""],
280"earthquake|xphb":[8,"T","Action","500 ft","VSM","1 min","conc","bludgeoning","CON/DEX",""],
281"eldritch blast|phb":[0,"V","Action","120 ft","VS","Instant","ranged","force","",""],
282"eldritch blast|xphb":[0,"V","Action","120 ft","VS","Instant","ranged","force","",""],
283"elemental bane|xge":[4,"T","Action","90 ft","VS","1 min","conc","acid,cold,fire,lightning,thunder","CON",""],
284"elemental weapon|phb":[3,"T","Action","Touch","VS","1 hr","conc","acid,cold,fire,lightning,thunder","","1d4"],
285"elemental weapon|xphb":[3,"T","Action","Touch","VS","1 hr","conc","acid,cold,fire,lightning,thunder","",""],
286"elementalism|xphb":[0,"T","Action","30 ft","VS","Instant","","","",""],
287"enemies abound|xge":[3,"E","Action","120 ft","VS","1 min","conc","","INT",""],
288"enervation|xge":[5,"N","Action","60 ft","VS","1 min","conc","necrotic","DEX","4d8;2d8"],
289"enhance ability|phb":[2,"T","Action","Touch","VSM","1 hr","conc","","",""],
290"enhance ability|xphb":[2,"T","Action","Touch","VSM","1 hr","conc","","",""],
291"enlarge reduce|phb":[2,"T","Action","30 ft","VSM","1 min","conc","","CON",""],
292"enlarge reduce|xphb":[2,"T","Action","30 ft","VSM","1 min","conc","","CON",""],
293"ensnaring strike|phb":[1,"C","Bonus Action","Self","V","1 min","conc","piercing","STR","1d6"],
294"ensnaring strike|xphb":[1,"C","Bonus Action","Self","V","1 min","conc","piercing","STR","1d6"],
295"entangle|phb":[1,"C","Action","90 ft","VS","1 min","conc","","STR",""],
296"entangle|xphb":[1,"C","Action","90 ft","VS","1 min","conc","","STR",""],
297"enthrall|phb":[2,"E","Action","60 ft","VS","1 min","","","WIS",""],
298"enthrall|xphb":[2,"E","Action","60 ft","VS","1 min","conc","","WIS",""],
299"erupting earth|xge":[3,"T","Action","120 ft","VSM","Instant","","bludgeoning","DEX","3d12"],
300"etherealness|phb":[7,"T","Action","Self","VS","8 hr","","force","",""],
301"etherealness|xphb":[7,"C","Action","Self","VS","8 hr","","force","",""],
302"evard s black tentacles|phb":[4,"C","Action","90 ft","VSM","1 min","conc","bludgeoning","DEX",""],
303"evard s black tentacles|xphb":[4,"C","Action","90 ft","VSM","1 min","conc","bludgeoning","STR",""],
304"expeditious retreat|phb":[1,"T","Bonus Action","Self","VS","10 min","conc","","",""],
305"expeditious retreat|xphb":[1,"T","Bonus Action","Self","VS","10 min","conc","","",""],
306"eyebite|phb":[6,"N","Action","Self","VS","1 min","conc","","WIS",""],
307"eyebite|xphb":[6,"N","Action","Self","VS","1 min","conc","","WIS",""],
308"fabricate|phb":[4,"T","10 min","120 ft","VS","Instant","","","",""],
309"fabricate|xphb":[4,"T","10 min","120 ft","VS","Instant","","","",""],
310"faerie fire|phb":[1,"V","Action","60 ft","V","1 min","conc","","DEX",""],
311"faerie fire|xphb":[1,"V","Action","60 ft","V","1 min","conc","","DEX",""],
312"false life|phb":[1,"N","Action","Self","VSM","1 hr","","","",""],
313"false life|xphb":[1,"N","Action","Self","VSM","Instant","","","",""],
314"far step|xge":[5,"C","Bonus Action","Self","V","1 min","conc","","",""],
315"fear|phb":[3,"I","Action","30 ft cone","VSM","1 min","conc","","WIS",""],
316"fear|xphb":[3,"I","Action","30 ft cone","VSM","1 min","conc","","WIS",""],
317"feather fall|phb":[1,"T","Reaction","60 ft","VM","1 min","","","",""],
318"feather fall|xphb":[1,"T","Reaction","60 ft","VM","1 min","","","",""],
319"feeblemind|phb":[8,"E","Action","150 ft","VSM","Instant","","psychic","INT",""],
320"feign death|phb":[3,"N","Action","Touch","VSM","1 hr","ritual","","",""],
321"feign death|xphb":[3,"N","Action","Touch","VSM","1 hr","ritual","","",""],
322"find familiar|phb":[1,"C","1 hr","10 ft","VSM","Instant","ritual","","",""],
323"find familiar|xphb":[1,"C","1 hr","10 ft","VSM","Instant","ritual","","",""],
324"find greater steed|xge":[4,"C","10 min","30 ft","VS","Instant","","","",""],
325"find steed|phb":[2,"C","10 min","30 ft","VS","Instant","","","",""],
326"find steed|xphb":[2,"C","Action","30 ft","VS","Instant","","","",""],
327"find the path|phb":[6,"D","1 min","Self","VSM","1 day","conc","","",""],
328"find the path|xphb":[6,"D","1 min","Self","VSM","1 day","conc","","",""],
329"find traps|phb":[2,"D","Action","120 ft","VS","Instant","","","",""],
330"find traps|xphb":[2,"D","Action","120 ft","VS","Instant","","","",""],
331"finger of death|phb":[7,"N","Action","60 ft","VS","Instant","","necrotic","CON",""],
332"finger of death|xphb":[7,"N","Action","60 ft","VS","Instant","","necrotic","CON",""],
333"fire bolt|phb":[0,"V","Action","120 ft","VS","Instant","ranged","fire","","1:1d10 5:2d10 11:3d10 17:4d10"],
334"fire bolt|xphb":[0,"V","Action","120 ft","VS","Instant","ranged","fire","","1:1d10 5:2d10 11:3d10 17:4d10"],
335"fire shield|phb":[4,"V","Action","Self","VSM","10 min","","cold,fire","",""],
336"fire shield|xphb":[4,"V","Action","Self","VSM","10 min","","cold,fire","",""],
337"fire storm|phb":[7,"V","Action","150 ft","VS","Instant","","fire","DEX",""],
338"fire storm|xphb":[7,"V","Action","150 ft","VS","Instant","","fire","DEX",""],
339"fireball|phb":[3,"V","Action","150 ft","VSM","Instant","","fire","DEX","8d6"],
340"fireball|xphb":[3,"V","Action","150 ft","VSM","Instant","","fire","DEX","8d6"],
341"flame arrows|xge":[3,"T","Action","Touch","VS","1 hr","conc","fire","",""],
342"flame blade|phb":[2,"V","Bonus Action","Self","VSM","10 min","conc melee","fire","","3d6"],
343"flame blade|xphb":[2,"V","Bonus Action","Self","VSM","10 min","conc melee","fire","","3d6"],
344"flame strike|phb":[5,"V","Action","60 ft","VSM","Instant","","fire,radiant","DEX","4d6"],
345"flame strike|xphb":[5,"V","Action","60 ft","VSM","Instant","","fire,radiant","DEX","5d6"],
346"flaming sphere|phb":[2,"C","Action","60 ft","VSM","1 min","conc","fire","DEX","2d6"],
347"flaming sphere|xphb":[2,"C","Action","60 ft","VSM","1 min","conc","fire","DEX","2d6"],
348"flesh to stone|phb":[6,"T","Action","60 ft","VSM","1 min","conc","","CON",""],
349"flesh to stone|xphb":[6,"T","Action","60 ft","VSM","1 min","conc","","CON",""],
350"fly|phb":[3,"T","Action","Touch","VSM","10 min","conc","","",""],
351"fly|xphb":[3,"T","Action","Touch","VSM","10 min","conc","","",""],
352"fog cloud|phb":[1,"C","Action","120 ft","VS","1 hr","conc","","",""],
353"fog cloud|xphb":[1,"C","Action","120 ft","VS","1 hr","conc","","",""],
354"forbiddance|phb":[6,"A","10 min","Touch","VSM","1 day","ritual","necrotic,radiant","",""],
355"forbiddance|xphb":[6,"A","10 min","Touch","VSM","1 day","ritual","necrotic,radiant","",""],
356"forcecage|phb":[7,"V","Action","100 ft","VSM","1 hr","","","CHA",""],
357"forcecage|xphb":[7,"V","Action","100 ft","VSM","1 hr","conc","","CHA",""],
358"foresight|phb":[9,"D","1 min","Touch","VSM","8 hr","","","",""],
359"foresight|xphb":[9,"D","1 min","Touch","VSM","8 hr","","","",""],
360"fount of moonlight|xphb":[4,"V","Action","Self","VS","10 min","conc","radiant","CON",""],
361"freedom of movement|phb":[4,"A","Action","Touch","VSM","1 hr","","","",""],
362"freedom of movement|xphb":[4,"A","Action","Touch","VSM","1 hr","","","",""],
363"friends|phb":[0,"E","Action","Self","SM","1 min","conc","","",""],
364"friends|xphb":[0,"E","Action","10 ft","SM","1 min","conc","","WIS",""],
365"frostbite|xge":[0,"V","Action","60 ft","VS","Instant","","cold","CON","1:1d6 5:2d6 11:3d6 17:4d6"],
366"gaseous form|phb":[3,"T","Action","Touch","VSM","1 hr","conc","","",""],
367"gaseous form|xphb":[3,"T","Action","Touch","VSM","1 hr","conc","","",""],
368"gate|phb":[9,"C","Action","60 ft","VSM","1 min","conc","","",""],
369"gate|xphb":[9,"C","Action","60 ft","VSM","1 min","conc","","",""],
370"geas|phb":[5,"E","1 min","60 ft","V","30 days","","psychic","WIS",""],
371"geas|xphb":[5,"E","1 min","60 ft","V","30 days","","psychic","WIS",""],
372"gentle repose|phb":[2,"N","Action","Touch","VSM","10 days","ritual","","",""],
373"gentle repose|xphb":[2,"N","Action","Touch","VSM","10 days","ritual","","",""],
374"giant insect|phb":[4,"T","Action","30 ft","VS","10 min","conc","","",""],
375"giant insect|xphb":[4,"C","Action","60 ft","VS","10 min","conc","","",""],
376"glibness|phb":[8,"T","Action","Self","V","1 hr","","","",""],
377"glibness|xphb":[8,"E","Action","Self","V","1 hr","","","",""],
378"globe of invulnerability|phb":[6,"A","Action","10 ft radius","VSM","1 min","conc","","",""],
379"globe of invulnerability|xphb":[6,"A","Action","10 ft emanation","VSM","1 min","conc","","",""],
380"glyph of warding|phb":[3,"A","1 hr","Touch","VSM","Until dispelled or triggered","","acid,cold,fire,lightning,thunder","DEX","5d8"],
381"glyph of warding|xphb":[3,"A","1 hr","Touch","VSM","Until dispelled or triggered","","acid,cold,fire,lightning,thunder","DEX","5d8"],
382"goodberry|phb":[1,"T","Action","Touch","VSM","Instant","heal","","",""],
383"goodberry|xphb":[1,"C","Action","Touch","VSM","24 hr","heal","","",""],
384"grasping vine|phb":[4,"C","Bonus Action","30 ft","VS","1 min","conc","","DEX",""],
385"grasping vine|xphb":[4,"C","Bonus Action","60 ft","VS","1 min","conc melee","bludgeoning","",""],
386"grease|phb":[1,"C","Action","60 ft","VSM","1 min","","","DEX",""],
387"grease|xphb":[1,"C","Action","60 ft","VSM","1 min","","","DEX",""],
388"greater invisibility|phb":[4,"I","Action","Touch","VS","1 min","conc","","",""],
389"greater invisibility|xphb":[4,"I","Action","Touch","VS","1 min","conc","","",""],
390"greater restoration|phb":[5,"A","Action","Touch","VSM","Instant","","","",""],
391"greater restoration|xphb":[5,"A","Action","Touch","VSM","Instant","","","",""],
392"green flame blade|tce":[0,"V","Action","5 ft radius","SM","Instant","melee","fire","","1:{{spellcasting_mod}}/ 5:1d8 + {{spellcasting_mod}}/1d8 11:2d8 + {{spellcasting_mod}}/2d8 17:3d8 + {{spellcasting_mod}}/3d8"],
393"guardian of faith|phb":[4,"C","Action","30 ft","V","8 hr","","radiant","DEX",""],
394"guardian of faith|xphb":[4,"C","Action","30 ft","V","8 hr","","radiant","DEX",""],
395"guardian of nature|xge":[4,"T","Bonus Action","Self","V","1 min","conc","force","",""],
396"guards and wards|phb":[6,"A","10 min","Touch","VSM","24 hr","","","",""],
397"guards and wards|xphb":[6,"A","1 hr","Touch","VSM","24 hr","","","",""],
398"guidance|phb":[0,"D","Action","Touch","VS","1 min","conc","","",""],
399"guidance|xphb":[0,"D","Action","Touch","VS","1 min","conc","","",""],
400"guiding bolt|phb":[1,"V","Action","120 ft","VS","1 round","ranged","radiant","","4d6"],
401"guiding bolt|xphb":[1,"V","Action","120 ft","VS","1 round","ranged","radiant","","4d6"],
402"gust of wind|phb":[2,"V","Action","60 ft line","VSM","1 min","conc","","STR",""],
403"gust of wind|xphb":[2,"V","Action","60 ft line","VSM","1 min","conc","","STR",""],
404"gust|xge":[0,"T","Action","30 ft","VS","Instant","","","STR",""],
405"hail of thorns|phb":[1,"C","Bonus Action","Self","V","1 min","conc","piercing","DEX","1d10"],
406"hail of thorns|xphb":[1,"C","Bonus Action","Self","V","Instant","","piercing","DEX","1d10"],
407"hallow|phb":[5,"V","24 hr","Touch","VSM","Until dispelled","","","CHA",""],
408"hallow|xphb":[5,"A","24 hr","Touch","VSM","Until dispelled","","","",""],
409"hallucinatory terrain|phb":[4,"I","10 min","300 ft","VSM","24 hr","","","",""],
410"hallucinatory terrain|xphb":[4,"I","10 min","300 ft","VSM","24 hr","","","",""],
411"harm|phb":[6,"N","Action","60 ft","VS","Instant","","necrotic","CON",""],
412"harm|xphb":[6,"N","Action","60 ft","VS","Instant","","necrotic","CON",""],
413"haste|phb":[3,"T","Action","30 ft","VSM","1 min","conc","","",""],
414"haste|xphb":[3,"T","Action","30 ft","VSM","1 min","conc","","",""],
415"healing spirit|xge":[2,"C","Bonus Action","60 ft","VS","1 min","conc heal mod","","","1d6"],
416"healing word|phb":[1,"V","Bonus Action","60 ft","V","Instant","heal mod","","","1d4"],
417"healing word|xphb":[1,"A","Bonus Action","60 ft","V","Instant","heal mod","","","2d4"],
418"heal|phb":[6,"V","Action","60 ft","VS","Instant","heal","","",""],
419"heal|xphb":[6,"A","Action","60 ft","VS","Instant","heal","","","70"],
420"heat metal|phb":[2,"T","Action","60 ft","VSM","1 min","conc","fire","CON","2d8"],
421"heat metal|xphb":[2,"T","Action","60 ft","VSM","1 min","conc","fire","CON","2d8"],
422"hellish rebuke|phb":[1,"V","Reaction","60 ft","VS","Instant","","fire","DEX","2d10"],
423"hellish rebuke|xphb":[1,"V","Reaction","60 ft","VS","Instant","","fire","DEX","2d10"],
424"heroes feast|phb":[6,"C","10 min","30 ft","VSM","Instant","heal","","",""],
425"heroes feast|xphb":[6,"C","10 min","10 ft cube","VSM","Instant","heal","","",""],
426"heroism|phb":[1,"E","Action","Touch","VS","1 min","conc","","",""],
427"heroism|xphb":[1,"E","Action","Touch","VS","1 min","conc","","",""],
428"hex|phb":[1,"E","Bonus Action","90 ft","VSM","1 hr","conc","necrotic","",""],
429"hex|xphb":[1,"E","Bonus Action","90 ft","VSM","1 hr","conc","necrotic","",""],
430"hold monster|phb":[5,"E","Action","90 ft","VSM","1 min","conc","","WIS",""],
431"hold monster|xphb":[5,"E","Action","90 ft","VSM","1 min","conc","","WIS",""],
432"hold person|phb":[2,"E","Action","60 ft","VSM","1 min","conc","","WIS",""],
433"hold person|xphb":[2,"E","Action","60 ft","VSM","1 min","conc","","WIS",""],
434"holy aura|phb":[8,"A","Action","Self","VSM","1 min","conc","","CON",""],
435"holy aura|xphb":[8,"A","Action","30 ft emanation","VSM","1 min","conc","","CON",""],
436"holy weapon|xge":[5,"V","Bonus Action","Touch","VS","1 hr","conc","radiant","CON",""],
437"homunculus servant|efa":[2,"C","1 hr","10 ft","VSM","Instant","ritual","","",""],
438"hunger of hadar|phb":[3,"C","Action","150 ft","VSM","1 min","conc","acid,cold","DEX",""],
439"hunger of hadar|xphb":[3,"C","Action","150 ft","VSM","1 min","conc","acid,cold","DEX","2d6"],
440"hunter s mark|phb":[1,"D","Bonus Action","90 ft","V","1 hr","conc","","",""],
441"hunter s mark|xphb":[1,"D","Bonus Action","90 ft","V","1 hr","conc","force","",""],
442"hypnotic pattern|phb":[3,"I","Action","120 ft","SM","1 min","conc","","WIS",""],
443"hypnotic pattern|xphb":[3,"I","Action","120 ft","SM","1 min","conc","","WIS",""],
444"ice knife|xge":[1,"C","Action","60 ft","SM","Instant","ranged","cold,piercing","DEX",""],
445"ice knife|xphb":[1,"C","Action","60 ft","SM","Instant","ranged","cold,piercing","DEX",""],
446"ice storm|phb":[4,"V","Action","300 ft","VSM","Instant","","bludgeoning,cold","DEX",""],
447"ice storm|xphb":[4,"V","Action","300 ft","VSM","Instant","","bludgeoning,cold","DEX",""],
448"identify|phb":[1,"D","1 min","Touch","VSM","Instant","ritual","","",""],
449"identify|xphb":[1,"D","1 min","Touch","VSM","Instant","ritual","","",""],
450"illusory dragon|xge":[8,"I","Action","120 ft","S","1 min","conc","acid,cold,fire,lightning,necrotic,poison","WIS/INT",""],
451"illusory script|phb":[1,"I","1 min","Touch","SM","10 days","ritual","","",""],
452"illusory script|xphb":[1,"I","1 min","Touch","SM","10 days","ritual","","",""],
453"immolation|xge":[5,"V","Action","90 ft","V","1 min","conc","fire","DEX",""],
454"imprisonment|phb":[9,"A","1 min","30 ft","VSM","Until dispelled","","","WIS",""],
455"imprisonment|xphb":[9,"A","1 min","30 ft","VSM","Until dispelled","","","WIS",""],
456"incendiary cloud|phb":[8,"C","Action","150 ft","VS","1 min","conc","fire","DEX",""],
457"incendiary cloud|xphb":[8,"C","Action","150 ft","VS","1 min","conc","fire","DEX",""],
458"infernal calling|xge":[5,"C","1 min","90 ft","VSM","1 hr","conc","","",""],
459"infestation|xge":[0,"C","Action","30 ft","VSM","Instant","","poison","CON","1:1d6 5:2d6 11:3d6 17:4d6"],
460"inflict wounds|phb":[1,"N","Action","Touch","VS","Instant","melee","necrotic","","3d10"],
461"inflict wounds|xphb":[1,"N","Action","Touch","VS","Instant","","necrotic","CON","2d10"],
462"insect plague|phb":[5,"C","Action","300 ft","VSM","10 min","conc","piercing","CON","4d10"],
463"insect plague|xphb":[5,"C","Action","300 ft","VSM","10 min","conc","piercing","CON","4d10"],
464"intellect fortress|tce":[3,"A","Action","30 ft","V","1 hr","conc","","",""],
465"investiture of flame|xge":[6,"T","Action","Self","VS","10 min","conc","fire","DEX",""],
466"investiture of ice|xge":[6,"T","Action","Self","VS","10 min","conc","cold","CON",""],
467"investiture of stone|xge":[6,"T","Action","Self","VS","10 min","conc","","DEX",""],
468"investiture of wind|xge":[6,"T","Action","Self","VS","10 min","conc","bludgeoning","CON",""],
469"invisibility|phb":[2,"I","Action","Touch","VSM","1 hr","conc","","",""],
470"invisibility|xphb":[2,"I","Action","Touch","VSM","1 hr","conc","","",""],
471"invulnerability|xge":[9,"A","Action","Self","VSM","10 min","conc","","",""],
472"jallarzi s storm of radiance|xphb":[5,"V","Action","120 ft","VSM","1 min","conc","radiant,thunder","CON","2d10"],
473"jump|phb":[1,"T","Action","Touch","VSM","1 min","","","",""],
474"jump|xphb":[1,"T","Bonus Action","Touch","VSM","1 min","","","",""],
475"knock|phb":[2,"T","Action","60 ft","V","Instant","","","",""],
476"knock|xphb":[2,"T","Action","60 ft","V","Instant","","","",""],
477"legend lore|phb":[5,"D","10 min","Self","VSM","Instant","","","",""],
478"legend lore|xphb":[5,"D","10 min","Self","VSM","Instant","","","",""],
479"leomund s secret chest|phb":[4,"C","Action","Touch","VSM","Instant","","","",""],
480"leomund s secret chest|xphb":[4,"C","Action","Touch","VSM","Until dispelled","","","",""],
481"leomund s tiny hut|phb":[3,"V","1 min","10 ft hemisphere","VSM","8 hr","ritual","","",""],
482"leomund s tiny hut|xphb":[3,"V","1 min","10 ft emanation","VSM","8 hr","ritual","","",""],
483"lesser restoration|phb":[2,"A","Action","Touch","VS","Instant","","","",""],
484"lesser restoration|xphb":[2,"A","Bonus Action","Touch","VS","Instant","","","",""],
485"levitate|phb":[2,"T","Action","60 ft","VSM","10 min","conc","","CON",""],
486"levitate|xphb":[2,"T","Action","60 ft","VSM","10 min","conc","","CON",""],
487"life transference|xge":[3,"N","Action","30 ft","VS","Instant","","necrotic","","4d8"],
488"lightning arrow|phb":[3,"T","Bonus Action","Self","VS","1 min","conc","lightning","DEX","4d8;2d8"],
489"lightning arrow|xphb":[3,"T","Bonus Action","Self","VS","Instant","","lightning","DEX","4d8;2d8"],
490"lightning bolt|phb":[3,"V","Action","100 ft line","VSM","Instant","","lightning","DEX","8d6"],
491"lightning bolt|xphb":[3,"V","Action","100 ft line","VSM","Instant","","lightning","DEX","8d6"],
492"lightning lure|tce":[0,"V","Action","15 ft radius","V","Instant","","lightning","STR","1:1d8 5:2d8 11:3d8 17:4d8"],
493"light|phb":[0,"V","Action","Touch","VM","1 hr","","","DEX",""],
494"light|xphb":[0,"V","Action","Touch","VM","1 hr","","","",""],
495"locate animals or plants|phb":[2,"D","Action","Self","VSM","Instant","ritual","","",""],
496"locate animals or plants|xphb":[2,"D","Action","Self","VSM","Instant","ritual","","",""],
497"locate creature|phb":[4,"D","Action","Self","VSM","1 hr","conc","","",""],
498"locate creature|xphb":[4,"D","Action","Self","VSM","1 hr","conc","","",""],
499"locate object|phb":[2,"D","Action","Self","VSM","10 min","conc","","",""],
500"locate object|xphb":[2,"D","Action","Self","VSM","10 min","conc","","",""],
501"longstrider|phb":[1,"T","Action","Touch","VSM","1 hr","","","",""],
502"longstrider|xphb":[1,"T","Action","Touch","VSM","1 hr","","","",""],
503"maddening darkness|xge":[8,"V","Action","150 ft","VM","10 min","conc","psychic","WIS",""],
504"maelstrom|xge":[5,"V","Action","120 ft","VSM","1 min","conc","bludgeoning","STR",""],
505"mage armor|phb":[1,"A","Action","Touch","VSM","8 hr","","","",""],
506"mage armor|xphb":[1,"A","Action","Touch","VSM","8 hr","","","",""],
507"mage hand|phb":[0,"C","Action","30 ft","VS","1 min","","","",""],
508"mage hand|xphb":[0,"C","Action","30 ft","VS","1 min","","","",""],
509"magic circle|phb":[3,"A","1 min","10 ft","VSM","1 hr","","","CHA",""],
510"magic circle|xphb":[3,"A","1 min","10 ft","VSM","1 hr","","","CHA",""],
511"magic jar|phb":[6,"N","1 min","Self","VSM","Until dispelled","","","CHA",""],
512"magic jar|xphb":[6,"N","1 min","Self","VSM","Until dispelled","","","CHA",""],
513"magic missile|phb":[1,"V","Action","120 ft","VS","Instant","","force","",""],
514"magic missile|xphb":[1,"V","Action","120 ft","VS","Instant","","force","",""],
515"magic mouth|phb":[2,"I","1 min","30 ft","VSM","Until dispelled","ritual","","",""],
516"magic mouth|xphb":[2,"I","1 min","30 ft","VSM","Until dispelled","ritual","","",""],
517"magic stone|xge":[0,"T","Bonus Action","Touch","VS","1 min","ranged","bludgeoning","",""],
518"magic weapon|phb":[2,"T","Bonus Action","Touch","VS","1 hr","conc","","",""],
519"magic weapon|xphb":[2,"T","Bonus Action","Touch","VS","1 hr","","","",""],
520"major image|phb":[3,"I","Action","120 ft","VSM","10 min","conc","","",""],
521"major image|xphb":[3,"I","Action","120 ft","VSM","10 min","conc","","",""],
522"mass cure wounds|phb":[5,"V","Action","60 ft","VS","Instant","heal mod","","","3d8"],
523"mass cure wounds|xphb":[5,"A","Action","60 ft","VS","Instant","heal mod","","","5d8"],
524"mass healing word|phb":[3,"V","Bonus Action","60 ft","V","Instant","heal mod","","","1d4"],
525"mass healing word|xphb":[3,"A","Bonus Action","60 ft","V","Instant","heal mod","","","2d4"],
526"mass heal|phb":[9,"V","Action","60 ft","VS","Instant","heal","","",""],
527"mass heal|xphb":[9,"A","Action","60 ft","VS","Instant","heal","","",""],
528"mass polymorph|xge":[9,"T","Action","120 ft","VSM","1 hr","conc","","WIS",""],
529"mass suggestion|phb":[6,"E","Action","60 ft","VM","24 hr","","","WIS",""],
530"mass suggestion|xphb":[6,"E","Action","60 ft","VM","24 hr","","","WIS",""],
531"maximilian s earthen grasp|xge":[2,"T","Action","30 ft","VSM","1 min","conc","bludgeoning","STR",""],
532"maze|phb":[8,"C","Action","60 ft","VS","10 min","conc","","",""],
533"maze|xphb":[8,"C","Action","60 ft","VS","10 min","conc","","",""],
534"meld into stone|phb":[3,"T","Action","Touch","VS","8 hr","ritual","bludgeoning","",""],
535"meld into stone|xphb":[3,"T","Action","Touch","VS","8 hr","ritual","force","",""],
536"melf s acid arrow|phb":[2,"V","Action","90 ft","VSM","Instant","ranged","acid","","4d4;2d4"],
537"melf s acid arrow|xphb":[2,"V","Action","90 ft","VSM","Instant","ranged","acid","","4d4;2d4"],
538"melf s minute meteors|xge":[3,"V","Action","Self","VSM","10 min","conc","fire","DEX",""],
539"mending|phb":[0,"T","1 min","Touch","VSM","Instant","","","",""],
540"mending|xphb":[0,"T","1 min","Touch","VSM","Instant","","","",""],
541"mental prison|xge":[6,"I","Action","60 ft","S","1 min","conc","psychic","INT",""],
542"message|phb":[0,"T","Action","120 ft","VSM","1 round","","","",""],
543"message|xphb":[0,"T","Action","120 ft","SM","1 round","","","",""],
544"meteor swarm|phb":[9,"V","Action","1 mile","VS","Instant","","bludgeoning,fire","DEX",""],
545"meteor swarm|xphb":[9,"V","Action","1 mile","VS","Instant","","bludgeoning,fire","DEX",""],
546"mighty fortress|xge":[8,"C","1 min","1 mile","VSM","Instant","","","",""],
547"mind blank|phb":[8,"A","Action","Touch","VS","24 hr","","","",""],
548"mind blank|xphb":[8,"A","Action","Touch","VS","24 hr","","","",""],
549"mind sliver|tce":[0,"E","Action","60 ft","V","1 round","","psychic","INT","1:1d6 5:2d6 11:3d6 17:4d6"],
550"mind sliver|xphb":[0,"E","Action","60 ft","V","Instant","","psychic","INT","1:1d6 5:2d6 11:3d6 17:4d6"],
551"mind spike|xge":[2,"D","Action","60 ft","S","1 hr","conc","psychic","WIS","3d8"],
552"mind spike|xphb":[2,"D","Action","120 ft","S","1 hr","conc","psychic","WIS","3d8"],
553"minor illusion|phb":[0,"I","Action","30 ft","SM","1 min","","","",""],
554"minor illusion|xphb":[0,"I","Action","30 ft","SM","1 min","","","",""],
555"mirage arcane|phb":[7,"I","10 min","Sight","VS","10 days","","","",""],
556"mirage arcane|xphb":[7,"I","10 min","Sight","VS","10 days","","","",""],
557"mirror image|phb":[2,"I","Action","Self","VS","1 min","","","",""],
558"mirror image|xphb":[2,"I","Action","Self","VS","1 min","","","",""],
559"mislead|phb":[5,"I","Action","Self","S","1 hr","conc","","",""],
560"mislead|xphb":[5,"I","Action","Self","S","1 hr","conc","","",""],
561"misty step|phb":[2,"C","Bonus Action","Self","V","Instant","","","",""],
562"misty step|xphb":[2,"C","Bonus Action","Self","V","Instant","","","",""],
563"modify memory|phb":[5,"E","Action","30 ft","VS","1 min","conc","","WIS",""],
564"modify memory|xphb":[5,"E","Action","30 ft","VS","1 min","conc","","WIS",""],
565"mold earth|xge":[0,"T","Action","30 ft","S","Instant or 1 hr","","","",""],
566"moonbeam|phb":[2,"V","Action","120 ft","VSM","1 min","conc","radiant","CON","2d10"],
567"moonbeam|xphb":[2,"V","Action","120 ft","VSM","1 min","conc","radiant","CON","2d10"],
568"mordenkainen s faithful hound|phb":[4,"C","Action","30 ft","VSM","8 hr","","piercing","",""],
569"mordenkainen s faithful hound|xphb":[4,"C","Action","30 ft","VSM","8 hr","","force","DEX",""],
570"mordenkainen s magnificent mansion|phb":[7,"C","1 min","300 ft","VSM","24 hr","","","",""],
571"mordenkainen s magnificent mansion|xphb":[7,"C","1 min","300 ft","VSM","24 hr","","","",""],
572"mordenkainen s private sanctum|phb":[4,"A","10 min","120 ft","VSM","24 hr","","","",""],
573"mordenkainen s private sanctum|xphb":[4,"A","10 min","120 ft","VSM","24 hr","","","",""],
574"mordenkainen s sword|phb":[7,"V","Action","60 ft","VSM","1 min","conc melee","force","",""],
575"mordenkainen s sword|xphb":[7,"V","Action","90 ft","VSM","1 min","conc melee","force","",""],
576"move earth|phb":[6,"T","Action","120 ft","VSM","2 hr","conc","","",""],
577"move earth|xphb":[6,"T","Action","120 ft","VSM","2 hr","conc","","",""],
578"negative energy flood|xge":[5,"N","Action","60 ft","VM","Instant","","necrotic","CON",""],
579"nondetection|phb":[3,"A","Action","Touch","VSM","8 hr","","","",""],
580"nondetection|xphb":[3,"A","Action","Touch","VSM","8 hr","","","",""],
581"nystul s magic aura|phb":[2,"I","Action","Touch","VSM","24 hr","","","",""],
582"nystul s magic aura|xphb":[2,"I","Action","Touch","VSM","24 hr","","","",""],
583"otiluke s freezing sphere|phb":[6,"V","Action","300 ft","VSM","Instant","","cold","CON","10d6"],
584"otiluke s freezing sphere|xphb":[6,"V","Action","300 ft","VSM","Instant","","cold","CON","10d6"],
585"otiluke s resilient sphere|phb":[4,"V","Action","30 ft","VSM","1 min","conc","","DEX",""],
586"otiluke s resilient sphere|xphb":[4,"A","Action","30 ft","VSM","1 min","conc","","DEX",""],
587"otto s irresistible dance|phb":[6,"E","Action","30 ft","V","1 min","conc","","WIS",""],
588"otto s irresistible dance|xphb":[6,"E","Action","30 ft","V","1 min","conc","","WIS",""],
589"pass without trace|phb":[2,"A","Action","Self","VSM","1 hr","conc","","",""],
590"pass without trace|xphb":[2,"A","Action","30 ft emanation","VSM","1 hr","conc","","",""],
591"passwall|phb":[5,"T","Action","30 ft","VSM","1 hr","","","",""],
592"passwall|xphb":[5,"T","Action","30 ft","VSM","1 hr","","","",""],
593"phantasmal force|phb":[2,"I","Action","60 ft","VSM","1 min","conc","psychic","INT",""],
594"phantasmal force|xphb":[2,"I","Action","60 ft","VSM","1 min","conc","psychic","INT",""],
595"phantasmal killer|phb":[4,"I","Action","120 ft","VS","1 min","conc","psychic","WIS","4d10"],
596"phantasmal killer|xphb":[4,"I","Action","120 ft","VS","1 min","conc","psychic","WIS","4d10"],
597"phantom steed|phb":[3,"I","1 min","30 ft","VS","1 hr","ritual","","",""],
598"phantom steed|xphb":[3,"I","1 min","30 ft","VS","1 hr","ritual","","",""],
599"planar ally|phb":[6,"C","10 min","60 ft","VS","Instant","","","",""],
600"planar ally|xphb":[6,"C","10 min","60 ft","VS","Instant","","","",""],
601"planar binding|phb":[5,"A","1 hr","60 ft","VSM","24 hr","","","CHA",""],
602"planar binding|xphb":[5,"A","1 hr","60 ft","VSM","24 hr","","","CHA",""],
603"plane shift|phb":[7,"C","Action","Touch","VSM","Instant","melee","","CHA",""],
604"plane shift|xphb":[7,"C","Action","Touch","VSM","Instant","","","",""],
605"plant growth|phb":[3,"T","Action or 8 hr","150 ft","VS","Instant","","","",""],
606"plant growth|xphb":[3,"T","Action or 8 hr","150 ft","VS","Instant","","","",""],
607"poison spray|phb":[0,"C","Action","10 ft","VS","Instant","","poison","CON","1:1d12 5:2d12 11:3d12 17:4d12"],
608"poison spray|xphb":[0,"N","Action","30 ft","VS","Instant","ranged","poison","","1:1d12 5:2d12 11:3d12 17:4d12"],
609"polymorph|phb":[4,"T","Action","60 ft","VSM","1 hr","conc","","WIS",""],
610"polymorph|xphb":[4,"T","Action","60 ft","VSM","1 hr","conc","","WIS",""],
611"power word fortify|xphb":[7,"E","Action","60 ft","V","Instant","","","",""],
612"power word heal|phb":[9,"V","Action","Touch","VS","Instant","heal","","",""],
613"power word heal|xphb":[9,"E","Action","60 ft","VS","Instant","heal","","",""],
614"power word kill|phb":[9,"E","Action","60 ft","V","Instant","","","",""],
615"power word kill|xphb":[9,"E","Action","60 ft","V","Instant","","psychic","",""],
616"power word pain|xge":[7,"E","Action","60 ft","V","Instant","","","CON",""],
617"power word stun|phb":[8,"E","Action","60 ft","V","Instant","","","CON",""],
618"power word stun|xphb":[8,"E","Action","60 ft","V","Instant","","","CON",""],
619"prayer of healing|phb":[2,"V","10 min","30 ft","V","Instant","heal mod","","","2d8"],
620"prayer of healing|xphb":[2,"A","10 min","30 ft","V","Instant","heal","","","2d8"],
621"prestidigitation|phb":[0,"T","Action","10 ft","VS","1 hr","","","",""],
622"prestidigitation|xphb":[0,"T","Action","10 ft","VS","1 hr","","","",""],
623"primal savagery|xge":[0,"T","Action","Self","S","Instant","melee","acid","","1:1d10 5:2d10 11:3d10 17:4d10"],
624"primordial ward|xge":[6,"A","Action","Self","VS","1 min","conc","","",""],
625"prismatic spray|phb":[7,"V","Action","60 ft cone","VS","Instant","","acid,cold,fire,lightning,poison","DEX/CON/WIS",""],
626"prismatic spray|xphb":[7,"V","Action","60 ft cone","VS","Instant","","acid,cold,fire,lightning,poison","DEX/CON/WIS",""],
627"prismatic wall|phb":[9,"A","Action","60 ft","VS","10 min","","acid,cold,fire,force,lightning,poison","CON/DEX/WIS",""],
628"prismatic wall|xphb":[9,"A","Action","60 ft","VS","10 min","","acid,cold,fire,force,lightning,poison","CON/DEX/WIS",""],
629"produce flame|phb":[0,"C","Action","Self","VS","10 min","ranged","fire","","1:1d8 5:2d8 11:3d8 17:4d8"],
630"produce flame|xphb":[0,"C","Bonus Action","Self","VS","10 min","ranged","fire","","1:1d8 5:2d8 11:3d8 17:4d8"],
631"programmed illusion|phb":[6,"I","Action","120 ft","VSM","Until dispelled","","","",""],
632"programmed illusion|xphb":[6,"I","Action","120 ft","VSM","Until dispelled","","","",""],
633"project image|phb":[7,"I","Action","500 miles","VSM","1 day","conc","","",""],
634"project image|xphb":[7,"I","Action","500 miles","VSM","1 day","conc","","",""],
635"protection from energy|phb":[3,"A","Action","Touch","VS","1 hr","conc","","",""],
636"protection from energy|xphb":[3,"A","Action","Touch","VS","1 hr","conc","","",""],
637"protection from evil and good|phb":[1,"A","Action","Touch","VSM","10 min","conc","","",""],
638"protection from evil and good|xphb":[1,"A","Action","Touch","VSM","10 min","conc","","",""],
639"protection from poison|phb":[2,"A","Action","Touch","VS","1 hr","","","",""],
640"protection from poison|xphb":[2,"A","Action","Touch","VS","1 hr","","","",""],
641"psychic scream|xge":[9,"E","Action","90 ft","S","Instant","","psychic","INT",""],
642"purify food and drink|phb":[1,"T","Action","10 ft","VS","Instant","ritual","","",""],
643"purify food and drink|xphb":[1,"T","Action","10 ft","VS","Instant","ritual","","",""],
644"pyrotechnics|xge":[2,"T","Action","60 ft","VS","Instant","","","CON",""],
645"raise dead|phb":[5,"N","1 hr","Touch","VSM","Instant","heal","","",""],
646"raise dead|xphb":[5,"N","1 hr","Touch","VSM","Instant","heal","","",""],
647"rary s telepathic bond|phb":[5,"D","Action","30 ft","VSM","1 hr","ritual","","",""],
648"rary s telepathic bond|xphb":[5,"D","Action","30 ft","VSM","1 hr","ritual","","",""],
649"ray of enfeeblement|phb":[2,"N","Action","60 ft","VS","1 min","conc ranged","","CON",""],
650"ray of enfeeblement|xphb":[2,"N","Action","60 ft","VS","1 min","conc","","CON",""],
651"ray of frost|phb":[0,"V","Action","60 ft","VS","Instant","ranged","cold","","1:1d8 5:2d8 11:3d8 17:4d8"],
652"ray of frost|xphb":[0,"V","Action","60 ft","VS","Instant","ranged","cold","","1:1d8 5:2d8 11:3d8 17:4d8"],
653"ray of sickness|phb":[1,"N","Action","60 ft","VS","Instant","ranged","poison","CON","2d8"],
654"ray of sickness|xphb":[1,"N","Action","60 ft","VS","Instant","ranged","poison","","2d8"],
655"regenerate|phb":[7,"T","1 min","Touch","VSM","1 hr","heal","","",""],
656"regenerate|xphb":[7,"T","1 min","Touch","VSM","1 hr","heal","","",""],
657"reincarnate|phb":[5,"T","1 hr","Touch","VSM","Instant","heal","","",""],
658"reincarnate|xphb":[5,"N","1 hr","Touch","VSM","Instant","heal","","",""],
659"remove curse|phb":[3,"A","Action","Touch","VS","Instant","","","",""],
660"remove curse|xphb":[3,"A","Action","Touch","VS","Instant","","","",""],
661"resistance|phb":[0,"A","Action","Touch","VSM","1 min","conc","","",""],
662"resistance|xphb":[0,"A","Action","Touch","VS","1 min","conc","","",""],
663"resurrection|phb":[7,"N","1 hr","Touch","VSM","Instant","heal","","",""],
664"resurrection|xphb":[7,"N","1 hr","Touch","VSM","Instant","heal","","",""],
665"reverse gravity|phb":[7,"T","Action","100 ft","VSM","1 min","conc","","DEX",""],
666"reverse gravity|xphb":[7,"T","Action","100 ft","VSM","1 min","conc","","DEX",""],
667"revivify|phb":[3,"N","Action","Touch","VSM","Instant","heal","","",""],
668"revivify|xphb":[3,"N","Action","Touch","VSM","Instant","heal","","",""],
669"rope trick|phb":[2,"T","Action","Touch","VSM","1 hr","","","",""],
670"rope trick|xphb":[2,"T","Action","Touch","VSM","1 hr","","","",""],
671"sacred flame|phb":[0,"V","Action","60 ft","VS","Instant","","radiant","DEX","1:1d8 5:2d8 11:3d8 17:4d8"],
672"sacred flame|xphb":[0,"V","Action","60 ft","VS","Instant","","radiant","DEX","1:1d8 5:2d8 11:3d8 17:4d8"],
673"sanctuary|phb":[1,"A","Bonus Action","30 ft","VSM","1 min","","","WIS",""],
674"sanctuary|xphb":[1,"A","Bonus Action","30 ft","VSM","1 min","","","WIS",""],
675"scatter|xge":[6,"C","Action","30 ft","V","Instant","","","WIS",""],
676"scorching ray|phb":[2,"V","Action","120 ft","VS","Instant","ranged","fire","",""],
677"scorching ray|xphb":[2,"V","Action","120 ft","VS","Instant","ranged","fire","",""],
678"scrying|phb":[5,"D","10 min","Self","VSM","10 min","conc","","WIS",""],
679"scrying|xphb":[5,"D","10 min","Self","VSM","10 min","conc","","WIS",""],
680"searing smite|phb":[1,"V","Bonus Action","Self","V","1 min","conc","fire","CON","1d6"],
681"searing smite|xphb":[1,"V","Bonus Action","Self","V","1 min","","fire","CON","1d6"],
682"see invisibility|phb":[2,"D","Action","Self","VSM","1 hr","","","",""],
683"see invisibility|xphb":[2,"D","Action","Self","VSM","1 hr","","","",""],
684"seeming|phb":[5,"I","Action","30 ft","VS","8 hr","","","CHA",""],
685"seeming|xphb":[5,"I","Action","30 ft","VS","8 hr","","","CHA",""],
686"sending|phb":[3,"V","Action","Unlimited","VSM","1 round","","","",""],
687"sending|xphb":[3,"D","Action","Unlimited","VSM","Instant","","","",""],
688"sequester|phb":[7,"T","Action","Touch","VSM","Until dispelled","","","",""],
689"sequester|xphb":[7,"T","Action","Touch","VSM","Until dispelled","","","",""],
690"shadow blade|xge":[2,"I","Bonus Action","Self","VS","1 min","conc","psychic","",""],
691"shadow of moil|xge":[4,"N","Action","Self","VSM","1 min","conc","necrotic","",""],
692"shape water|xge":[0,"T","Action","30 ft","S","Instant or 1 hr","","","",""],
693"shapechange|phb":[9,"T","Action","Self","VSM","1 hr","conc","","",""],
694"shapechange|xphb":[9,"T","Action","Self","VSM","1 hr","conc","","",""],
695"shatter|phb":[2,"V","Action","60 ft","VSM","Instant","","thunder","CON","3d8"],
696"shatter|xphb":[2,"V","Action","60 ft","VSM","Instant","","thunder","CON","3d8"],
697"shield of faith|phb":[1,"A","Bonus Action","60 ft","VSM","10 min","conc","","",""],
698"shield of faith|xphb":[1,"A","Bonus Action","60 ft","VSM","10 min","conc","","",""],
699"shield|phb":[1,"A","Reaction","Self","VS","1 round","","","",""],
700"shield|xphb":[1,"A","Reaction","Self","VS","1 round","","","",""],
701"shillelagh|phb":[0,"T","Bonus Action","Touch","VSM","1 min","","","",""],
702"shillelagh|xphb":[0,"T","Bonus Action","Self","VSM","1 min","","force","","1:1d8 5:1d10 11:1d12 17:2d6"],
703"shining smite|xphb":[2,"T","Bonus Action","Self","V","1 min","conc","radiant","","2d6"],
704"shocking grasp|phb":[0,"V","Action","Touch","VS","Instant","melee","lightning","","1:1d8 5:2d8 11:3d8 17:4d8"],
705"shocking grasp|xphb":[0,"V","Action","Touch","VS","Instant","melee","lightning","","1:1d8 5:2d8 11:3d8 17:4d8"],
706"sickening radiance|xge":[4,"V","Action","120 ft","VS","10 min","conc","radiant","CON",""],
707"silence|phb":[2,"I","Action","120 ft","VS","10 min","conc ritual","","",""],
708"silence|xphb":[2,"I","Action","120 ft","VS","10 min","conc ritual","","",""],
709"silent image|phb":[1,"I","Action","60 ft","VSM","10 min","conc","","",""],
710"silent image|xphb":[1,"I","Action","60 ft","VSM","10 min","conc","","",""],
711"simulacrum|phb":[7,"I","12 hr","Touch","VSM","Until dispelled","","","",""],
712"simulacrum|xphb":[7,"I","12 hr","Touch","VSM","Until dispelled","","","",""],
713"skill empowerment|xge":[5,"T","Action","Touch","VS","1 hr","conc","","",""],
714"skywrite|xge":[2,"T","Action","Sight","VS","1 hr","conc ritual","","",""],
715"sleep|phb":[1,"E","Action","90 ft","VSM","1 min","","","",""],
716"sleep|xphb":[1,"E","Action","60 ft","VSM","1 min","conc","","WIS",""],
717"sleet storm|phb":[3,"C","Action","150 ft","VSM","1 min","conc","","DEX/CON",""],
718"sleet storm|xphb":[3,"C","Action","150 ft","VSM","1 min","conc","","DEX",""],
719"slow|phb":[3,"T","Action","120 ft","VSM","1 min","conc","","WIS",""],
720"slow|xphb":[3,"T","Action","120 ft","VSM","1 min","conc","","WIS",""],
721"snare|xge":[1,"A","1 min","Touch","SM","8 hr","","","DEX",""],
722"snilloc s snowball swarm|xge":[2,"V","Action","90 ft","VSM","Instant","","cold","DEX","3d6"],
723"sorcerous burst|xphb":[0,"V","Action","120 ft","VS","Instant","ranged","acid,cold,fire,lightning,poison,psychic,thunder","","1:1d8 5:2d8 11:3d8 17:4d8"],
724"soul cage|xge":[6,"N","Reaction","60 ft","VSM","8 hr","heal","","",""],
725"spare the dying|phb":[0,"N","Action","Touch","VS","Instant","","","",""],
726"spare the dying|xphb":[0,"N","Action","15 ft","VS","Instant","","","",""],
727"speak with animals|phb":[1,"D","Action","Self","VS","10 min","ritual","","",""],
728"speak with animals|xphb":[1,"D","Action","Self","VS","10 min","ritual","","",""],
729"speak with dead|phb":[3,"N","Action","10 ft","VSM","10 min","","","",""],
730"speak with dead|xphb":[3,"N","Action","10 ft","VSM","10 min","","","",""],
731"speak with plants|phb":[3,"T","Action","30 ft radius","VS","10 min","","","",""],
732"speak with plants|xphb":[3,"T","Action","30 ft emanation","VS","10 min","","","",""],
733"spider climb|phb":[2,"T","Action","Touch","VSM","1 hr","conc","","",""],
734"spider climb|xphb":[2,"T","Action","Touch","VSM","1 hr","conc","","",""],
735"spike growth|phb":[2,"T","Action","150 ft","VSM","10 min","conc","piercing","",""],
736"spike growth|xphb":[2,"T","Action","150 ft","VSM","10 min","conc","piercing","",""],
737"spirit guardians|phb":[3,"C","Action","15 ft radius","VSM","10 min","conc","necrotic,radiant","WIS","3d8"],
738"spirit guardians|xphb":[3,"C","Action","15 ft emanation","VSM","10 min","conc","necrotic,radiant","WIS","3d8"],
739"spirit shroud|tce":[3,"N","Bonus Action","Self","VS","1 min","conc","radiant,necrotic,cold","","1d8"],
740"spiritual weapon|phb":[2,"V","Bonus Action","60 ft","VS","1 min","melee","force","","1d8"],
741"spiritual weapon|xphb":[2,"V","Bonus Action","60 ft","VS","1 min","conc melee","force","","1d8"],
742"staggering smite|phb":[4,"V","Bonus Action","Self","V","1 min","conc","psychic","WIS",""],
743"staggering smite|xphb":[4,"E","Bonus Action","Self","V","Instant","","psychic","WIS","4d6"],
744"starry wisp|xphb":[0,"V","Action","60 ft","VS","Instant","ranged","radiant","","1:1d8 5:2d8 11:3d8 17:4d8"],
745"steel wind strike|xge":[5,"C","Action","30 ft","SM","Instant","melee","force","",""],
746"steel wind strike|xphb":[5,"C","Action","30 ft","SM","Instant","melee","force","",""],
747"stinking cloud|phb":[3,"C","Action","90 ft","VSM","1 min","conc","","CON",""],
748"stinking cloud|xphb":[3,"C","Action","90 ft","VSM","1 min","conc","","CON",""],
749"stone shape|phb":[4,"T","Action","Touch","VSM","Instant","","","",""],
750"stone shape|xphb":[4,"T","Action","Touch","VSM","Instant","","","",""],
751"stoneskin|phb":[4,"A","Action","Touch","VSM","1 hr","conc","","",""],
752"stoneskin|xphb":[4,"T","Action","Touch","VSM","1 hr","conc","","",""],
753"storm of vengeance|phb":[9,"C","Action","Sight","VS","1 min","conc","acid,bludgeoning,cold,lightning,thunder","CON/DEX",""],
754"storm of vengeance|xphb":[9,"C","Action","1 mile","VS","1 min","conc","acid,bludgeoning,cold,lightning,thunder","CON/DEX",""],
755"storm sphere|xge":[4,"V","Action","150 ft","VS","1 min","conc ranged","bludgeoning,lightning","STR",""],
756"suggestion|phb":[2,"E","Action","30 ft","VM","8 hr","conc","","WIS",""],
757"suggestion|xphb":[2,"E","Action","30 ft","VM","8 hr","conc","","WIS",""],
758"summon aberration|tce":[4,"C","Action","90 ft","VSM","1 hr","conc","","",""],
759"summon aberration|xphb":[4,"C","Action","90 ft","VSM","1 hr","conc","","",""],
760"summon beast|tce":[2,"C","Action","90 ft","VSM","1 hr","conc","","",""],
761"summon beast|xphb":[2,"C","Action","90 ft","VSM","1 hr","conc","","",""],
762"summon celestial|tce":[5,"C","Action","90 ft","VSM","1 hr","conc","","",""],
763"summon celestial|xphb":[5,"C","Action","90 ft","VSM","1 hr","conc","","",""],
764"summon construct|tce":[4,"C","Action","90 ft","VSM","1 hr","conc","","",""],
765"summon construct|xphb":[4,"C","Action","90 ft","VSM","1 hr","conc","","",""],
766"summon dragon|xphb":[5,"C","Action","60 ft","VSM","1 hr","conc","","",""],
767"summon elemental|tce":[4,"C","Action","90 ft","VSM","1 hr","conc","","",""],
768"summon elemental|xphb":[4,"C","Action","90 ft","VSM","1 hr","conc","","",""],
769"summon fey|tce":[3,"C","Action","90 ft","VSM","1 hr","conc","","",""],
770"summon fey|xphb":[3,"C","Action","90 ft","VSM","1 hr","conc","","",""],
771"summon fiend|tce":[6,"C","Action","90 ft","VSM","1 hr","conc","","",""],
772"summon fiend|xphb":[6,"C","Action","90 ft","VSM","1 hr","conc","","",""],
773"summon greater demon|xge":[4,"C","Action","60 ft","VSM","1 hr","conc","","CHA",""],
774"summon lesser demons|xge":[3,"C","Action","60 ft","VSM","1 hr","conc","","",""],
775"summon shadowspawn|tce":[3,"C","Action","90 ft","VSM","1 hr","conc","","",""],
776"summon undead|tce":[3,"N","Action","90 ft","VSM","1 hr","conc","","",""],
777"summon undead|xphb":[3,"N","Action","90 ft","VSM","1 hr","conc","","",""],
778"sunbeam|phb":[6,"V","Action","60 ft line","VSM","1 min","conc","radiant","CON",""],
779"sunbeam|xphb":[6,"V","Action","60 ft line","VSM","1 min","conc","radiant","CON",""],
780"sunburst|phb":[8,"V","Action","150 ft","VSM","Instant","","radiant","CON",""],
781"sunburst|xphb":[8,"V","Action","150 ft","VSM","Instant","","radiant","CON",""],
782"swift quiver|phb":[5,"T","Bonus Action","Touch","VSM","1 min","conc","","",""],
783"swift quiver|xphb":[5,"T","Bonus Action","Self","VSM","1 min","conc","","",""],
784"sword burst|tce":[0,"C","Action","5 ft radius","V","Instant","","force","DEX","1:1d6 5:2d6 11:3d6 17:4d6"],
785"symbol|phb":[7,"A","1 min","Touch","VSM","Until dispelled or triggered","","necrotic","CON/WIS/CHA/INT",""],
786"symbol|xphb":[7,"A","1 min","Touch","VSM","Until dispelled or triggered","","necrotic","CON/WIS/INT",""],
787"synaptic static|xge":[5,"E","Action","120 ft","VS","Instant","","psychic","INT/CON",""],
788"synaptic static|xphb":[5,"E","Action","120 ft","VS","Instant","","psychic","INT/CON",""],
789"tasha s bubbling cauldron|xphb":[6,"C","Action","5 ft","VSM","10 min","heal","","",""],
790"tasha s caustic brew|tce":[1,"V","Action","30 ft line","VSM","1 min","conc","acid","DEX","2d4"],
791"tasha s hideous laughter|phb":[1,"E","Action","30 ft","VSM","1 min","conc","","WIS",""],
792"tasha s hideous laughter|xphb":[1,"E","Action","30 ft","VSM","1 min","conc","","WIS",""],
793"tasha s mind whip|tce":[2,"E","Action","90 ft","V","1 round","","psychic","INT",""],
794"tasha s otherworldly guise|tce":[6,"T","Bonus Action","Self","VSM","1 min","conc","","",""],
795"telekinesis|phb":[5,"T","Action","60 ft","VS","10 min","conc","","",""],
796"telekinesis|xphb":[5,"T","Action","60 ft","VS","10 min","conc","","STR",""],
797"telepathy|phb":[8,"V","Action","Unlimited","VSM","24 hr","","","",""],
798"telepathy|xphb":[8,"D","Action","Unlimited","VSM","24 hr","","","",""],
799"teleportation circle|phb":[5,"C","1 min","10 ft","VM","1 round","","","",""],
800"teleportation circle|xphb":[5,"C","1 min","10 ft","VM","1 round","","","",""],
801"teleport|phb":[7,"C","Action","10 ft","V","Instant","","force","",""],
802"teleport|xphb":[7,"C","Action","10 ft","V","Instant","","force","",""],
803"temple of the gods|xge":[7,"C","1 hr","120 ft","VSM","24 hr","heal","","CHA",""],
804"tenser s floating disk|phb":[1,"C","Action","30 ft","VSM","1 hr","ritual","","",""],
805"tenser s floating disk|xphb":[1,"C","Action","30 ft","VSM","1 hr","ritual","","",""],
806"tenser s transformation|xge":[6,"T","Action","Self","VSM","10 min","conc","force","CON",""],
807"thaumaturgy|phb":[0,"T","Action","30 ft","V","1 min","","","",""],
808"thaumaturgy|xphb":[0,"T","Action","30 ft","V","1 min","","","",""],
809"thorn whip|phb":[0,"T","Action","30 ft","VSM","Instant","melee","piercing","","1:1d6 5:2d6 11:3d6 17:4d6"],
810"thorn whip|xphb":[0,"T","Action","30 ft","VSM","Instant","melee","piercing","","1:1d6 5:2d6 11:3d6 17:4d6"],
811"thunder step|xge":[3,"C","Action","90 ft","V","Instant","","thunder","CON","3d10"],
812"thunderclap|xge":[0,"V","Action","5 ft","S","Instant","","thunder","CON","1:1d6 5:2d6 11:3d6 17:4d6"],
813"thunderclap|xphb":[0,"V","Action","5 ft emanation","S","Instant","","thunder","CON","1:1d6 5:2d6 11:3d6 17:4d6"],
814"thunderous smite|phb":[1,"V","Bonus Action","Self","V","1 min","conc","thunder","STR",""],
815"thunderous smite|xphb":[1,"V","Bonus Action","Self","V","Instant","","thunder","STR","2d6"],
816"thunderwave|phb":[1,"V","Action","15 ft cube","VS","Instant","","thunder","CON","2d8"],
817"thunderwave|xphb":[1,"V","Action","15 ft cube","VS","Instant","","thunder","CON","2d8"],
818"tidal wave|xge":[3,"C","Action","120 ft","VSM","Instant","","bludgeoning","DEX",""],
819"time stop|phb":[9,"T","Action","Self","V","Instant","","","",""],
820"time stop|xphb":[9,"T","Action","Self","V","Instant","","","",""],
821"tiny servant|xge":[3,"T","1 min","Touch","VS","8 hr","","","",""],
822"toll the dead|xge":[0,"N","Action","60 ft","VS","Instant","","necrotic","WIS","1:1d8/1d12 5:2d8/2d12 11:3d8/3d12 17:4d8/4d12"],
823"toll the dead|xphb":[0,"N","Action","60 ft","VS","Instant","","necrotic","WIS","1:1d8/1d12 5:2d8/2d12 11:3d8/3d12 17:4d8/4d12"],
824"tongues|phb":[3,"D","Action","Touch","VM","1 hr","","","",""],
825"tongues|xphb":[3,"D","Action","Touch","VM","1 hr","","","",""],
826"transmute rock|xge":[5,"T","Action","120 ft","VSM","Until dispelled","","bludgeoning","STR/DEX",""],
827"transport via plants|phb":[6,"C","Action","10 ft","VS","1 round","","","",""],
828"transport via plants|xphb":[6,"C","Action","10 ft","VS","1 min","","","",""],
829"tree stride|phb":[5,"C","Action","Self","VS","1 min","conc","","",""],
830"tree stride|xphb":[5,"C","Action","Self","VS","1 min","conc","","",""],
831"true polymorph|phb":[9,"T","Action","30 ft","VSM","1 hr","conc","","WIS",""],
832"true polymorph|xphb":[9,"T","Action","30 ft","VSM","1 hr","conc","","WIS",""],
833"true resurrection|phb":[9,"N","1 hr","Touch","VSM","Instant","heal","","",""],
834"true resurrection|xphb":[9,"N","1 hr","Touch","VSM","Instant","heal","","",""],
835"true seeing|phb":[6,"D","Action","Touch","VSM","1 hr","","","",""],
836"true seeing|xphb":[6,"D","Action","Touch","VSM","1 hr","","","",""],
837"true strike|phb":[0,"D","Action","30 ft","S","1 round","conc","","",""],
838"true strike|xphb":[0,"D","Action","Self","SM","Instant","","radiant","","5:1d6 11:2d6 17:3d6"],
839"tsunami|phb":[8,"C","1 min","Sight","VS","6 rounds","conc","bludgeoning","STR",""],
840"tsunami|xphb":[8,"C","1 min","1 mile","VS","6 rounds","conc","bludgeoning","STR",""],
841"unseen servant|phb":[1,"C","Action","60 ft","VSM","1 hr","ritual","","",""],
842"unseen servant|xphb":[1,"C","Action","60 ft","VSM","1 hr","ritual","","",""],
843"vampiric touch|phb":[3,"N","Action","Self","VS","1 min","conc melee","necrotic","","3d6"],
844"vampiric touch|xphb":[3,"N","Action","Self","VS","1 min","conc melee","necrotic","","3d6"],
845"vicious mockery|phb":[0,"E","Action","60 ft","V","Instant","","psychic","WIS","1:1d4 5:2d4 11:3d4 17:4d4"],
846"vicious mockery|xphb":[0,"E","Action","60 ft","V","Instant","","psychic","WIS","1:1d6 5:2d6 11:3d6 17:4d6"],
847"vitriolic sphere|xge":[4,"V","Action","150 ft","VSM","Instant","","acid","DEX","10d4"],
848"vitriolic sphere|xphb":[4,"V","Action","150 ft","VSM","Instant","","acid","DEX","10d4"],
849"wall of fire|phb":[4,"V","Action","120 ft","VSM","1 min","conc","fire","DEX","5d8"],
850"wall of fire|xphb":[4,"V","Action","120 ft","VSM","1 min","conc","fire","DEX","5d8"],
851"wall of force|phb":[5,"V","Action","120 ft","VSM","10 min","conc","","",""],
852"wall of force|xphb":[5,"V","Action","120 ft","VSM","10 min","conc","","",""],
853"wall of ice|phb":[6,"V","Action","120 ft","VSM","10 min","conc","cold","DEX/CON",""],
854"wall of ice|xphb":[6,"V","Action","120 ft","VSM","10 min","conc","cold","DEX/CON",""],
855"wall of light|xge":[5,"V","Action","120 ft","VSM","10 min","conc ranged","radiant","CON","4d8"],
856"wall of sand|xge":[3,"V","Action","90 ft","VSM","10 min","conc","","",""],
857"wall of stone|phb":[5,"V","Action","120 ft","VSM","10 min","conc","","DEX",""],
858"wall of stone|xphb":[5,"V","Action","120 ft","VSM","10 min","conc","","DEX",""],
859"wall of thorns|phb":[6,"C","Action","120 ft","VSM","10 min","conc","piercing,slashing","DEX","7d8"],
860"wall of thorns|xphb":[6,"C","Action","120 ft","VSM","10 min","conc","piercing,slashing","DEX","7d8"],
861"wall of water|xge":[3,"V","Action","60 ft","VSM","10 min","conc","","",""],
862"warding bond|phb":[2,"A","Action","Touch","VSM","1 hr","","","",""],
863"warding bond|xphb":[2,"A","Action","Touch","VSM","1 hr","","","",""],
864"warding wind|xge":[2,"V","Action","Self","V","10 min","conc","","",""],
865"water breathing|phb":[3,"T","Action","30 ft","VSM","24 hr","ritual","","",""],
866"water breathing|xphb":[3,"T","Action","30 ft","VSM","24 hr","ritual","","",""],
867"water walk|phb":[3,"T","Action","30 ft","VSM","1 hr","ritual","","",""],
868"water walk|xphb":[3,"T","Action","30 ft","VSM","1 hr","ritual","","",""],
869"watery sphere|xge":[4,"C","Action","90 ft","VSM","1 min","conc","","STR",""],
870"web|phb":[2,"C","Action","60 ft","VSM","1 hr","conc","fire","DEX",""],
871"web|xphb":[2,"C","Action","60 ft","VSM","1 hr","conc","fire","DEX",""],
872"weird|phb":[9,"I","Action","120 ft","VS","1 min","conc","psychic","WIS",""],
873"weird|xphb":[9,"I","Action","120 ft","VS","1 min","conc","psychic","WIS",""],
874"whirlwind|xge":[7,"V","Action","300 ft","VM","1 min","conc","bludgeoning","DEX/STR",""],
875"wind walk|phb":[6,"T","1 min","30 ft","VSM","8 hr","","","",""],
876"wind walk|xphb":[6,"T","1 min","30 ft","VSM","8 hr","","","",""],
877"wind wall|phb":[3,"V","Action","120 ft","VSM","1 min","conc","bludgeoning","STR",""],
878"wind wall|xphb":[3,"V","Action","120 ft","VSM","1 min","conc","bludgeoning","STR",""],
879"wish|phb":[9,"C","Action","Self","V","Instant","","necrotic","",""],
880"wish|xphb":[9,"C","Action","Self","V","Instant","","necrotic","",""],
881"witch bolt|phb":[1,"V","Action","30 ft","VSM","1 min","conc ranged","lightning","","1d12"],
882"witch bolt|xphb":[1,"V","Action","60 ft","VSM","1 min","conc ranged","lightning","","2d12"],
883"word of radiance|xge":[0,"V","Action","5 ft","VM","Instant","","radiant","CON","1:1d6 5:2d6 11:3d6 17:4d6"],
884"word of radiance|xphb":[0,"V","Action","5 ft emanation","VM","Instant","","radiant","CON","1:1d6 5:2d6 11:3d6 17:4d6"],
885"word of recall|phb":[6,"C","Action","5 ft","V","Instant","","","",""],
886"word of recall|xphb":[6,"C","Action","5 ft","V","Instant","","","",""],
887"wrath of nature|xge":[5,"V","Action","120 ft","VS","1 min","conc ranged","bludgeoning,slashing","DEX/STR",""],
888"wrathful smite|phb":[1,"V","Bonus Action","Self","V","1 min","conc","psychic","WIS",""],
889"wrathful smite|xphb":[1,"N","Bonus Action","Self","V","1 min","","necrotic","WIS","1d6"],
890"yolande s regal presence|xphb":[5,"E","Action","10 ft emanation","VSM","1 min","conc","psychic","WIS",""],
891"zephyr strike|xge":[1,"T","Bonus Action","Self","V","1 min","conc","force","",""],
892"zone of truth|phb":[2,"E","Action","60 ft","VS","10 min","","","CHA",""],
893"zone of truth|xphb":[2,"E","Action","60 ft","VS","10 min","","","CHA",""],
894}
895
896/** Other names the data gives a spell (Firebolt), to the name keyed above. */
897export const SPELL_ALIASES: Record<string, string> = {
898"firebolt":"fire bolt",
899}
900
901export const WEAPONS: Record<string, WeaponRow> = {
902"antimatter rifle|dmg":["martial","ranged","6d8","necrotic","","Ammunition,Reload,Two-Handed","120/360",""],
903"antimatter rifle|xdmg":["martial","ranged","6d8","necrotic","","Ammunition,Reload,Two-Handed","120/360","Sap"],
904"automatic pistol|dmg":["martial","ranged","2d6","piercing","","Ammunition,Reload","50/150",""],
905"automatic rifle|dmg":["martial","ranged","2d8","piercing","","Ammunition,Burst Fire,Reload,Two-Handed","80/240",""],
906"automatic rifle|xdmg":["martial","ranged","2d8","piercing","","Ammunition,Burst Fire,Reload,Two-Handed","80/240","Slow"],
907"battleaxe|phb":["martial","melee","1d8","slashing","1d10","Versatile","",""],
908"battleaxe|xphb":["martial","melee","1d8","slashing","1d10","Versatile","","Topple"],
909"blowgun|phb":["martial","ranged","1","piercing","","Ammunition,Loading","25/100",""],
910"blowgun|xphb":["martial","ranged","1","piercing","","Ammunition,Loading","25/100","Vex"],
911"club|phb":["simple","melee","1d4","bludgeoning","","Light","",""],
912"club|xphb":["simple","melee","1d4","bludgeoning","","Light","","Slow"],
913"dagger|phb":["simple","melee","1d4","piercing","","Finesse,Light,Thrown","20/60",""],
914"dagger|xphb":["simple","melee","1d4","piercing","","Finesse,Light,Thrown","20/60","Nick"],
915"dart|phb":["simple","ranged","1d4","piercing","","Finesse,Thrown","20/60",""],
916"dart|xphb":["simple","ranged","1d4","piercing","","Finesse,Thrown","20/60","Vex"],
917"flail|phb":["martial","melee","1d8","bludgeoning","","","",""],
918"flail|xphb":["martial","melee","1d8","bludgeoning","","","","Sap"],
919"glaive|phb":["martial","melee","1d10","slashing","","Heavy,Reach,Two-Handed","",""],
920"glaive|xphb":["martial","melee","1d10","slashing","","Heavy,Reach,Two-Handed","","Graze"],
921"greataxe|phb":["martial","melee","1d12","slashing","","Heavy,Two-Handed","",""],
922"greataxe|xphb":["martial","melee","1d12","slashing","","Heavy,Two-Handed","","Cleave"],
923"greatclub|phb":["simple","melee","1d8","bludgeoning","","Two-Handed","",""],
924"greatclub|xphb":["simple","melee","1d8","bludgeoning","","Two-Handed","","Push"],
925"greatsword|phb":["martial","melee","2d6","slashing","","Heavy,Two-Handed","",""],
926"greatsword|xphb":["martial","melee","2d6","slashing","","Heavy,Two-Handed","","Graze"],
927"halberd|phb":["martial","melee","1d10","slashing","","Heavy,Reach,Two-Handed","",""],
928"halberd|xphb":["martial","melee","1d10","slashing","","Heavy,Reach,Two-Handed","","Cleave"],
929"hand crossbow|phb":["martial","ranged","1d6","piercing","","Ammunition,Light,Loading","30/120",""],
930"hand crossbow|xphb":["martial","ranged","1d6","piercing","","Ammunition,Light,Loading","30/120","Vex"],
931"handaxe|phb":["simple","melee","1d6","slashing","","Light,Thrown","20/60",""],
932"handaxe|xphb":["simple","melee","1d6","slashing","","Light,Thrown","20/60","Vex"],
933"heavy crossbow|phb":["martial","ranged","1d10","piercing","","Ammunition,Heavy,Loading,Two-Handed","100/400",""],
934"heavy crossbow|xphb":["martial","ranged","1d10","piercing","","Ammunition,Heavy,Loading,Two-Handed","100/400","Push"],
935"hunting rifle|dmg":["martial","ranged","2d10","piercing","","Ammunition,Reload,Two-Handed","80/240",""],
936"hunting rifle|xdmg":["martial","ranged","2d10","piercing","","Ammunition,Reload,Two-Handed","80/240","Slow"],
937"javelin|phb":["simple","melee","1d6","piercing","","Thrown","30/120",""],
938"javelin|xphb":["simple","melee","1d6","piercing","","Thrown","30/120","Slow"],
939"lance|phb":["martial","melee","1d12","piercing","","Reach,Special","",""],
940"lance|xphb":["martial","melee","1d10","piercing","","Heavy,Reach,Two-Handed (unless mounted)","","Topple"],
941"laser pistol|dmg":["martial","ranged","3d6","radiant","","Ammunition,Reload","40/120",""],
942"laser pistol|xdmg":["martial","ranged","3d6","radiant","","Ammunition,Reload","40/120","Vex"],
943"laser rifle|dmg":["martial","ranged","3d8","radiant","","Ammunition,Reload,Two-Handed","100/300",""],
944"laser rifle|xdmg":["martial","ranged","3d8","radiant","","Ammunition,Reload,Two-Handed","100/300","Slow"],
945"light crossbow|phb":["simple","ranged","1d8","piercing","","Ammunition,Loading,Two-Handed","80/320",""],
946"light crossbow|xphb":["simple","ranged","1d8","piercing","","Ammunition,Loading,Two-Handed","80/320","Slow"],
947"light hammer|phb":["simple","melee","1d4","bludgeoning","","Light,Thrown","20/60",""],
948"light hammer|xphb":["simple","melee","1d4","bludgeoning","","Light,Thrown","20/60","Nick"],
949"longbow|phb":["martial","ranged","1d8","piercing","","Ammunition,Heavy,Two-Handed","150/600",""],
950"longbow|xphb":["martial","ranged","1d8","piercing","","Ammunition,Heavy,Two-Handed","150/600","Slow"],
951"longsword|phb":["martial","melee","1d8","slashing","1d10","Versatile","",""],
952"longsword|xphb":["martial","melee","1d8","slashing","1d10","Versatile","","Sap"],
953"mace|phb":["simple","melee","1d6","bludgeoning","","","",""],
954"mace|xphb":["simple","melee","1d6","bludgeoning","","","","Sap"],
955"maul|phb":["martial","melee","2d6","bludgeoning","","Heavy,Two-Handed","",""],
956"maul|xphb":["martial","melee","2d6","bludgeoning","","Heavy,Two-Handed","","Topple"],
957"morningstar|phb":["martial","melee","1d8","piercing","","","",""],
958"morningstar|xphb":["martial","melee","1d8","piercing","","","","Sap"],
959"musket|dmg":["martial","ranged","1d12","piercing","","Ammunition,Loading,Two-Handed","40/120",""],
960"musket|xphb":["martial","ranged","1d12","piercing","","Ammunition,Loading,Two-Handed","40/120","Slow"],
961"net|phb":["martial","ranged","","","","Special,Thrown","5/15",""],
962"pike|phb":["martial","melee","1d10","piercing","","Heavy,Reach,Two-Handed","",""],
963"pike|xphb":["martial","melee","1d10","piercing","","Heavy,Reach,Two-Handed","","Push"],
964"pistol|dmg":["martial","ranged","1d10","piercing","","Ammunition,Loading","30/90",""],
965"pistol|xphb":["martial","ranged","1d10","piercing","","Ammunition,Loading","30/90","Vex"],
966"quarterstaff|phb":["simple","melee","1d6","bludgeoning","1d8","Versatile","",""],
967"quarterstaff|xphb":["simple","melee","1d6","bludgeoning","1d8","Versatile","","Topple"],
968"rapier|phb":["martial","melee","1d8","piercing","","Finesse","",""],
969"rapier|xphb":["martial","melee","1d8","piercing","","Finesse","","Vex"],
970"revolver|dmg":["martial","ranged","2d8","piercing","","Ammunition,Reload","40/120",""],
971"revolver|xdmg":["martial","ranged","2d8","piercing","","Ammunition,Reload","40/120","Sap"],
972"scimitar|phb":["martial","melee","1d6","slashing","","Finesse,Light","",""],
973"scimitar|xphb":["martial","melee","1d6","slashing","","Finesse,Light","","Nick"],
974"semiautomatic pistol|xdmg":["martial","ranged","2d6","piercing","","Ammunition,Reload","50/150","Vex"],
975"shortbow|phb":["simple","ranged","1d6","piercing","","Ammunition,Two-Handed","80/320",""],
976"shortbow|xphb":["simple","ranged","1d6","piercing","","Ammunition,Two-Handed","80/320","Vex"],
977"shortsword|phb":["martial","melee","1d6","piercing","","Finesse,Light","",""],
978"shortsword|xphb":["martial","melee","1d6","piercing","","Finesse,Light","","Vex"],
979"shotgun|dmg":["martial","ranged","2d8","piercing","","Ammunition,Reload,Two-Handed","30/90",""],
980"shotgun|xdmg":["martial","ranged","2d8","piercing","","Ammunition,Reload,Two-Handed","30/90","Push"],
981"sickle|phb":["simple","melee","1d4","slashing","","Light","",""],
982"sickle|xphb":["simple","melee","1d4","slashing","","Light","","Nick"],
983"sling|phb":["simple","ranged","1d4","bludgeoning","","Ammunition","30/120",""],
984"sling|xphb":["simple","ranged","1d4","bludgeoning","","Ammunition","30/120","Slow"],
985"spear|phb":["simple","melee","1d6","piercing","1d8","Thrown,Versatile","20/60",""],
986"spear|xphb":["simple","melee","1d6","piercing","1d8","Thrown,Versatile","20/60","Sap"],
987"trident|phb":["martial","melee","1d6","piercing","1d8","Thrown,Versatile","20/60",""],
988"trident|xphb":["martial","melee","1d8","piercing","1d10","Thrown,Versatile","20/60","Topple"],
989"war pick|phb":["martial","melee","1d8","piercing","","","",""],
990"war pick|xphb":["martial","melee","1d8","piercing","1d10","Versatile","","Sap"],
991"warhammer|phb":["martial","melee","1d8","bludgeoning","1d10","Versatile","",""],
992"warhammer|xphb":["martial","melee","1d8","bludgeoning","1d10","Versatile","","Push"],
993"whip|phb":["martial","melee","1d4","slashing","","Finesse,Reach","",""],
994"whip|xphb":["martial","melee","1d4","slashing","","Finesse,Reach","","Slow"],
995"yklwa|toa":["simple","melee","1d8","piercing","","Thrown","10/30",""],
996}
997
998/** Where SKILLS is printed: XPHB, Proficiency > Skill Proficiencies, the Skills table. */
999export const SKILLS_CITE = 'XPHB p.14'
1000
1001/** Each skill, lower-cased, to the ability it is checked with. */
1002export const SKILLS: Record<string, string> = {
1003"acrobatics":"dex",
1004"animal handling":"wis",
1005"arcana":"int",
1006"athletics":"str",
1007"deception":"cha",
1008"history":"int",
1009"insight":"wis",
1010"intimidation":"cha",
1011"investigation":"int",
1012"medicine":"wis",
1013"nature":"int",
1014"perception":"wis",
1015"performance":"cha",
1016"persuasion":"cha",
1017"religion":"int",
1018"sleight of hand":"dex",
1019"stealth":"dex",
1020"survival":"wis",
1021}
1022