diff --git a/README.md b/README.md index 1789ff5..6db59fb 100644 --- a/README.md +++ b/README.md @@ -40,9 +40,29 @@ including a character sheet or an encounter) and **Account**. - The **🧙 character button** is on every page (floating at the bottom right on a wide screen). It opens a panel with your character's numbers and everything they hold; the DM can open it for any character. -- The campaign page and the character sheet are long, so each starts with a - row of **section links** (Characters, Encounters, NPCs, Monsters...) that - jump straight to that part of the page. +- The **campaign page shows one part at a time**, picked from a row of + buttons under its name: Overview (characters and encounters), NPCs, + Locations, Weapons, Items, Spells, Monsters, Notes and Settings for the DM; + Overview, Places and Notes for a player. Each button shows how many things + are in that part. On a phone the row is one line that scrolls sideways. The + part showing is in the address (`?view=weapons`), so it can be bookmarked + and the back button steps through the parts. +- **Search this campaign**, the box above that row, looks through everything + that has been added to the campaign at once: characters, encounters, + locations and notes, and for the DM also NPCs, weapons, items, spells and + monsters. It matches names and descriptions, every word typed, in any + order. A result opens that thing. Each of the DM's lists also has a search + box of its own. +- The DM's lists (NPCs, weapons, items, spells, monsters) are short rows: a + name and a few words. **Clicking a row opens a pop-out** with everything + about it and everything that can be changed. Adding one, by hand or from the + library, is a pop-out too. A pop-out is a window over the page on a wide + screen and the whole screen on a phone; ✕, Escape or a click outside it + closes it. +- Every paged list has Prev and Next, and with three pages or more the page + number is a menu to **jump straight to any page**. +- The character sheet is long, so it starts with a row of **section links** + that jump straight to that part of the page. - On a small screen every table (weapons, items, spells, monsters, the party overview) is shown as a stack of cards, one per row, with each figure labelled, and rows of controls wrap rather than run off the side. diff --git a/backend/package.json b/backend/package.json index 4cd1d83..2160c9b 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "backend", - "version": "1.12.3", + "version": "1.13.0", "private": true, "type": "commonjs", "main": "src/index.js", diff --git a/docs/CHARACTERS.md b/docs/CHARACTERS.md index dda4567..46ee621 100644 --- a/docs/CHARACTERS.md +++ b/docs/CHARACTERS.md @@ -421,7 +421,9 @@ calculations but is only ever set if the DM supplies it during step 5. ## 10. Gear pools, starting options and gear levels -Each campaign has three **pools**, managed by the DM on the campaign page: +Each campaign has three **pools**, managed by the DM on the campaign page, +each in a part of its own ("Weapons", "Items", "Spells") where every entry +opens in a pop-out: | Pool | What an entry holds | How entries are added | |---|---|---| @@ -666,7 +668,7 @@ character in the same campaign. | Screen | What it shows | |---|---| -| Campaign page | Character list: species, class, level, HP, AC, location. A player's own characters are under "Your Characters" and nowhere else; "Rest of the Party" is everyone else's. | +| Campaign page | On its "Overview". Character list: species, class, level, HP, AC, location. A player's own characters are under "Your Characters" and nowhere else; "Rest of the Party" is everyone else's. | | Party overview | One table of every character with an HP bar, AC, gold and location. A player's own characters are highlighted and marked "★ Yours". | | Character sheet | Everything in this document. | | Character builder | A character that is still being built (section 2). | diff --git a/docs/ENCOUNTERS.md b/docs/ENCOUNTERS.md index 4d18d37..5e75049 100644 --- a/docs/ENCOUNTERS.md +++ b/docs/ENCOUNTERS.md @@ -77,18 +77,20 @@ characters are at that location: beginning it, changing its location, or adding a character to it moves them there. Each place a character is moved to (this way or by the DM on the sheet) is remembered, and a player can see only the locations one of their own characters has been to — on the campaign page -under "Places You've Been", and on the encounter itself. Archiving or deleting +under "Places", and on the encounter itself. Archiving or deleting the encounter does not take a visited place away again. ### Order, archive and delete -**Order.** The campaign page lists encounters in the **campaign order**, which +**Order.** The campaign page lists encounters on its "Overview", under the +characters, in the **campaign order**, which the DM arranges with the ▲ and ▼ buttons and everyone sees. A new encounter goes to the top. The "Sort by" menu re-sorts the list by name, status, type or date instead; that choice is remembered per browser and changes nothing for anyone else. ▲ and ▼ only show while sorting by campaign order. -The list shows **ten encounters a page**, with Prev and Next beneath it, and +The list shows **ten encounters a page**, with Prev and Next beneath it (and, +with three pages or more, a menu to jump to any page), and the DM's archived list is paged the same way. The order runs on across pages: moving the last encounter on a page down carries it to the top of the next. @@ -410,8 +412,8 @@ when there is something to trade, and always for the DM in a quest. holds at the level it is sold at, and uses up stock. A character below that level holds it but cannot use it yet. - Every trade is written to the character's money log. -- **An NPC's rate and wares are set on the campaign page**, under "Trade" on - the NPC's row, and follow the NPC into every quest they are in. **An +- **An NPC's rate and wares are set on the campaign page**, in the NPC's + pop-out, and follow the NPC into every quest they are in. **An encounter's own wares are set here**, in the DM's part of the card, and exist only in this encounter: a market stall, a vending machine, a chest with a price tag. diff --git a/docs/ITEMS.md b/docs/ITEMS.md index c485227..ca162de 100644 --- a/docs/ITEMS.md +++ b/docs/ITEMS.md @@ -36,7 +36,11 @@ level up the same way weapons do), [SPELLS.md](SPELLS.md), ## 2. The item pool -The pool is the "Items Pool" card on the campaign page (DM only). +The pool is the "Items" part of the campaign page (DM only). It lists each +item as a short row: its name, then what it does, its dice and its +description, as far as they fit on a line. The list has a search box, shows +ten to a page, and clicking a row opens the item's **pop-out**, which shows +everything below and is where it is changed. | Field | What it is | |---|---| @@ -48,21 +52,23 @@ The pool is the "Items Pool" card on the campaign page (DM only). | Starting option | Whether a brand-new character may pick it in the builder (section 6) | | Effects | What it does to whoever has it equipped: bonuses and penalties to the sheet's numbers, and a note (section 5) | -- **Adding:** by hand with the "+ Add Item" form, or with "📚 From Library", - which offers 32 ready-made items: light, medium and heavy armor, shields, +- **Adding:** by hand with "+ Add Item", or with "📚 From Library". Both open + in a pop-out; an item added by hand opens its own pop-out straight away, to + set what it does. The library offers 32 ready-made items: light, medium and heavy armor, shields, worn gear such as a Ring of Protection, and common supplies. Each is copied into the pool with its effects already set (Chain Mail: +6 AC, −10 Speed, and a note about Stealth), at starting level 1 and not ticked as a starting option. The copy is yours to change. The full list is in section 10. Each can be added once: an item the pool already has by that name is left out of the library list, and comes back if the pool's item is renamed or deleted. -- **Effects:** the "Effects" button on an item's row. The row shows what the - item does under its name. +- **Effects:** under "While equipped" in the item's pop-out, saved with "Save + Effects". The item's row shows what it does under its name. - **Changing:** starting level, growth (when the item has dice) and the - starting-option tick box can be changed in the table. Name, description and - dice cannot be changed on screen once created (the API accepts it); remove - and re-add instead. -- **Removing:** the ✕ button. This takes the item out of **every inventory** + starting-option tick box are changed in the pop-out, and saved as they are + changed. Name, description and dice cannot be changed on screen once + created (the API accepts it); remove and re-add instead. +- **Removing:** "Remove from campaign" at the foot of the pop-out, after a + confirmation. This takes the item out of **every inventory** and off every encounter's reward list. There is no undo. ## 3. A character's inventory @@ -188,8 +194,8 @@ plus a **note** for what is not a number ("Disadvantage on Stealth", card lists every item in force with what it is doing, and its note. - **Max HP can move.** If taking something off lowers a character's maximum HP below their current HP, current HP comes down to the new maximum. -- **Only the DM sets effects**, with the "Effects" button on the item's row in - the pool. Changing them changes the sheet of everyone wearing the item, +- **Only the DM sets effects**, under "While equipped" in the item's pop-out + on the campaign page. Changing them changes the sheet of everyone wearing the item, straight away. - The DM also has an **Extra AC** number on each sheet, added on top of gear, for anything an item does not cover. It can be negative. diff --git a/docs/MONSTERS.md b/docs/MONSTERS.md index 2d7c30b..92db5b5 100644 --- a/docs/MONSTERS.md +++ b/docs/MONSTERS.md @@ -50,22 +50,29 @@ from its scores for display only. ## 3. Managing monsters -The list is the "Monsters" card on the campaign page (DM only). +The list is the "Monsters" part of the campaign page (DM only). Each monster +is a short row: its name, challenge rating, AC, HP and attack. The list has a +search box, shows ten to a page, and clicking a row opens the monster's +**pop-out** with its whole stat block. -- **Adding by hand:** "+ Add Monster" opens the whole stat block: name, +- **Adding by hand:** "+ Add Monster" opens a pop-out with the whole stat + block: name, challenge rating, AC, HP, speed, attack bonus, damage, the six ability scores, special trait and notes. Only name, AC and HP must be typed; speed starts at 30, attack bonus at 0 and each ability score at 10. -- **Adding from the bestiary:** "📚 From Library" copies a complete stat block. +- **Adding from the bestiary:** "📚 From Library" opens the bestiary in a + pop-out, and "+ Add" copies a complete stat block. Each monster can be added once: one the campaign already has by that name is left out of the list, and comes back if the campaign's monster is renamed or deleted. -- **Changing:** "Edit" on a monster's row opens the same form filled in. +- **Changing:** "Edit stat block" in a monster's pop-out opens the same form + filled in. Saving changes the template, and copies already in encounters show the new stat block straight away; their current HP is left alone. -- The list shows each monster's full stat block: the numbers in columns, and - its ability scores, trait and notes under its name. -- **Removing:** the ✕ button, after a confirmation. Copies +- The pop-out shows the full stat block: the numbers, the six ability scores, + the trait and the notes. +- **Removing:** "Remove from campaign" at the foot of the pop-out, after a + confirmation. Copies already in encounters stay there with their name and HP, but lose their stat block. diff --git a/docs/NPCS.md b/docs/NPCS.md index 540f7f8..cb026c5 100644 --- a/docs/NPCS.md +++ b/docs/NPCS.md @@ -52,18 +52,23 @@ A new NPC is Neutral unless you choose otherwise. ## 3. Managing NPCs -The NPC list is the "NPCs" card on the campaign page (DM only). +The NPC list is the "NPCs" part of the campaign page (DM only). Each NPC is a +short row: name, role, the start of their description, and badges for their +attitude, a 💱 with their exchange rate and a 🛒 with how many things they +have for sale. The list has a search box and shows ten to a page. -- **Adding:** "+ Add NPC" opens a form with every field above except the - exchange rate and wares. Only the name is required. -- **Trade:** the "Trade" button on an NPC's row opens their exchange rate and - their wares (section 5). The row shows a 💱 badge with the rate and a 🛒 - badge with how many things are for sale. +- **The pop-out:** clicking a row opens the NPC's pop-out, with everything + above: description, DM notes, combat stats, and their trade. +- **Adding:** "+ Add NPC" opens a pop-out with every field above except the + exchange rate and wares. Only the name is required. Once added, the NPC's + own pop-out opens, to set their trade. +- **Trade:** the exchange rate and the wares are set in the NPC's pop-out, + under "Changes money" and "For sale" (section 5). - **Changing:** there is no edit form for the other fields. To change them, remove the NPC and add it again (the API accepts changes, but no screen offers them). Removing an NPC removes their wares too. -- **Removing:** the ✕ button, after a confirmation. This also **removes the - NPC from every encounter** it was in. +- **Removing:** "Remove from campaign" at the foot of the pop-out, after a + confirmation. This also **removes the NPC from every encounter** it was in. ## 4. NPCs in encounters @@ -113,7 +118,8 @@ another. - Both sides go on the character's money log, naming the NPC: "Changed with Vex for $45" and "Changed with Vex from 6 gold". - An NPC never runs out of gold or cash to change. -- To set a rate, type both numbers under "Trade" and press "Save rate". +- To set a rate, type both numbers under "Changes money" in the NPC's pop-out + and press "Save rate". "Stop changing money" clears it. An NPC with no rate does not change money. ### Selling diff --git a/docs/SPELLS.md b/docs/SPELLS.md index c587a0e..f26a951 100644 --- a/docs/SPELLS.md +++ b/docs/SPELLS.md @@ -36,7 +36,10 @@ This describes the code as it stands. The built-in list is ## 2. The spell list -The list is the "Spell List" card on the campaign page (DM only). +The list is the "Spells" part of the campaign page (DM only). Each spell is a +short row: its name, level, damage and the start of what it does. The list +has a search box, shows ten to a page, and clicking a row opens the spell's +**pop-out**, which shows everything below and is where it is changed. | Field | What it is | |---|---| @@ -47,15 +50,16 @@ The list is the "Spell List" card on the campaign page (DM only). | Damage | Picked from a list, or "No damage". Fixed; it does not grow | | Starting option | Whether a brand-new character may pick it in the builder (section 8) | | Revives | Whether it brings back the dead. A character who can cast one may revive a dead ally on their turn in a battle ([ENCOUNTERS.md](ENCOUNTERS.md), section 6). Ticked already on the library's Revivify and Raise Dead | -| Casting time, range, duration | Stored for library spells but not shown on any screen | +| Casting time, range, duration | Stored for library spells. Shown to the DM in the spell's pop-out on the campaign page, and nowhere else | A cantrip is a spell of level 0. The app always calls it a **cantrip**, never "level 0" or "level 1". -- **Adding:** by hand with the "+ Add Spell" form (name, level, school, - damage, what it does and the two tick boxes), or from the library. -- **Changing:** damage (the drop-down in the table) and the Revives and - starting-option tick boxes. Name, level, school and description cannot be changed on screen +- **Adding:** by hand with "+ Add Spell" (name, level, school, damage, what + it does and the two tick boxes), or from the library. Both open in a + pop-out. +- **Changing:** in the spell's pop-out: damage (the drop-down) and the Revives + and starting-option tick boxes, saved as they are changed. Name, level, school and description cannot be changed on screen once created (the API accepts it); remove and re-add instead. - **Damage choices:** the drop-down offers "No damage", then 1 to 6, 8 or 10 dice of d4, d6, d8, d10 or d12 (1d4 up to 10d12), plus the three unusual diff --git a/docs/WEAPONS.md b/docs/WEAPONS.md index 44246ae..f95a2da 100644 --- a/docs/WEAPONS.md +++ b/docs/WEAPONS.md @@ -37,7 +37,11 @@ This describes the code as it stands. The formulas live in ## 2. The weapon pool -The pool is the "Weapons Pool" card on the campaign page (DM only). +The pool is the "Weapons" part of the campaign page (DM only). It lists each +weapon as a short row: its name, base damage, starting level and what it does +while equipped. The list has a search box, shows ten to a page, and clicking a +row opens the weapon's **pop-out**, which shows everything below and is where +it is changed. | Field | What it is | |---|---| @@ -48,17 +52,22 @@ The pool is the "Weapons Pool" card on the campaign page (DM only). | Starts at level | 1 to 9. The lowest level this weapon can be (section 5) | | Growth | Standard, Powerful or Legendary: how fast the dice climb per level (section 6) | | Starting option | Whether a brand-new character may pick it in the builder (section 8) | -| Properties, range | Stored for library weapons (light, thrown, 20/60 ft…) but not shown or used anywhere | +| Properties, range | Stored for library weapons (light, thrown, 20/60 ft…). Shown in the weapon's pop-out, and not used anywhere | | Effects | What it does to whoever has it equipped: bonuses and penalties to the sheet's numbers, and a note. Works exactly as for items ([ITEMS.md](ITEMS.md), section 5) | -- **Adding:** by hand with the "+ Add Weapon" form, or from the library. -- **Effects:** the "Effects" button on a weapon's row. A defending blade can - give +1 AC, a heavy maul −5 speed. They count only while the weapon is - equipped, and do not change its own attack or damage. -- **Changing:** starting level, growth and the starting-option tick box can be - changed in the table. Name, damage, type and ability cannot be changed on - screen once created (the API accepts it); remove and re-add instead. -- **Removing:** the ✕ button. This takes the weapon away from **every +- **Adding:** by hand with "+ Add Weapon", or from the library. Both open in + a pop-out. A weapon added by hand opens its own pop-out straight away, to + set what it does. +- **Effects:** under "While equipped" in the weapon's pop-out, saved with + "Save Effects". A defending blade can give +1 AC, a heavy maul −5 speed. + They count only while the weapon is equipped, and do not change its own + attack or damage. +- **Changing:** starting level, growth and the starting-option tick box are + changed in the pop-out, and saved as they are changed. Name, damage, type + and ability cannot be changed on screen once created (the API accepts it); + remove and re-add instead. +- **Removing:** "Remove from campaign" at the foot of the pop-out, after a + confirmation. This takes the weapon away from **every character holding it** and off every encounter's reward list. There is no undo. - The same weapon can be added twice; nothing stops duplicate names. diff --git a/frontend/package.json b/frontend/package.json index 45d6537..6b970a8 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "frontend", "private": true, - "version": "1.12.3", + "version": "1.13.0", "type": "module", "scripts": { "dev": "vite", diff --git a/frontend/src/components/Modal.tsx b/frontend/src/components/Modal.tsx new file mode 100644 index 0000000..bb264e7 --- /dev/null +++ b/frontend/src/components/Modal.tsx @@ -0,0 +1,73 @@ +import { useEffect, useId, useRef, type ReactNode } from 'react'; +import { createPortal } from 'react-dom'; + +// A pop-out over the page: a centred window on a wide screen, the whole +// screen on a phone. Escape, the ✕ and a click outside all close it, and the +// page behind stays where it was. +export function Modal({ + title, + subtitle, + wide, + onClose, + children, +}: { + title: ReactNode; + subtitle?: ReactNode; + wide?: boolean; + onClose: () => void; + children: ReactNode; +}) { + const titleId = useId(); + const windowRef = useRef(null); + // A click only closes if it both started and ended outside the window, so + // dragging to select text in a field never does. + const pressedOutside = useRef(false); + const close = useRef(onClose); + useEffect(() => { + close.current = onClose; + }); + + useEffect(() => { + const opener = document.activeElement as HTMLElement | null; + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape') close.current(); + }; + document.addEventListener('keydown', onKey); + const scroll = document.body.style.overflow; + document.body.style.overflow = 'hidden'; + windowRef.current?.focus(); + return () => { + document.removeEventListener('keydown', onKey); + document.body.style.overflow = scroll; + opener?.focus?.(); + }; + }, []); + + return createPortal( +
{ + pressedOutside.current = e.target === e.currentTarget; + }} + onClick={(e) => { + if (pressedOutside.current && e.target === e.currentTarget) onClose(); + }} + > +
+
+
+

+ {title} +

+ {subtitle &&
{subtitle}
} +
+ +
+
{children}
+
+
, + document.body + ); +} diff --git a/frontend/src/components/Paginated.tsx b/frontend/src/components/Paginated.tsx index df77d0e..1e7f05d 100644 --- a/frontend/src/components/Paginated.tsx +++ b/frontend/src/components/Paginated.tsx @@ -4,11 +4,14 @@ export function Pagination({ pageCount, onPrev, onNext, + onJump, }: { page: number; pageCount: number; onPrev: () => void; onNext: () => void; + // Given this, the page number is a list to pick any page from. + onJump?: (page: number) => void; }) { if (pageCount <= 1) return null; return ( @@ -16,9 +19,23 @@ export function Pagination({ - - Page {page} of {pageCount} - + {onJump && pageCount > 2 ? ( + + ) : ( + + Page {page} of {pageCount} + + )} diff --git a/frontend/src/components/SectionNav.tsx b/frontend/src/components/SectionNav.tsx new file mode 100644 index 0000000..1ab9919 --- /dev/null +++ b/frontend/src/components/SectionNav.tsx @@ -0,0 +1,37 @@ +import { useEffect, useRef } from 'react'; + +export interface Section { + id: string; + label: string; + icon: string; + // How many things are in it, shown beside its name. + count?: number; +} + +// The parts of a page that shows one part at a time. A row of buttons on a +// wide screen; on a phone a single line that scrolls sideways, with the +// current part kept in view. +export function SectionNav({ sections, current, onSelect }: { sections: Section[]; current: string; onSelect: (id: string) => void }) { + const currentRef = useRef(null); + useEffect(() => { + currentRef.current?.scrollIntoView({ block: 'nearest', inline: 'center' }); + }, [current]); + + return ( + + ); +} diff --git a/frontend/src/components/campaign/CampaignSearch.tsx b/frontend/src/components/campaign/CampaignSearch.tsx new file mode 100644 index 0000000..16f33fb --- /dev/null +++ b/frontend/src/components/campaign/CampaignSearch.tsx @@ -0,0 +1,55 @@ +import type { ReactNode } from 'react'; +import { EntryRow } from './parts'; + +export interface SearchHit { + key: string; + title: string; + detail?: ReactNode; + badges?: ReactNode; + // Where it goes: a page of its own, or whatever `onPick` opens. + to?: string; + onPick?: () => void; +} + +export interface SearchGroup { + label: string; + icon: string; + hits: SearchHit[]; +} + +// More than this of one kind and the rest are counted, not listed. +const SHOWN_PER_GROUP = 12; + +// Everything in the campaign that a search found, a kind at a time. +export function CampaignSearch({ query, groups }: { query: string; groups: SearchGroup[] }) { + const found = groups.filter((g) => g.hits.length > 0); + const total = found.reduce((sum, g) => sum + g.hits.length, 0); + + return ( +
+
+ + {total} {total === 1 ? 'result' : 'results'} for "{query}" + +
+ {total === 0 &&

Nothing in this campaign matches. Try fewer words, or part of a name.

} + {found.map((group) => ( +
+
+ {group.icon} {group.label} ({group.hits.length}) +
+
+ {group.hits.slice(0, SHOWN_PER_GROUP).map((hit) => ( + + ))} +
+ {group.hits.length > SHOWN_PER_GROUP && ( +

+ …and {group.hits.length - SHOWN_PER_GROUP} more. Add a word to narrow it down. +

+ )} +
+ ))} +
+ ); +} diff --git a/frontend/src/components/campaign/EntryDetail.tsx b/frontend/src/components/campaign/EntryDetail.tsx new file mode 100644 index 0000000..0ec877a --- /dev/null +++ b/frontend/src/components/campaign/EntryDetail.tsx @@ -0,0 +1,347 @@ +import { useState, type ReactNode } from 'react'; +import { useDeleteMonster, useDeletePoolEntry, usePatchPoolEntry, useUpdateMonster } from '../../api/queries'; +import { Modal } from '../Modal'; +import { NumberInput } from '../NumberInput'; +import { ErrorBanner } from '../Spinner'; +import { EffectsEditor } from '../EffectsEditor'; +import { WaresEditor } from '../Wares'; +import { extractErrorMessage, fmtMod, spellLevelLabel, spellRequirementLabel } from '../../lib/format'; +import { abilityLine, rateLabel, type EntryRef } from '../../lib/campaignEntries'; +import { Field, MonsterForm, ScalingSelect, SpellDamageSelect, StartLevelSelect } from './parts'; +import type { GearEffect, Item, Monster, Npc, Spell, Weapon } from '../../api/types'; + +const ATTACK_ABILITY_LABELS: Record = { STR: 'STR', DEX: 'DEX', FINESSE: 'Finesse (the better of STR and DEX)' }; + +function Chip({ label, children }: { label: string; children: ReactNode }) { + return ( +
+ {label} + {children} +
+ ); +} + +// The foot of every pop-out: taking the thing out of the campaign. +function RemoveButton({ name, warning, pending, onRemove }: { name: string; warning: string; pending: boolean; onRemove: () => void }) { + return ( +
+ +
+ ); +} + +// A weapon or an item: the two share levels, growth and effects. +function GearDetail({ campaignId, pool, entry, onClose }: { campaignId: string; pool: 'weapons' | 'items'; entry: Weapon | Item; onClose: () => void }) { + const patch = usePatchPoolEntry(campaignId, pool); + const remove = useDeletePoolEntry(campaignId, pool); + const [effects, setEffects] = useState(entry.effects ?? []); + const [note, setNote] = useState(entry.effectNote ?? ''); + const [effectsSaved, setEffectsSaved] = useState(false); + const [error, setError] = useState(null); + const onError = (err: unknown) => setError(extractErrorMessage(err)); + const weapon = 'damageType' in entry ? entry : null; + + return ( + + {error && } +
+ {weapon ? ( + <> + + {weapon.damageDice} {weapon.damageType} + + {ATTACK_ABILITY_LABELS[weapon.attackAbility]} + {weapon.rangeNormal && ( + + {weapon.rangeNormal} + {weapon.rangeLong ? `/${weapon.rangeLong}` : ''} ft + + )} + {weapon.properties.length > 0 && {weapon.properties.join(', ')}} + + ) : ( + entry.damageDice && {entry.damageDice} + )} +
+ {!weapon && 'description' in entry && entry.description &&

{entry.description}

} + +
+ + {(id) => patch.mutate({ id: entry.id, minLevel }, { onError })} />} + + {entry.damageDice && ( + + {(id) => patch.mutate({ id: entry.id, damageScaling }, { onError })} />} + + )} +
+

+ A character must be at least its level to use it. + {entry.damageDice && + ' The dice above are what it does at the level it starts at. When you level up a character\'s copy they grow one small step per level (1d4 → 1d6 → 1d8 → 1d10 → 1d12 → 2d6 → …): two steps for Powerful gear, three for Legendary.'} +

+ + +
While equipped
+

+ These count for a character only while it is equipped and they are high enough level to use it. Armor is an item with + +AC; a penalty is a negative number. +

+ { + setEffects(nextEffects); + setNote(nextNote); + setEffectsSaved(false); + }} + /> +
+ + {effectsSaved && Saved.} +
+ + remove.mutate(entry.id, { onError, onSuccess: onClose })} /> +
+ ); +} + +function SpellDetail({ campaignId, spell, onClose }: { campaignId: string; spell: Spell; onClose: () => void }) { + const patch = usePatchPoolEntry(campaignId, 'spells'); + const remove = useDeletePoolEntry(campaignId, 'spells'); + const [error, setError] = useState(null); + const onError = (err: unknown) => setError(extractErrorMessage(err)); + + return ( + + {error && } +
+ {spell.castingTime && {spell.castingTime}} + {spell.range && {spell.range}} + {spell.duration && {spell.duration}} +
+

{spell.description || 'No description.'}

+ +
+ + {(id) => patch.mutate({ id: spell.id, damageDice }, { onError })} />} + +
+ + + + remove.mutate(spell.id, { onError, onSuccess: onClose })} /> +
+ ); +} + +function MonsterDetail({ campaignId, monster, onClose }: { campaignId: string; monster: Monster; onClose: () => void }) { + const update = useUpdateMonster(campaignId); + const remove = useDeleteMonster(campaignId); + const [editing, setEditing] = useState(false); + const [error, setError] = useState(null); + const onError = (err: unknown) => setError(extractErrorMessage(err)); + + return ( + + {error && } + {editing ? ( + setEditing(false)} + onSave={async (stats) => { + setError(null); + try { + await update.mutateAsync({ id: monster.id, ...stats }); + setEditing(false); + } catch (err) { + onError(err); + throw err; + } + }} + /> + ) : ( + <> +
+ {monster.challengeRating || '—'} + {monster.ac} + {monster.maxHp} + {monster.speed} + {fmtMod(monster.attackBonus)} + {monster.damageDice || '—'} +
+

{abilityLine(monster)}

+ {monster.specialTrait && ( +

+ Trait: {monster.specialTrait} +

+ )} + {monster.notes &&

{monster.notes}

} + + remove.mutate(monster.id, { onError, onSuccess: onClose })} + /> + + )} +
+ ); +} + +// An NPC: who they are, and what they trade — the rate they change gold and +// cash at, and their wares. Players meet both on the encounter page, in a +// quest the NPC is part of. +function NpcDetail({ campaignId, npc, weapons, items, onClose }: { campaignId: string; npc: Npc; weapons: Weapon[]; items: Item[]; onClose: () => void }) { + const patch = usePatchPoolEntry(campaignId, 'npcs'); + const remove = useDeletePoolEntry(campaignId, 'npcs'); + const [gold, setGold] = useState(npc.exchangeGold ? String(npc.exchangeGold) : ''); + const [cash, setCash] = useState(npc.exchangeCash ? String(npc.exchangeCash) : ''); + const [error, setError] = useState(null); + const onError = (err: unknown) => setError(extractErrorMessage(err)); + const rate = rateLabel(npc); + const hasStats = npc.ac !== null || npc.maxHp !== null || npc.attackBonus !== null || Boolean(npc.damageDice); + + return ( + + {npc.role || 'NPC'} + {npc.disposition} + {rate && 💱 {rate}} + + } + wide + onClose={onClose} + > + {error && } + {npc.description ?

{npc.description}

:

No description for the players.

} + {npc.dmNotes &&

🔒 {npc.dmNotes}

} + {hasStats && ( +
+ {npc.ac !== null && {npc.ac}} + {npc.maxHp !== null && {npc.maxHp}} + {npc.attackBonus !== null && {fmtMod(npc.attackBonus)}} + {npc.damageDice && {npc.damageDice}} +
+ )} + +
Changes money
+

+ Set a rate and the party can change gold into cash, or cash into gold, with {npc.name}. Silver and copper are not + taken. Leave it empty for someone who does not change money. +

+
+ setGold(e.target.value)} style={{ width: 90 }} /> + gold = + $ + setCash(e.target.value)} style={{ width: 90 }} /> + + {rate && ( + + )} +
+ +
For sale
+ + + remove.mutate(npc.id, { onError, onSuccess: onClose })} + /> +
+ ); +} + +// The pop-out for whichever weapon, item, spell, monster or NPC is open. +// Nothing shows if it is no longer in the campaign. +export function EntryDetail({ + campaignId, + entry, + weapons, + items, + spells, + monsters, + npcs, + onClose, +}: { + campaignId: string; + entry: EntryRef; + weapons: Weapon[]; + items: Item[]; + spells: Spell[]; + monsters: Monster[]; + npcs: Npc[]; + onClose: () => void; +}) { + const find = (list: T[]) => list.find((e) => e.id === entry.id); + switch (entry.kind) { + case 'weapon': { + const weapon = find(weapons); + return weapon ? : null; + } + case 'item': { + const item = find(items); + return item ? : null; + } + case 'spell': { + const spell = find(spells); + return spell ? : null; + } + case 'monster': { + const monster = find(monsters); + return monster ? : null; + } + case 'npc': { + const npc = find(npcs); + return npc ? : null; + } + } +} diff --git a/frontend/src/components/campaign/PoolSections.tsx b/frontend/src/components/campaign/PoolSections.tsx new file mode 100644 index 0000000..8073310 --- /dev/null +++ b/frontend/src/components/campaign/PoolSections.tsx @@ -0,0 +1,585 @@ +import { useState, type FormEvent, type ReactNode } from 'react'; +import { + useAddItemFromLibrary, + useAddMonsterFromLibrary, + useAddSpellFromLibrary, + useAddWeaponFromLibrary, + useCampaignLibrary, + useCreateItem, + useCreateMonster, + useCreateNpc, + useCreateSpell, + useCreateWeapon, +} from '../../api/queries'; +import { Modal } from '../Modal'; +import { NumberInput } from '../NumberInput'; +import { ErrorBanner, Spinner } from '../Spinner'; +import { effectsSummary } from '../../lib/gear'; +import { extractErrorMessage, fmtMod, spellLevelLabel, spellRequirementLabel } from '../../lib/format'; +import { MAX_GEAR_LEVEL } from '../../lib/previewCalc'; +import { abilityLine, rateLabel, type EntryRef } from '../../lib/campaignEntries'; +import { EntryList, Field, LibraryPicker, MonsterForm, ScalingSelect, SpellDamageSelect, StartLevelSelect } from './parts'; +import type { CampaignLibrary, Item, LibraryItem, LibraryMonster, LibrarySpell, LibraryWeapon, Monster, Npc, NpcDisposition, Spell, Weapon } from '../../api/types'; + +interface SectionProps { + campaignId: string; + entries: T[] | undefined; + onOpen: (entry: EntryRef) => void; +} + +// Which of a list's two "add" pop-outs is open: the form, or the library. +type Adding = 'form' | 'library' | null; + +function SectionCard({ + title, + addLabel, + hasLibrary = true, + onAdd, + intro, + children, +}: { + title: string; + addLabel: string; + hasLibrary?: boolean; + onAdd: (adding: Adding) => void; + intro: ReactNode; + children: ReactNode; +}) { + return ( +
+
+ {title} +
+ {hasLibrary && ( + + )} + +
+
+

+ {intro} +

+ {children} +
+ ); +} + +// The built-in library in a pop-out. It is a large download, so it is only +// asked for once one of these is opened. +function LibraryModal({ + campaignId, + title, + pick, + taken, + adding, + onAdd, + placeholder, + renderMeta, + renderDetail, + error, + onClose, +}: { + campaignId: string; + title: string; + pick: (library: CampaignLibrary) => T[]; + taken: { name: string }[] | undefined; + adding: boolean; + onAdd: (key: string) => void; + placeholder: string; + renderMeta: (item: T) => string; + renderDetail?: (item: T) => string | null; + error: string | null; + onClose: () => void; +}) { + const { data: library, isError } = useCampaignLibrary(campaignId); + return ( + + {error && } + {isError && } + {!library && !isError && } + {library && ( + items={pick(library)} taken={taken} adding={adding} onAdd={onAdd} placeholder={placeholder} renderMeta={renderMeta} renderDetail={renderDetail} /> + )} + + ); +} + +const StartingOption = () => ( + +); + +const startingBadge = (entry: { isStartingOption: boolean }) => entry.isStartingOption && Starting; + +export function WeaponsSection({ campaignId, entries, onOpen }: SectionProps) { + const createWeapon = useCreateWeapon(campaignId); + const addFromLibrary = useAddWeaponFromLibrary(campaignId); + const [adding, setAdding] = useState(null); + const [error, setError] = useState(null); + const open = (next: Adding) => { + setError(null); + setAdding(next); + }; + + async function handleSubmit(e: FormEvent) { + e.preventDefault(); + const fd = new FormData(e.target as HTMLFormElement); + setError(null); + try { + const weapon = await createWeapon.mutateAsync({ + name: String(fd.get('name')).trim(), + damageDice: String(fd.get('damageDice')).trim(), + damageType: String(fd.get('damageType')).trim(), + attackAbility: fd.get('attackAbility') as Weapon['attackAbility'], + properties: [], + rangeNormal: null, + rangeLong: null, + damageScaling: Number(fd.get('damageScaling')), + minLevel: Number(fd.get('minLevel')), + isStartingOption: fd.get('isStartingOption') === 'on', + effects: [], + effectNote: null, + }); + setAdding(null); + onOpen({ kind: 'weapon', id: weapon.id }); + } catch (err) { + setError(extractErrorMessage(err)); + } + } + + return ( + + The weapons you hand out on each character's sheet. Open one to set the level it starts at, how fast its damage grows + (levels 1–{MAX_GEAR_LEVEL}), whether a new character may start with it, and what it does while equipped. + + } + > + [w.name, w.damageDice, w.damageType, effectsSummary(w.effects, w.effectNote)]} + renderMeta={(w) => [`${w.damageDice} ${w.damageType}`, `Lv ${w.minLevel}`, effectsSummary(w.effects, w.effectNote) && `✦ ${effectsSummary(w.effects, w.effectNote)}`].filter(Boolean).join(' · ')} + renderBadges={startingBadge} + onOpen={(id) => onOpen({ kind: 'weapon', id })} + /> + {adding === 'library' && ( + + campaignId={campaignId} + title="Weapon library" + pick={(library) => library.weapons} + taken={entries} + adding={addFromLibrary.isPending} + onAdd={(key) => addFromLibrary.mutate(key, { onError: (err) => setError(extractErrorMessage(err)) })} + placeholder="Search the weapon library…" + renderMeta={(w) => `${w.category} · ${w.damageDice} ${w.damageType} · starts at level 1`} + renderDetail={(w) => effectsSummary(w.effects, w.effectNote)} + error={error} + onClose={() => setAdding(null)} + /> + )} + {adding === 'form' && ( + setAdding(null)}> + {error && } +
+
+ {(id) => } + {(id) => } + {(id) => } + + {(id) => ( + + )} + + {(id) => } + {(id) => } + +
+ +
+
+ )} +
+ ); +} + +export function ItemsSection({ campaignId, entries, onOpen }: SectionProps) { + const createItem = useCreateItem(campaignId); + const addFromLibrary = useAddItemFromLibrary(campaignId); + const [adding, setAdding] = useState(null); + const [error, setError] = useState(null); + const open = (next: Adding) => { + setError(null); + setAdding(next); + }; + + async function handleSubmit(e: FormEvent) { + e.preventDefault(); + const fd = new FormData(e.target as HTMLFormElement); + setError(null); + try { + const item = await createItem.mutateAsync({ + name: String(fd.get('name')).trim(), + description: String(fd.get('description') || '').trim() || null, + damageDice: String(fd.get('damageDice') || '').trim() || null, + damageScaling: Number(fd.get('damageScaling')), + minLevel: Number(fd.get('minLevel')), + isStartingOption: fd.get('isStartingOption') === 'on', + effects: [], + effectNote: null, + }); + setAdding(null); + onOpen({ kind: 'item', id: item.id }); + } catch (err) { + setError(extractErrorMessage(err)); + } + } + + return ( + + Rope, potions, armor, quest items. Armor, shields, rings and the like are items with effects: open the item and set + what it does while equipped (chain mail: +6 AC, −10 Speed). + + } + > + [i.name, i.description, i.damageDice, effectsSummary(i.effects, i.effectNote)]} + renderMeta={(i) => [effectsSummary(i.effects, i.effectNote) && `✦ ${effectsSummary(i.effects, i.effectNote)}`, i.damageDice, i.description].filter(Boolean).join(' · ') || `Lv ${i.minLevel}`} + renderBadges={startingBadge} + onOpen={(id) => onOpen({ kind: 'item', id })} + /> + {adding === 'library' && ( + + campaignId={campaignId} + title="Item library" + pick={(library) => library.items} + taken={entries} + adding={addFromLibrary.isPending} + onAdd={(key) => addFromLibrary.mutate(key, { onError: (err) => setError(extractErrorMessage(err)) })} + placeholder="Search the item library: armor, shields, worn gear, supplies…" + renderMeta={(i) => [i.category, effectsSummary(i.effects, i.effectNote), i.damageDice].filter(Boolean).join(' · ')} + renderDetail={(i) => i.description} + error={error} + onClose={() => setAdding(null)} + /> + )} + {adding === 'form' && ( + setAdding(null)}> + {error && } +
+
+ {(id) => } + {(id) => } + + {(id) => } + + {(id) => } + {(id) => } + +
+ +
+
+ )} +
+ ); +} + +export function SpellsSection({ campaignId, entries, onOpen }: SectionProps) { + const createSpell = useCreateSpell(campaignId); + const addFromLibrary = useAddSpellFromLibrary(campaignId); + const [adding, setAdding] = useState(null); + const [error, setError] = useState(null); + const open = (next: Adding) => { + setError(null); + setAdding(next); + }; + + async function handleSubmit(e: FormEvent) { + e.preventDefault(); + const fd = new FormData(e.target as HTMLFormElement); + setError(null); + try { + const spell = await createSpell.mutateAsync({ + name: String(fd.get('name')).trim(), + level: Number(fd.get('level')), + school: String(fd.get('school') || '').trim() || null, + castingTime: null, + range: null, + duration: null, + description: String(fd.get('description') || '').trim() || null, + damageDice: String(fd.get('damageDice') || '') || null, + isStartingOption: fd.get('isStartingOption') === 'on', + revives: fd.get('revives') === 'on', + }); + setAdding(null); + onOpen({ kind: 'spell', id: spell.id }); + } catch (err) { + setError(extractErrorMessage(err)); + } + } + + return ( + + [s.name, s.school, s.description, spellLevelLabel(s.level)]} + renderMeta={(s) => [spellLevelLabel(s.level), s.damageDice && `${s.damageDice} damage`, s.description].filter(Boolean).join(' · ')} + renderBadges={(s) => ( + <> + {s.revives && Revives} + {startingBadge(s)} + + )} + onOpen={(id) => onOpen({ kind: 'spell', id })} + /> + {adding === 'library' && ( + + campaignId={campaignId} + title="Spell library" + pick={(library) => library.spells} + taken={entries} + adding={addFromLibrary.isPending} + onAdd={(key) => addFromLibrary.mutate(key, { onError: (err) => setError(extractErrorMessage(err)) })} + placeholder="Search the spell library…" + renderMeta={(s) => + [spellLevelLabel(s.level), spellRequirementLabel(s.level), s.damageDice ? `${s.damageDice} damage` : 'no damage', s.school].filter(Boolean).join(' · ') + } + renderDetail={(s) => s.description} + error={error} + onClose={() => setAdding(null)} + /> + )} + {adding === 'form' && ( + setAdding(null)}> + {error && } +
+
+ {(id) => } + + {(id) => ( + + )} + + {(id) => } + {(id) => } + + {(id) => } + + + +
+ +
+
+ )} +
+ ); +} + +export function MonstersSection({ campaignId, entries, onOpen }: SectionProps) { + const createMonster = useCreateMonster(campaignId); + const addFromLibrary = useAddMonsterFromLibrary(campaignId); + const [adding, setAdding] = useState(null); + const [error, setError] = useState(null); + const open = (next: Adding) => { + setError(null); + setAdding(next); + }; + + return ( + + [m.name, m.challengeRating && `CR ${m.challengeRating}`, m.specialTrait, m.notes]} + renderMeta={(m) => `CR ${m.challengeRating || '—'} · AC ${m.ac} · HP ${m.maxHp} · attack ${fmtMod(m.attackBonus)}${m.damageDice ? ` for ${m.damageDice}` : ''}`} + onOpen={(id) => onOpen({ kind: 'monster', id })} + /> + {adding === 'library' && ( + + campaignId={campaignId} + title="Monster library" + pick={(library) => library.monsters} + taken={entries} + adding={addFromLibrary.isPending} + onAdd={(key) => addFromLibrary.mutate(key, { onError: (err) => setError(extractErrorMessage(err)) })} + placeholder="Search the monster library…" + renderMeta={(m) => + `CR ${m.challengeRating ?? '—'} · AC ${m.ac} · HP ${m.maxHp} · speed ${m.speed} · attack ${fmtMod(m.attackBonus)}${m.damageDice ? ` for ${m.damageDice}` : ''} · ${abilityLine(m)}` + } + renderDetail={(m) => [m.specialTrait, m.notes].filter(Boolean).join(' — ') || null} + error={error} + onClose={() => setAdding(null)} + /> + )} + {adding === 'form' && ( + setAdding(null)}> + {error && } + { + setError(null); + try { + const monster = await createMonster.mutateAsync(stats); + setAdding(null); + onOpen({ kind: 'monster', id: monster.id }); + } catch (err) { + setError(extractErrorMessage(err)); + throw err; + } + }} + /> + + )} + + ); +} + +export function NpcsSection({ campaignId, entries, onOpen }: SectionProps) { + const createNpc = useCreateNpc(campaignId); + const [adding, setAdding] = useState(null); + const [error, setError] = useState(null); + const open = (next: Adding) => { + setError(null); + setAdding(next); + }; + + async function handleSubmit(e: FormEvent) { + e.preventDefault(); + const fd = new FormData(e.target as HTMLFormElement); + const text = (key: string) => String(fd.get(key) || '').trim() || null; + const num = (key: string) => (fd.get(key) ? Number(fd.get(key)) : null); + setError(null); + try { + const npc = await createNpc.mutateAsync({ + name: String(fd.get('name')).trim(), + role: text('role'), + disposition: fd.get('disposition') as NpcDisposition, + description: text('description'), + dmNotes: text('dmNotes'), + ac: num('ac'), + maxHp: num('maxHp'), + attackBonus: num('attackBonus'), + damageDice: text('damageDice'), + }); + setAdding(null); + onOpen({ kind: 'npc', id: npc.id }); + } catch (err) { + setError(extractErrorMessage(err)); + } + } + + return ( + + [n.name, n.role, n.disposition, n.description, n.dmNotes]} + renderMeta={(n) => [n.role, n.description].filter(Boolean).join(' · ')} + renderBadges={(n) => ( + <> + {rateLabel(n) && 💱 {rateLabel(n)}} + {(n.wares?.length ?? 0) > 0 && 🛒 {n.wares?.length}} + {n.disposition} + + )} + onOpen={(id) => onOpen({ kind: 'npc', id })} + /> + {adding === 'form' && ( + setAdding(null)}> + {error && } +
+
+ {(id) => } + {(id) => } + + {(id) => ( + + )} + +
+ + {(id) =>