diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 1480902f..c7c6cb0d 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased ### Added +- **Tests only:** the UI flow tests in `src/Ui/e2e/` are split by feature (the 69 tests of `flow.e2e.tsx` into eight files, the 13 of `forms.e2e.tsx` into two, shared helpers in `helpers.tsx`); no test changed and no file is over 800 lines. The e2e files now run one after another against the shared DevHost. No app change. - **Release assets:** each release now includes two CycloneDX software bills of materials, `tomestack-X.Y.Z-nuget.cdx.json` (the .NET packages) and `tomestack-X.Y.Z-npm.cdx.json` (the UI's npm runtime packages). They are listed in `SHA256SUMS` and attested like the installer (D101). No app change. - **Content schema 13: creation guides and packs, engine only (D97, D98, [ADR-024](decisions/ADR-024-content-v13.md)):** content can now carry a creation guide for a class or background (starting equipment as picks and options, and primary abilities) and packs (an item that lists what it contains). The change adds the format, validation, kit expansion and a catalogue lookup; the bundled guides and gear are listed below. The one change a player can see is in saving for an older TomeStack. Characters never pin a guide. Saving for an older TomeStack leaves guides out, drops what a pack contains, and turns plain gear that release does not have into a custom item (the save is blocked if that would pass 50 custom items, if a quantity is outside 1 to 9,999, or if an item's name is blank or over 80 characters). A source pack or campaign pack that would hold only guides cannot be saved for an older TomeStack; a library backup is unaffected. Older versions refuse v13 content. - **Easier to find your way around (D94):** the sidebar is grouped into Characters, Library and App. "+ Add a character" opens one screen with three ways in: make a new one, open a TomeStack file, or read a character sheet (PDF or text). Add-ons moved into Settings. The "TomeStack, your characters" button at the top takes you home. Every screen has one main heading, and the window title names where you are (a character's name shows in the taskbar). Esc closes an open "Why?"-style detail or the sidebar and never changes screen. In a narrow window, opening a character sheet tucks the sidebar away without changing your saved choice. diff --git a/docs/decisions/ADR-014-sheet-tabs.md b/docs/decisions/ADR-014-sheet-tabs.md index ee7e4986..aa99d09b 100644 --- a/docs/decisions/ADR-014-sheet-tabs.md +++ b/docs/decisions/ADR-014-sheet-tabs.md @@ -8,7 +8,7 @@ Note (2026-11-15): D96 (Wave 3 Group 4) replaced the Manage tab with the header' ## Context -The character sheet (`src/Ui/src/components/CharacterSheet.tsx`) was one page of about 25 sections, with the admin panels at the top and the core numbers at the bottom in collapsed field cards. The owner asked for a summary area with focused pages below, as paper sheets and other digital sheets have. SPEC P-03 forbids mimicking D&D Beyond's trade dress. There is no router: `App.tsx` keeps one `screen` in state, and the sheet is keyed by character so every play action replaces the view in place. The e2e flow (`src/Ui/e2e/flow.e2e.tsx`) queries every section by role and name and asserts focus on the sheet heading, on the gap-note text box after "Report a gap", and on buttons after Archive, Snapshot and Print. +The character sheet (`src/Ui/src/components/CharacterSheet.tsx`) was one page of about 25 sections, with the admin panels at the top and the core numbers at the bottom in collapsed field cards. The owner asked for a summary area with focused pages below, as paper sheets and other digital sheets have. SPEC P-03 forbids mimicking D&D Beyond's trade dress. There is no router: `App.tsx` keeps one `screen` in state, and the sheet is keyed by character so every play action replaces the view in place. The e2e flow (`src/Ui/e2e/*.e2e.tsx`) queries every section by role and name and asserts focus on the sheet heading, on the gap-note text box after "Report a gap", and on buttons after Archive, Snapshot and Print. ## Decision diff --git a/docs/decisions/ADR-018-play-mechanics.md b/docs/decisions/ADR-018-play-mechanics.md index 3fb89b49..e810bb37 100644 --- a/docs/decisions/ADR-018-play-mechanics.md +++ b/docs/decisions/ADR-018-play-mechanics.md @@ -46,5 +46,5 @@ The engine is built in slices. Each slice is complete and tested before the next ## Evidence -- `tests/RulesCore.Tests/ToggleGroupTests.cs`, `ToggleGroupValidationTests.cs` and `Properties/ToggleGroupProperties.cs` (resolution, calculation, validation), `tests/AppService.Tests/ToggleGroupCommandTests.cs` (atomic switch, cost, refusals) and `SourcePackTests.cs` (references), `src/Ui/src/components/FormGroups.test.tsx`, `src/Ui/src/undo.test.ts`, and the e2e flow in `src/Ui/e2e/forms.e2e.tsx`. Fixture: `tests/RulesFixtures/fixture-pack-forms.json`. +- `tests/RulesCore.Tests/ToggleGroupTests.cs`, `ToggleGroupValidationTests.cs` and `Properties/ToggleGroupProperties.cs` (resolution, calculation, validation), `tests/AppService.Tests/ToggleGroupCommandTests.cs` (atomic switch, cost, refusals) and `SourcePackTests.cs` (references), `src/Ui/src/components/FormGroups.test.tsx`, `src/Ui/src/undo.test.ts`, and the e2e flows in `src/Ui/e2e/forms.e2e.tsx` and `forms-play.e2e.tsx`. Fixture: `tests/RulesFixtures/fixture-pack-forms.json`. - [play-mechanics.md](../features/play-mechanics.md) lists the fields, codes and actions. diff --git a/docs/features/accessibility-checklist.md b/docs/features/accessibility-checklist.md index 717c6b5a..8172e438 100644 --- a/docs/features/accessibility-checklist.md +++ b/docs/features/accessibility-checklist.md @@ -8,7 +8,7 @@ Status key: ✅ verified (how) · 🔧 found and fixed in this change · ⚠️ ## Automated evidence -- `src/Ui/e2e/flow.e2e.tsx` (Vitest + Testing Library against the real DevHost) drives create → sheet → override → export → import **only through accessible roles and names**. A control without a usable label would fail the test. +- `src/Ui/e2e/core.e2e.tsx` (Vitest + Testing Library against the real DevHost) drives create → sheet → override → export → import **only through accessible roles and names**. A control without a usable label would fail the test. - The same file checks keyboard-only access: Tab reaches "+ Add a character", and choosing "Make a new one" then Continue opens the form with focus on Name. - M2 item 1: the builder test drives create → choices → cancelled level-up → level-up to 3 → "Make choices" by role and name only (radio groups, choice groups named by their legends), and asserts focus on the builder heading after a step change (2.4.3). Keyboard-only and Narrator passes of the builder are still owner checks (items 3 and 15). - M2 item 2: the same test spends a resource, sets temporary hit points, takes damage, toggles a condition and rolls (feature and d20 with advantage), all by role and name. Panels are regions named by their headings; the summary is the exception, a region named "Summary" by `aria-label`, with no heading. The roll result is a polite live region (`aria-live`), not `role="status"`, so it does not compete with the app's status line. Its announcement by Narrator is not checked yet (item 15). Superseded by row 106 (Wave 3 G3): the region is now "Status" and the last roll is one `role="status"` node. diff --git a/docs/features/builder.md b/docs/features/builder.md index 3f218fce..261b2d7f 100644 --- a/docs/features/builder.md +++ b/docs/features/builder.md @@ -2,7 +2,7 @@ SPEC C-01, C-07, S-02 · ROADMAP M2 · MVP "Builder" · status: implemented (M2 item 1). -`src/Ui/src/components/CharacterBuilder.tsx` over `src/AppService/Builder.cs`. Acceptance: `tests/AppService.Tests/BuilderDraftTests.cs` and the e2e test "builds an SRD 5.2.1 Barbarian as drafts" in `src/Ui/e2e/flow.e2e.tsx`. +`src/Ui/src/components/CharacterBuilder.tsx` over `src/AppService/Builder.cs`. Acceptance: `tests/AppService.Tests/BuilderDraftTests.cs` and the e2e test "builds an SRD 5.2.1 Barbarian as drafts" in `src/Ui/e2e/builder.e2e.tsx`. ## Drafts (SPEC C-07) @@ -76,7 +76,7 @@ In the choices step each caster's picker has a search by name ([spellcasting.md] ### Tests -Vitest: `CharacterBuilder.test.tsx` (steps, methods, review). e2e: the `createCharacter(user, { name, family?, scores?, species?, cls?, background?, other? })` helper in `src/Ui/e2e/flow.e2e.tsx` walks the seven steps (it skips Gear unless `kit` is set). With `scores` it uses "Enter by hand"; without, it assigns the standard array in order. +Vitest: `CharacterBuilder.test.tsx` (steps, methods, review). e2e: the `createCharacter(user, { name, family?, scores?, species?, cls?, background?, other? })` helper in `src/Ui/e2e/helpers.tsx` walks the seven steps (it skips Gear unless `kit` is set). With `scores` it uses "Enter by hand"; without, it assigns the standard array in order. ## Accessibility (WCAG 2.2 AA, D05) diff --git a/docs/features/ddb-pdf-import-plan.md b/docs/features/ddb-pdf-import-plan.md index d8c97795..c226386f 100644 --- a/docs/features/ddb-pdf-import-plan.md +++ b/docs/features/ddb-pdf-import-plan.md @@ -287,7 +287,7 @@ Dispatcher (`tests/AppService.Tests/PersistenceAndDispatchTests.cs`, extend): `d - `falls back to a file input when the host has no dialog` - `every table has a caption and row headers` (axe-style assertions as the existing component tests do; check `src/Ui/src/components/*.test.tsx` for the pattern) -`src/Ui/e2e/flow.e2e.tsx` (extend): `it('imports a D&D Beyond sheet, resolves a choice, keeps one sheet number as an override and creates the character', …)` reading `tests/RulesFixtures/pdf/fixture-ddb-sheet.pdf` through `ddb.readData` (the DevHost has no dialog), plus `it('cancelling the D&D Beyond import at each step leaves the character list unchanged', …)`. +`src/Ui/e2e/character-import.e2e.tsx` (extend): `it('imports a D&D Beyond sheet, resolves a choice, keeps one sheet number as an override and creates the character', …)` reading `tests/RulesFixtures/pdf/fixture-ddb-sheet.pdf` through `ddb.readData` (the DevHost has no dialog), plus `it('cancelling the D&D Beyond import at each step leaves the character list unchanged', …)`. **Doc updates.** Spec: status to "built, awaiting owner checks"; `docs/features/gap-notes.md` "A note" gains the `import` kind and the refusal in `gap.add`; `docs/schemas/README.md`; `docs/features/accessibility-checklist.md` gains an item for the step view; `docs/CHANGELOG.md` "Unreleased / Added"; LIVING_SPECS change history (built; gap-note v2; no DB or package change). The companion edits below are listed for the owner, not made here. diff --git a/docs/features/play-mechanics.md b/docs/features/play-mechanics.md index 5b9261c5..ebdde87d 100644 --- a/docs/features/play-mechanics.md +++ b/docs/features/play-mechanics.md @@ -262,7 +262,7 @@ A cost, a `toHit` or a `damageBonus` that does not parse is the usual `validate. ## Slice 5: action details and named values (content v11 only) -Rules core: `RollEffect` (new fields), `RollSave`, `RollArea`, `RollPerUnit`, `ValueEffect` and `DiceRoller.TryPerUnitFormula` in `src/RulesCore/Effects.cs` and `Dice.cs`; `FormulaFeatures` and the `VALUE.` identifier in `Formulas.cs`; `RollDetailsOf`, `CollectValues`, `ResolveValue` and `FieldReads` in `Calculation.cs`; `FormulaPreview.cs`; the checks in `ContentValidation.cs`. Service: the roll-effect branch of `src/AppService/Rolling.cs`. UI: the actions panel and the roll record in `PlayPanels.tsx`; `RollFields.tsx`, `rollAuthoring.ts` and `HomebrewStudio.tsx`. Acceptance: `tests/RulesCore.Tests/ActionDetailContentTests.cs`, `ActionDetailTests.cs`, `NamedValueTests.cs` and `Properties/PerUnitProperties.cs`, `tests/AppService.Tests/RollCommandTests.cs` (including `The_acceptance_technique_rolls_and_spends_the_same_amount`), `src/Ui/src/components/ActionsPanel.test.tsx`, `HomebrewStudioRolls.test.tsx` and `rollAuthoring.test.ts`, and the e2e flow in `src/Ui/e2e/forms.e2e.tsx`. Fixtures: `tests/RulesFixtures/fixture-pack-action-details.json` and `characters/pm-wave-adept-l5.json`. There is no new character field, play action or version: everything here is content schema v11. +Rules core: `RollEffect` (new fields), `RollSave`, `RollArea`, `RollPerUnit`, `ValueEffect` and `DiceRoller.TryPerUnitFormula` in `src/RulesCore/Effects.cs` and `Dice.cs`; `FormulaFeatures` and the `VALUE.` identifier in `Formulas.cs`; `RollDetailsOf`, `CollectValues`, `ResolveValue` and `FieldReads` in `Calculation.cs`; `FormulaPreview.cs`; the checks in `ContentValidation.cs`. Service: the roll-effect branch of `src/AppService/Rolling.cs`. UI: the actions panel and the roll record in `PlayPanels.tsx`; `RollFields.tsx`, `rollAuthoring.ts` and `HomebrewStudio.tsx`. Acceptance: `tests/RulesCore.Tests/ActionDetailContentTests.cs`, `ActionDetailTests.cs`, `NamedValueTests.cs` and `Properties/PerUnitProperties.cs`, `tests/AppService.Tests/RollCommandTests.cs` (including `The_acceptance_technique_rolls_and_spends_the_same_amount`), `src/Ui/src/components/ActionsPanel.test.tsx`, `HomebrewStudioRolls.test.tsx` and `rollAuthoring.test.ts`, and the e2e flow in `src/Ui/e2e/forms-play.e2e.tsx`. Fixtures: `tests/RulesFixtures/fixture-pack-action-details.json` and `characters/pm-wave-adept-l5.json`. There is no new character field, play action or version: everything here is content schema v11. ### Content (schema v11, added) @@ -348,7 +348,7 @@ A roll's editor has every field: Dice (clearing it makes an action that rolls no ## Slice 6: roll modes, fly speed and form-only damage defences (content v11 only) -Rules core: `RollModeEffect`, `GrantEffect.WhileToggle` and `FieldIds.FlySpeed` in `src/RulesCore/Effects.cs`; `RollModes.cs` (`RollModeReason`, `RollModeSummary`, `RollModes.Combine`); `CollectRollModes`, `GateOnToggle`, `CollectDamageDefences`, `IsPlayMechanicsOnlyField` and the `speed.fly` spec in `Calculation.cs`; the checks in `ContentValidation.cs`. Service: the field branch of `src/AppService/Rolling.cs`. UI: `rollModes.ts`, `rollText.ts`, the field buttons in `CharacterSheet.tsx` and `SheetSummary.tsx`, `RollResult` and `RollModePicker` in `PlayPanels.tsx`, and `RollModeFields.tsx` with `HomebrewStudio.tsx`. Acceptance: `tests/RulesCore.Tests/RollModeContentTests.cs`, `RollModeTests.cs`, `Properties/RollModeProperties.cs`, `FormOnlyDefenceTests.cs`, `DamagePipelineTests.cs` and `AbilityCapTests.cs`, `tests/AppService.Tests/RollCommandTests.cs`, `src/Ui/src/rollText.test.ts`, `components/CharacterSheet.test.tsx`, `SheetSummary.test.tsx` and `HomebrewStudioRollModes.test.tsx`, and the e2e flow in `src/Ui/e2e/forms.e2e.tsx`. Fixtures: `tests/RulesFixtures/fixture-pack-roll-modes.json` and `characters/pm-instinct-l4.json`. There is no new character field, play action or version: everything here is content schema v11. +Rules core: `RollModeEffect`, `GrantEffect.WhileToggle` and `FieldIds.FlySpeed` in `src/RulesCore/Effects.cs`; `RollModes.cs` (`RollModeReason`, `RollModeSummary`, `RollModes.Combine`); `CollectRollModes`, `GateOnToggle`, `CollectDamageDefences`, `IsPlayMechanicsOnlyField` and the `speed.fly` spec in `Calculation.cs`; the checks in `ContentValidation.cs`. Service: the field branch of `src/AppService/Rolling.cs`. UI: `rollModes.ts`, `rollText.ts`, the field buttons in `CharacterSheet.tsx` and `SheetSummary.tsx`, `RollResult` and `RollModePicker` in `PlayPanels.tsx`, and `RollModeFields.tsx` with `HomebrewStudio.tsx`. Acceptance: `tests/RulesCore.Tests/RollModeContentTests.cs`, `RollModeTests.cs`, `Properties/RollModeProperties.cs`, `FormOnlyDefenceTests.cs`, `DamagePipelineTests.cs` and `AbilityCapTests.cs`, `tests/AppService.Tests/RollCommandTests.cs`, `src/Ui/src/rollText.test.ts`, `components/CharacterSheet.test.tsx`, `SheetSummary.test.tsx` and `HomebrewStudioRollModes.test.tsx`, and the e2e flow in `src/Ui/e2e/forms-play.e2e.tsx`. Fixtures: `tests/RulesFixtures/fixture-pack-roll-modes.json` and `characters/pm-instinct-l4.json`. There is no new character field, play action or version: everything here is content schema v11. ### Content (schema v11, added) @@ -432,7 +432,7 @@ mode: { automatic: "advantage" | "disadvantage" | "normal", ## Slice 7: damage responses (content v11 only; D45) -Rules core: `ResponseEffect`, `ResponsePhase`, `ResponseWhen` and `ResponseOutcome` in `src/RulesCore/Effects.cs`; `DamagePipeline.Plan` and `DamagePipeline.Apply` with their records in `src/RulesCore/DamagePipeline.cs`; `CollectResponses` and `CharacterSheet.Responses` in `Calculation.cs`; the checks in `ContentValidation.cs`. Service: `character.damagePreview` and the damage branch of `character.play` (`src/AppService/Damage.cs`, `Play.cs`). UI: `DamagePanel.tsx`, `PlayPanels.tsx`, `CharacterSheet.tsx` and `ResponseFields.tsx` with `HomebrewStudio.tsx`. Acceptance: `tests/RulesCore.Tests/ResponseContentTests.cs` and `DamageResponseTests.cs`, `tests/AppService.Tests/DamageResponseServiceTests.cs`, `src/Ui/src/components/DamagePanel.test.tsx` and `HomebrewStudioResponses.test.tsx`, and the e2e flow in `src/Ui/e2e/forms.e2e.tsx`. Fixtures: `tests/RulesFixtures/fixture-pack-responses.json` and `characters/pm-bulwark-l8.json`. There is no new character field or version: everything here is content schema v11. Benchmarks: [performance.md](../performance.md). +Rules core: `ResponseEffect`, `ResponsePhase`, `ResponseWhen` and `ResponseOutcome` in `src/RulesCore/Effects.cs`; `DamagePipeline.Plan` and `DamagePipeline.Apply` with their records in `src/RulesCore/DamagePipeline.cs`; `CollectResponses` and `CharacterSheet.Responses` in `Calculation.cs`; the checks in `ContentValidation.cs`. Service: `character.damagePreview` and the damage branch of `character.play` (`src/AppService/Damage.cs`, `Play.cs`). UI: `DamagePanel.tsx`, `PlayPanels.tsx`, `CharacterSheet.tsx` and `ResponseFields.tsx` with `HomebrewStudio.tsx`. Acceptance: `tests/RulesCore.Tests/ResponseContentTests.cs` and `DamageResponseTests.cs`, `tests/AppService.Tests/DamageResponseServiceTests.cs`, `src/Ui/src/components/DamagePanel.test.tsx` and `HomebrewStudioResponses.test.tsx`, and the e2e flow in `src/Ui/e2e/forms-play.e2e.tsx`. Fixtures: `tests/RulesFixtures/fixture-pack-responses.json` and `characters/pm-bulwark-l8.json`. There is no new character field or version: everything here is content schema v11. Benchmarks: [performance.md](../performance.md). ### The response effect @@ -478,7 +478,7 @@ On a sheet with responses, "Take damage" and the summary's "Lose 1 hit point" op ## Slice 8: charging (content v11 only) -Rules core: `RollEffect.AlsoChange`, `RollEffect.DrawsDown` and `AlsoChange` in `src/RulesCore/Effects.cs`; `PoolChange` and `PoolChanges.Apply` in `src/RulesCore/Charging.cs`; `AlsoChangeValue` and the roll details in `Calculation.cs`; the checks in `ContentValidation.cs`. Service: the `useAction` and `endEncounter` branches of `src/AppService/Play.cs` and the draw-down check of the roll command in `Rolling.cs`. UI: the actions panel, the roll record and the Combat strip in `PlayPanels.tsx` and `CombatStrip.tsx`; `RollFields.tsx` with `HomebrewStudio.tsx`. Acceptance: `tests/RulesCore.Tests/ChargingContentTests.cs` and `Properties/ChargingProperties.cs`, `tests/AppService.Tests/ChargingTests.cs`, `src/Ui/src/components/ActionsPanel.test.tsx`, `CombatStrip.test.tsx` and `HomebrewStudioRolls.test.tsx`, and the e2e flow in `src/Ui/e2e/forms.e2e.tsx`. Fixtures: `tests/RulesFixtures/fixture-pack-charging.json` and `characters/pm-charger-l5.json`. There is no new character field or version: everything here is content schema v11. +Rules core: `RollEffect.AlsoChange`, `RollEffect.DrawsDown` and `AlsoChange` in `src/RulesCore/Effects.cs`; `PoolChange` and `PoolChanges.Apply` in `src/RulesCore/Charging.cs`; `AlsoChangeValue` and the roll details in `Calculation.cs`; the checks in `ContentValidation.cs`. Service: the `useAction` and `endEncounter` branches of `src/AppService/Play.cs` and the draw-down check of the roll command in `Rolling.cs`. UI: the actions panel, the roll record and the Combat strip in `PlayPanels.tsx` and `CombatStrip.tsx`; `RollFields.tsx` with `HomebrewStudio.tsx`. Acceptance: `tests/RulesCore.Tests/ChargingContentTests.cs` and `Properties/ChargingProperties.cs`, `tests/AppService.Tests/ChargingTests.cs`, `src/Ui/src/components/ActionsPanel.test.tsx`, `CombatStrip.test.tsx` and `HomebrewStudioRolls.test.tsx`, and the e2e flow in `src/Ui/e2e/forms-play.e2e.tsx`. Fixtures: `tests/RulesFixtures/fixture-pack-charging.json` and `characters/pm-charger-l5.json`. There is no new character field or version: everything here is content schema v11. ### Content (schema v11, added) diff --git a/docs/features/sheet-layout.md b/docs/features/sheet-layout.md index b2c11761..21bc7050 100644 --- a/docs/features/sheet-layout.md +++ b/docs/features/sheet-layout.md @@ -2,7 +2,7 @@ SPEC P-03 · ADR-014 · LIVING_SPECS D17 (owner, 2026-10-03) · status: **implemented** (slices 1 to 4, 2026-10-04) · ADR-015, D18 (2026-10-05) · D96 (status bar, six tabs and More, Wave 3 Groups 3 and 4). -UI: `src/Ui/src/App.tsx`, `src/Ui/src/components/CharacterSheet.tsx`, `src/Ui/src/components/sheet/TabList.tsx`, `src/Ui/src/components/sheet/MoreMenu.tsx`, `src/Ui/src/components/SheetSummary.tsx`, `src/Ui/src/sheetTab.ts`. Tests: `TabList.test.tsx`, `MoreMenu.test.tsx`, `SheetSummary.test.tsx`, `sheetTab.test.ts`, `CharacterSheet.test.tsx` and every sheet test in `src/Ui/e2e/flow.e2e.tsx` (helpers `openTab` and `summaryValue`). +UI: `src/Ui/src/App.tsx`, `src/Ui/src/components/CharacterSheet.tsx`, `src/Ui/src/components/sheet/TabList.tsx`, `src/Ui/src/components/sheet/MoreMenu.tsx`, `src/Ui/src/components/SheetSummary.tsx`, `src/Ui/src/sheetTab.ts`. Tests: `TabList.test.tsx`, `MoreMenu.test.tsx`, `SheetSummary.test.tsx`, `sheetTab.test.ts`, `CharacterSheet.test.tsx` and every sheet test in `src/Ui/e2e/*.e2e.tsx` (helpers `openTab` and `summaryValue` in `src/Ui/e2e/helpers.tsx`). ## Layout diff --git a/docs/features/sheet-play.md b/docs/features/sheet-play.md index c776db10..2356e20a 100644 --- a/docs/features/sheet-play.md +++ b/docs/features/sheet-play.md @@ -119,7 +119,7 @@ Two additions to the Play tab, both worked out in the page from what the sheet a - **The quickbar never pays hit points or slots (MECH-X item 1, R37).** A roll or feature attack that pays hit points or a spell slot ([play-mechanics.md](play-mechanics.md)) is pinned as a plain roll: its press only rolls, never says "and spend", and the Last roll's Pay button is the deliberate press that pays. A switch that pays hit points or a slot cannot be pinned, and neither can a paying roll with no dice (its press would only pay), so one tap never pays; a stored pin of one is hidden. A paying roll or attack that cannot be paid now (too few hit points, no slot at or above its level) is blocked on the quickbar with the reason, like a pinned action that cannot be used. The Actions panel Roll still rolls, as with a pool shortage, because rolling pays nothing. - **Pins survive.** They are kept per character in the page's own storage (`tomestack.quickbar.`; in no package, share or backup) and so survive closing and reopening the app. A pin that does not resolve on the current sheet (a removed feature, an unequipped weapon, a form that is off) is hidden, not deleted: storage keeps the visible pins first, then the hidden ones, up to 16. -See accessibility checklist row 90 and the e2e flows in `src/Ui/e2e/forms.e2e.tsx`. +See accessibility checklist row 90 and the e2e flows in `src/Ui/e2e/forms-play.e2e.tsx`. ## Details, languages and tools (item 17, D36) diff --git a/src/Ui/e2e/builder.e2e.tsx b/src/Ui/e2e/builder.e2e.tsx new file mode 100644 index 00000000..1c6f835a --- /dev/null +++ b/src/Ui/e2e/builder.e2e.tsx @@ -0,0 +1,652 @@ +// End-to-end UI flow against the real DevHost (same CommandDispatcher as the shell). Only the transport differs from the desktop +// app: HTTP to loopback instead of the WebView2 bridge, so export takes the download fallback instead of the native Save dialog. +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, expect, it, vi } from 'vitest'; +import { App } from '../src/App'; +import { client } from '../src/api/client'; +import { TomeStackError } from '../src/api/transport'; +import { appStatus, createCharacter, expectStatus, fighter, goHome, openTab, pick, srd, startNewCharacter, summaryValue } from './helpers'; + +vi.mock('../src/api/client', async (importOriginal) => { + const { inject } = await import('vitest'); + const { createHttpTransport } = await import('../src/api/transport'); + const original = await importOriginal(); + const { endpoint, token } = inject('devHost'); + return { ...original, client: original.createClient(createHttpTransport(endpoint, { 'X-TomeStack-Token': token })) }; +}); + +vi.mock('../src/files', async (importOriginal) => ({ + ...(await importOriginal()), + downloadBase64: vi.fn(), +})); + +afterEach(() => { + cleanup(); + // One jsdom window serves the whole file: a preference or `html` attribute left by one test would leak into the next. + // The per-character tab memory stays (ids are unique per test and the deep-link test relies on it). + for (const key of Object.keys(localStorage)) if (key.startsWith('tomestack.') && !key.startsWith('tomestack.sheetTab.')) localStorage.removeItem(key); + for (const key of Object.keys(document.documentElement.dataset)) delete document.documentElement.dataset[key]; +}); + +// The longest flow in the suite (create, two level-ups, play, rests): ~58 s alone locally (2026-10-29), so the 60 s +// default timed it out on a loaded machine; it gets 180 s, three times the suite's per-test budget. +it('builds an SRD 5.2.1 Barbarian as drafts: create, cancel a level-up, level to 3 with a subclass', async () => { + const user = userEvent.setup(); + render(); + // The M1 acceptance character Brenna (Str 15, Dex 13, Con 14, Int 8, Wis 12, Cha 10); D31: only the character's family is listed. + await createCharacter(user, { + name: 'E2E Brenna', + family: 'srd-5.2.1', + scores: { Strength: 15, Dexterity: 13, Constitution: 14, Intelligence: 8, Wisdom: 12, Charisma: 10 }, + species: /^Dwarf/, + cls: /^Barbarian/, + background: /^Soldier/, + }); + + // Level-1 choices are offered and flagged until answered; the subclass (level 3) is not offered yet. + await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('heading', { name: 'New character' }))); + expect(await screen.findByText(/2 choices still to make/)).toBeTruthy(); + expect(screen.queryByRole('group', { name: /^Barbarian: choose 1/ })).toBeNull(); + await pick(user, /^Soldier: choose 1/, /^Soldier Ability Scores: Strength \+2, Constitution \+1/); + await pick(user, /^Barbarian: choose 2/, /^Barbarian Skill: Perception/); + await pick(user, /^Barbarian: choose 2/, /^Barbarian Skill: Survival/); + expect(await screen.findByText('All choices are made.')).toBeTruthy(); + await user.click(screen.getByRole('button', { name: 'Create and save' })); + + let sheet = await screen.findByRole('article', { name: 'E2E Brenna' }); + await openTab(user, sheet, 'Skills and saves'); + expect(within(sheet).getByRole('heading', { name: /^Strength score: 17/ })).toBeTruthy(); + expect(within(sheet).queryByRole('heading', { name: 'Choices to make' })).toBeNull(); + + // A cancelled level-up draft changes nothing. + await user.click(within(sheet).getByRole('button', { name: 'Level up' })); + await user.click(await screen.findByRole('radio', { name: /^Barbarian 2\b/ })); + await user.click(screen.getByRole('button', { name: 'Next: choices' })); + expect(await screen.findByText('All choices are made.')).toBeTruthy(); // level 2 offers no new choice + await user.click(screen.getByRole('button', { name: 'Cancel' })); + await user.click(await screen.findByRole('button', { name: 'Discard' })); // a level-up pick was made: Cancel asks first + await expectStatus(/Draft discarded/); + sheet = await screen.findByRole('article', { name: 'E2E Brenna' }); + expect(within(sheet).getByText('Level 1')).toBeTruthy(); + + // Level 2, then 3: the subclass and Primal Knowledge choices appear at level 3. + for (const next of [2, 3]) { + await user.click(within(await screen.findByRole('article', { name: 'E2E Brenna' })).getByRole('button', { name: 'Level up' })); + await user.click(await screen.findByRole('radio', { name: new RegExp(`^Barbarian ${next}\\b`) })); + await user.click(screen.getByRole('button', { name: 'Next: choices' })); + if (next === 3) { + await pick(user, /^Barbarian: choose 1/, /^Path of the Berserker/); + // Leave Primal Knowledge open: the save is allowed and the sheet flags it. + expect(await screen.findByText(/1 choice still to make/)).toBeTruthy(); + } + await user.click(await screen.findByRole('button', { name: 'Save level-up' })); + } + + sheet = await screen.findByRole('article', { name: 'E2E Brenna' }); + expect(within(sheet).getByText('Level 3')).toBeTruthy(); + + // D74: Save level-up opens the sheet on Features with "What changed at level 3" focused (the level-2 list was overwritten). + const changed = within(sheet).getByRole('region', { name: 'What changed at level 3' }); + await waitFor(() => expect(document.activeElement).toBe(within(changed).getByRole('heading', { name: 'What changed at level 3' }))); + expect(within(changed).getByText(/^Hit point maximum:/)).toBeTruthy(); + expect(within(changed).getByText(/^New choice: Primal Knowledge/)).toBeTruthy(); + await user.click(within(changed).getByRole('button', { name: 'Dismiss' })); + expect(within(sheet).queryByRole('region', { name: /^What changed at level/ })).toBeNull(); + // Gone for good: leaving the sheet and opening the character again shows no panel. + await goHome(user); + await user.click(within(await screen.findByRole('navigation', { name: 'Main' })).getByRole('button', { name: /E2E Brenna/ })); + sheet = await screen.findByRole('article', { name: 'E2E Brenna' }); + expect(within(sheet).queryByRole('region', { name: /^What changed at level/ })).toBeNull(); + + const open = within(sheet).getByRole('heading', { name: 'Choices to make' }).parentElement!; + expect(open.textContent).toMatch(/Primal Knowledge: choose 1 \(0 chosen\)/); + + // Answer it from the sheet: Survival is already chosen elsewhere, so pick Animal Handling. + await user.click(within(open).getByRole('button', { name: 'Choose now' })); + await pick(user, /^Primal Knowledge: choose 1/, /^Barbarian Skill: Animal Handling/); + expect(await screen.findByRole('checkbox', { name: /^Barbarian Skill: Animal Handling/, checked: true })).toBeTruthy(); + await user.click(await screen.findByRole('button', { name: 'Save choices' })); + + // The M1 acceptance values for Brenna (m1-acceptance.md): AC 13, HP 35, Animal Handling +3. + // The builder waits for the tick's preview before saving, and the saved view opens the sheet; wait for the re-render all the same. + sheet = await screen.findByRole('article', { name: 'E2E Brenna' }); + await openTab(user, sheet, 'Skills and saves'); + expect(await within(sheet).findByRole('heading', { name: /^Armor Class: 13/ })).toBeTruthy(); + expect(await within(sheet).findByRole('heading', { name: /^Hit point maximum: 35/ })).toBeTruthy(); + expect(await within(sheet).findByRole('heading', { name: /^Animal Handling: \+3/ })).toBeTruthy(); + await waitFor(() => expect(within(sheet).queryByRole('heading', { name: 'Choices to make' })).toBeNull()); + + // M2 item 2, play: resources with calculated maximums, explicit spending, hit points, conditions and rolls. + await openTab(user, sheet, 'Play'); + const resources = within(sheet).getByRole('region', { name: 'Resources' }); + expect(within(resources).getByRole('heading', { name: 'Rages: 3 of 3' })).toBeTruthy(); + expect(within(resources).getByRole('heading', { name: 'Stonecunning: 2 of 2' })).toBeTruthy(); + await user.click(within(resources).getByRole('button', { name: 'Spend 1 Rages' })); + await waitFor(() => expect(within(screen.getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Rages: 2 of 3' })).toBeTruthy()); + + const hp = screen.getByRole('region', { name: /^Hit points:/ }); + await user.type(within(hp).getByRole('spinbutton', { name: 'Amount' }), '5'); + await user.click(within(hp).getByRole('button', { name: 'Set temporary hit points' })); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 35 of 35, 5 temporary' })).toBeTruthy()); + await user.type(within(screen.getByRole('region', { name: /^Hit points:/ })).getByRole('spinbutton', { name: 'Amount' }), '12'); + await user.click(within(screen.getByRole('region', { name: /^Hit points:/ })).getByRole('button', { name: 'Take damage' })); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 28 of 35' })).toBeTruthy()); + + // D23: Undo puts the hit points and the temporary hit points back, then the damage is taken again. + await user.click(await screen.findByRole('button', { name: 'Undo last change: damage 12' })); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 35 of 35, 5 temporary' })).toBeTruthy()); + await waitFor(() => expect(screen.getByRole('button', { name: 'Undo last change' }).disabled).toBe(true)); + const amount = () => within(screen.getByRole('region', { name: /^Hit points:/ })).getByRole('spinbutton', { name: 'Amount' }); + await user.clear(amount()); + await user.type(amount(), '12'); + await user.click(within(screen.getByRole('region', { name: /^Hit points:/ })).getByRole('button', { name: 'Take damage' })); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 28 of 35' })).toBeTruthy()); + + await user.selectOptions(screen.getByRole('combobox', { name: 'Add condition' }), 'Poisoned'); + await waitFor(() => expect(screen.getByRole('button', { name: 'Remove Poisoned' })).toBeTruthy()); + + // A feature roll shows its record, and rolling spends nothing. + await user.click(screen.getByRole('checkbox', { name: /Critical hit/ })); + await user.click(screen.getByRole('button', { name: 'Roll Frenzy extra damage (Rage Damage +2: 2d6) (2d6)' })); + const lastRoll = screen.getByRole('status', { name: 'Last roll' }); + expect(within(screen.getByRole('region', { name: 'Status' })).getByRole('status', { name: 'Last roll' })).toBe(lastRoll); + await waitFor(() => expect(lastRoll.textContent).toMatch(/Frenzy extra damage.*: \d+ \(2d6, critical\)/)); + expect(lastRoll.textContent).toMatch(/d6 \d \(critical\)/); // doubled dice are marked + expect(lastRoll.textContent).toMatch(/Frenzy \(System Reference Document 5\.2\.1, p\. \d+\)/); + + // A d20 test with advantage keeps one die and drops the other. + await user.click(screen.getByRole('radio', { name: 'Advantage' })); + await openTab(user, sheet, 'Skills and saves'); + const strSave = screen.getByRole('region', { name: /^Strength saving throw:/ }); + await user.click(within(strSave).getByRole('heading')); + await user.click(within(strSave).getByRole('button', { name: 'Roll Strength saving throw' })); + await waitFor(() => expect(lastRoll.textContent).toMatch(/Strength saving throw \(d20 test\): \d+ \(1d20, advantage\)/)); + expect(lastRoll.textContent).toMatch(/\(dropped\)/); + expect(lastRoll.textContent).toMatch(/Strength saving throw \+5/); + // D72: "Why?" sits beside the Last roll (not inside it) and explains the +5 in words, naming the proficiency bonus. + const why = within(screen.getByRole('region', { name: 'Status' })).getByText('Why?').closest('details')!; + expect(why.open).toBe(false); + expect(lastRoll.contains(why)).toBe(false); + await user.click(within(why).getByText('Why?')); + expect(why.open).toBe(true); + expect(within(why).getByRole('list', { name: 'Why this roll came out this way' }).textContent).toMatch(/proficiency bonus/i); + // D28: the roll before it is in Earlier rolls, outside the live region. + await user.click(within(sheet).getByText('Earlier rolls (1)')); + expect(within(sheet).getByText('Earlier rolls (1)').closest('details')!.textContent).toMatch(/Frenzy extra damage.*: \d+ \(2d6, critical\)/); + expect(lastRoll.textContent).not.toMatch(/Earlier rolls/); + await openTab(user, sheet, 'Play'); + expect(within(screen.getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Rages: 2 of 3' })).toBeTruthy(); + + // Features list their automation status. + await openTab(user, sheet, 'Features'); + const features = screen.getByRole('region', { name: 'Features' }); + // C2-1: the new Barbarian's Danger Sense is a worked-out Dexterity-save advantage (it was reference text before). + expect(within(features).getByText('Danger Sense').closest('li')!.textContent).toMatch(/Worked out for you/); + + // M2 item 3, long rest (D01): preview first, cancel changes nothing, then confirm. + await openTab(user, sheet, 'Play'); + await user.click(screen.getByRole('button', { name: 'Long rest…' })); + let rest = await screen.findByRole('region', { name: 'Long rest' }); + await waitFor(() => expect(document.activeElement).toBe(within(rest).getByRole('heading', { name: 'Long rest' }))); + // The heading is focused on mount; the preview's changes arrive afterwards (restPreview), so wait for them. + expect(await within(rest).findByRole('checkbox', { name: /^Hit points: 28 → 35/ })).toBeTruthy(); + expect(await within(rest).findByRole('checkbox', { name: /^Rages: 2 → 3/ })).toBeTruthy(); + await user.click(within(rest).getByRole('button', { name: 'Cancel rest' })); + expect(screen.getByRole('heading', { name: 'Hit points: 28 of 35' })).toBeTruthy(); + + await user.click(screen.getByRole('button', { name: 'Long rest…' })); + rest = await screen.findByRole('region', { name: 'Long rest' }); + await user.click(await within(rest).findByRole('checkbox', { name: /^Rages: 2 → 3/ })); // untick: keep Rages as they are + await user.click(within(rest).getByRole('button', { name: 'Finish long rest' })); + await expectStatus(/Long rest finished: 1 change applied/); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 35 of 35' })).toBeTruthy()); + expect(within(screen.getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Rages: 2 of 3' })).toBeTruthy(); + + // Short rest (D01 follow-up): spend a hit die rolled at the table (5 + Con 2 = 7), and Rage regains one use (2024). + const hpPanel = () => screen.getByRole('region', { name: /^Hit points:/ }); + await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '10'); + await user.click(within(hpPanel()).getByRole('button', { name: 'Take damage' })); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 25 of 35' })).toBeTruthy()); + expect(hpPanel().textContent).toMatch(/Hit dice: 3 of 3 \(d12\)/); + await user.click(screen.getByRole('button', { name: 'Short rest…' })); + rest = await screen.findByRole('region', { name: 'Short rest' }); + await waitFor(() => expect(document.activeElement).toBe(within(rest).getByRole('heading', { name: 'Short rest' }))); + expect(await within(rest).findByRole('checkbox', { name: /^Rages: 2 → 3/ })).toBeTruthy(); + await user.type(within(rest).getByRole('spinbutton', { name: 'd12 rolled at the table' }), '5'); + await user.click(within(rest).getByRole('button', { name: 'Add d12' })); + const spend = await within(rest).findByRole('list', { name: 'Hit dice to spend' }); + expect(spend.textContent).toMatch(/Rolled 5, Constitution modifier \+2: 7 hit point\(s\)\. Hit points 25 → 32/); + await user.click(within(rest).getByRole('button', { name: 'Finish short rest' })); + await expectStatus(/Short rest finished: 2 changes applied/); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 32 of 35' })).toBeTruthy()); + expect(hpPanel().textContent).toMatch(/Hit dice: 2 of 3 \(d12\)/); + expect(within(screen.getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Rages: 3 of 3' })).toBeTruthy(); + + // Heroic Inspiration (2024) and death saving throws (SPEC C-05): a 20 at the table regains 1 hit point. + const statusBar = () => screen.getByRole('region', { name: 'Status' }); + await user.click(within(statusBar()).getByRole('checkbox', { name: 'Heroic Inspiration' })); + await waitFor(() => expect(within(statusBar()).getByRole('checkbox', { name: 'Heroic Inspiration' }).checked).toBe(true)); + expect(screen.queryByRole('region', { name: /^Death saving throws/ })).toBeNull(); + await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '40'); + await user.click(within(hpPanel()).getByRole('button', { name: 'Take damage' })); + const deathSaves = await screen.findByRole('region', { name: /^Death saving throws: 0 of 3 successes, 0 of 3 failures/ }); + await user.click(within(deathSaves).getByRole('button', { name: 'Add a failure (damage at 0)' })); + await screen.findByRole('region', { name: /^Death saving throws: 0 of 3 successes, 1 of 3 failures/ }); + // D23: healing from 0 clears the death saves, which no command puts back, so it offers no Undo (one that silently wiped + // the failure would be worse than none). Then back to 0 hit points for the roll below. + await user.clear(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' })); + await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '1'); + await user.click(within(hpPanel()).getByRole('button', { name: 'Heal' })); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 1 of 35' })).toBeTruthy()); + expect(screen.getByRole('button', { name: 'Undo last change' }).disabled).toBe(true); + await user.clear(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' })); + await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '1'); + await user.click(within(hpPanel()).getByRole('button', { name: 'Take damage' })); + await screen.findByRole('region', { name: /^Death saving throws: 0 of 3 successes, 0 of 3 failures/ }); + await user.type(within(screen.getByRole('region', { name: /^Death saving throws/ })).getByRole('spinbutton', { name: 'd20 rolled at the table' }), '20'); + await user.click(within(screen.getByRole('region', { name: /^Death saving throws/ })).getByRole('button', { name: 'Record this roll' })); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 1 of 35' })).toBeTruthy()); + expect(screen.queryByRole('region', { name: /^Death saving throws/ })).toBeNull(); // regaining hit points cleared them + await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '34'); + await user.click(within(hpPanel()).getByRole('button', { name: 'Heal' })); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 35 of 35' })).toBeTruthy()); + + // Wave 3 item 21 (D19 amended): a resistance recorded by hand on Stats halves typed damage on Play, and Undo puts it all back. + await openTab(user, sheet, 'Skills and saves'); + const defences = () => screen.getByRole('region', { name: 'Damage resistances, immunities and vulnerabilities' }); + await user.selectOptions(within(defences()).getByRole('combobox', { name: 'Damage type' }), 'slashing'); + await user.click(within(defences()).getByRole('button', { name: 'Add' })); + await waitFor(() => expect(within(defences()).getByRole('list', { name: 'Damage defences the sheet applies' }).textContent).toMatch(/Slashing resistance from Entered by hand/)); + await openTab(user, sheet, 'Play'); + await user.selectOptions(within(hpPanel()).getByRole('combobox', { name: 'Damage type' }), 'slashing'); + await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '13'); + await user.click(within(hpPanel()).getByRole('button', { name: 'Take damage' })); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 29 of 35' })).toBeTruthy()); // 13 halved, rounded down: 6 + expect(hpPanel().textContent).toMatch(/13 slashing, halved: 6\./); + await user.click(await screen.findByRole('button', { name: 'Undo last change: damage 13 slashing (6 taken)' })); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 35 of 35' })).toBeTruthy()); + // Untyped damage ignores the resistance. + await user.selectOptions(within(hpPanel()).getByRole('combobox', { name: 'Damage type' }), ''); + await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '4'); + await user.click(within(hpPanel()).getByRole('button', { name: 'Take damage' })); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 31 of 35' })).toBeTruthy()); + await user.click(await screen.findByRole('button', { name: 'Undo last change: damage 4' })); + await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 35 of 35' })).toBeTruthy()); + await openTab(user, sheet, 'Skills and saves'); + await user.click(within(defences()).getByRole('button', { name: 'Remove slashing resistance' })); + await waitFor(() => expect(screen.queryByRole('list', { name: 'Damage defences the sheet applies' })).toBeNull()); + + // Wave 3 item 27: Track XP is off by default; a total at the next level's threshold shows "Level up available" (display only). + const xp = () => screen.getByRole('region', { name: 'Experience points' }); + expect(within(xp()).getByRole('checkbox', { name: 'Track XP' }).checked).toBe(false); + await user.click(within(xp()).getByRole('checkbox', { name: 'Track XP' })); + const xpBox = await within(xp()).findByRole('spinbutton', { name: 'Experience points' }); + expect(xpBox.value).toBe('0'); + expect(within(xp()).queryByText('Level up available')).toBeNull(); + const nextLevelAt = /^Next level at (\d{1,3}(,\d{3})*)$/; + const threshold = Number((await within(xp()).findByText(nextLevelAt)).textContent!.replace(nextLevelAt, '$1').replaceAll(',', '')); + await user.clear(xpBox); + await user.type(xpBox, String(threshold - 1)); + await user.click(within(xp()).getByRole('button', { name: 'Save experience points' })); + // Wait for the save to land (nothing differs, so Save is aria-disabled and focus is on the heading) before typing again: + // a reply that arrives mid-type moves focus off the box and leaves a partial number in it. + await waitFor(() => expect(within(xp()).getByRole('button', { name: 'Save experience points' }).getAttribute('aria-disabled')).toBe('true')); + expect(within(xp()).getByRole('spinbutton', { name: 'Experience points' }).value).toBe(String(threshold - 1)); + expect(within(xp()).queryByText('Level up available')).toBeNull(); + await user.clear(within(xp()).getByRole('spinbutton', { name: 'Experience points' })); + await user.type(within(xp()).getByRole('spinbutton', { name: 'Experience points' }), String(threshold)); + await user.click(within(xp()).getByRole('button', { name: 'Save experience points' })); + await within(xp()).findByText('Level up available'); + await user.click(within(xp()).getByRole('checkbox', { name: 'Track XP' })); // untick: the total and the hint go + await waitFor(() => expect(within(xp()).queryByRole('spinbutton', { name: 'Experience points' })).toBeNull()); + expect(within(xp()).queryByText('Level up available')).toBeNull(); + await openTab(user, sheet, 'Play'); + + // M2 item 4: armor replaces Unarmored Defense (13); a shield adds to it. Original fixture equipment. + await openTab(user, sheet, 'Gear'); + const equipment = () => screen.getByRole('region', { name: 'Equipment' }); + await waitFor(() => expect(within(equipment()).getByRole('option', { name: /^Fixture Scale Vest/ })).toBeTruthy()); + await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^Fixture Scale Vest/ })); + await user.click(within(equipment()).getByRole('button', { name: 'Add' })); + await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip Fixture Scale Vest' })); + await waitFor(() => expect(summaryValue(sheet, 'Armor Class')).toBe('15')); // 14 + Dex 1 + await openTab(user, sheet, 'Skills and saves'); + const ac = screen.getByRole('region', { name: /^Armor Class:/ }); + await user.click(within(ac).getByRole('heading')); + expect(within(ac).getByRole('table').textContent).toMatch(/Unarmored Defense.*not used: it applies only while no armor is worn/); + + await openTab(user, sheet, 'Gear'); + await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^Fixture Kite Shield/ })); + await user.click(within(equipment()).getByRole('button', { name: 'Add' })); + await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip Fixture Kite Shield' })); + await waitFor(() => expect(summaryValue(sheet, 'Armor Class')).toBe('17')); + await user.click(within(equipment()).getByRole('checkbox', { name: 'Equip Fixture Scale Vest' })); // take the armor off + await waitFor(() => expect(summaryValue(sheet, 'Armor Class')).toBe('15')); // Unarmored Defense 13 + shield 2 +}, 180_000); + +it('drops picks that do not fit when the rules family changes, in the builder and in a campaign', async () => { + const user = userEvent.setup(); + render(); + + // Builder: an SRD 5.1 species, then SRD 5.2.1. The 5.1 pick is cleared and no longer listed. + await startNewCharacter(user); + await user.type(await screen.findByRole('textbox', { name: 'Name' }), 'E2E Switcher'); // the name is required to leave the Rules step + await user.click(screen.getByRole('radio', { name: /2014 rules/ })); + await user.click(screen.getByRole('button', { name: 'Next: class' })); + await user.click(screen.getByRole('button', { name: 'Next: ability scores' })); + await user.click(screen.getByRole('radio', { name: 'Enter by hand' })); + await user.click(screen.getByRole('button', { name: 'Next: species' })); + const species = screen.getByRole('group', { name: 'Species' }); + const halfOrc = () => within(species).getByRole('radio', { name: /^Half-Orc/ }); + await waitFor(() => expect(halfOrc().getAttribute('aria-disabled')).toBeNull()); + await user.click(halfOrc()); + expect(halfOrc().checked).toBe(true); + for (let i = 0; i < 3; i++) await user.click(screen.getByRole('button', { name: 'Back' })); // species, scores, class, rules + await user.click(screen.getByRole('radio', { name: /2024 rules/ })); + await user.click(screen.getByRole('button', { name: 'Next: class' })); + await user.click(screen.getByRole('button', { name: 'Next: ability scores' })); + await user.click(screen.getByRole('button', { name: 'Next: species' })); + // D31: the 5.1 species leaves the list altogether, and the pick is cleared. + await waitFor(() => expect(within(screen.getByRole('group', { name: 'Species' })).queryByRole('radio', { name: /^Half-Orc/ })).toBeNull()); + expect(within(screen.getByRole('group', { name: 'Species' })).getByRole('radio', { name: 'None' }).checked).toBe(true); + await user.click(screen.getByRole('button', { name: 'Cancel' })); + await user.click(await screen.findByRole('button', { name: 'Discard' })); // the rules family was changed: Cancel asks first + + // Campaign: an SRD 5.1 source, then SRD 5.2.1. The hidden 5.1 source is not saved with the campaign. + await user.click(screen.getByRole('button', { name: 'Campaigns' })); + await user.click(await screen.findByRole('button', { name: 'New campaign' })); + const form = screen.getByRole('form', { name: 'Campaign' }); + await user.type(within(form).getByRole('textbox', { name: 'Campaign name' }), 'E2E Switched'); + await user.click(within(form).getByRole('radio', { name: /2014 rules/ })); + await user.click(within(form).getByRole('checkbox', { name: /^System Reference Document 5\.1/ })); + await user.click(within(form).getByRole('radio', { name: /2024 rules/ })); + await user.click(within(form).getByRole('button', { name: 'Save campaign' })); + await waitFor(() => expect(appStatus().textContent).toBe('Saved the campaign E2E Switched.')); + const saved = screen.getAllByRole('listitem').find((li) => li.textContent?.startsWith('E2E Switched'))!; + expect(saved.textContent).toMatch(/0 allowed sources/); +}); + +it('builds a spellcaster: picks spells in the builder, casts one, rolls a spell attack and a long rest restores the slot', async () => { + // D04 (M2 spellcasting) with the original fixture caster "Fixture Arcanist" (invented tables: 2 level 1 slots at level 1). + const user = userEvent.setup(); + render(); + await createCharacter(user, { name: 'E2E Sage', family: 'srd-5.2.1', scores: { Intelligence: 16 }, cls: /^Fixture Arcanist/ }); + + // Int 16 (+3) at level 1: 3 cantrips, max(1, 3 + 1) = 4 prepared. Only spells on the caster's list and castable levels. + let picker = await screen.findByRole('group', { name: /^Fixture Arcanist spells \(0 of 3 cantrips, 0 of 4 prepared spells\)/ }); + expect(within(picker).queryByRole('checkbox', { name: /Fixture Mending Word/ })).toBeNull(); // another list + expect(within(picker).queryByRole('checkbox', { name: /Fixture Ember Wave/ })).toBeNull(); // level 3: no slot yet + // D30: the search hides what does not match and says how many are shown; clearing it brings everything back. + const search = within(picker).getByRole('searchbox', { name: 'Search Fixture Arcanist spells by name' }); + await user.type(search, 'frost'); + expect(within(picker).getByText(/^1 of \d+ spells shown$/)).toBeTruthy(); + expect(within(picker).queryByRole('checkbox', { name: /^Fixture Spark/ })).toBeNull(); + await user.clear(search); + await user.click(within(picker).getByRole('checkbox', { name: /^Fixture Spark/ })); + picker = await screen.findByRole('group', { name: /^Fixture Arcanist spells \(1 of 3 cantrips/ }); + // R23: a chosen spell the search hides is named in the status, and the legend's count still includes it. + const search2 = within(picker).getByRole('searchbox', { name: 'Search Fixture Arcanist spells by name' }); + await user.type(search2, 'frost'); + expect(within(picker).getByText(/^1 of \d+ spells shown, 1 chosen hidden by the search$/)).toBeTruthy(); + expect(within(picker).queryByRole('checkbox', { name: /^Fixture Spark/ })).toBeNull(); + await screen.findByRole('group', { name: /^Fixture Arcanist spells \(1 of 3 cantrips/ }); + await user.type(search2, 'zz'); + expect(within(picker).getByText(/No spells match “frostzz”/)).toBeTruthy(); + await user.clear(search2); + expect(within(picker).getByRole('checkbox', { name: /^Fixture Spark/ })).toBeTruthy(); + await user.click(within(picker).getByRole('checkbox', { name: /^Fixture Frost Ring/ })); + await screen.findByRole('group', { name: /^Fixture Arcanist spells \(1 of 3 cantrips, 1 of 4 prepared spells\)/ }); + await user.click(screen.getByRole('button', { name: 'Create and save' })); + + const sheet = await screen.findByRole('article', { name: 'E2E Sage' }); + await openTab(user, sheet, 'Spells'); + const spells = () => within(screen.getByRole('article', { name: 'E2E Sage' })).getByRole('region', { name: 'Spells and slots' }); + expect(within(spells()).getByRole('heading', { name: 'Fixture Arcanist (level 1, Intelligence): spell attack +5, save DC 13' })).toBeTruthy(); + expect(within(spells()).getByRole('heading', { name: 'Level 1 slots: 2 of 2' })).toBeTruthy(); + expect(within(sheet).getByRole('heading', { name: /^Spell attack bonus: \+5/ })).toBeTruthy(); + + // Concentration (D19) is not driven here: the fixture pack's only concentration spell (Fixture Veil) is level 2, which this + // level 1 character cannot prepare. The panel and its service rules are covered by ConcentrationPanel.test.tsx and PlayCommandTests. + // Casting spends a slot (a confirmed play change); rolling a spell spends nothing. + await user.click(within(spells()).getByRole('button', { name: 'Cast Fixture Frost Ring (spend a slot)' })); + await waitFor(() => expect(within(spells()).getByRole('heading', { name: 'Level 1 slots: 1 of 2' })).toBeTruthy()); + await user.click(within(spells()).getByRole('button', { name: 'Roll Fixture Spark attack' })); + const lastRoll = screen.getByRole('status', { name: 'Last roll' }); + await waitFor(() => expect(lastRoll.textContent).toMatch(/Fixture Spark \(spell attack\): \d+ \(1d20\)/)); + expect(lastRoll.textContent).toMatch(/Fixture Arcanist spell attack \+5/); + expect(within(spells()).getByRole('heading', { name: 'Level 1 slots: 1 of 2' })).toBeTruthy(); + + // The long rest proposes the slot back. + await openTab(user, sheet, 'Play'); + await user.click(screen.getByRole('button', { name: 'Long rest…' })); + const rest = await screen.findByRole('region', { name: 'Long rest' }); + expect(await within(rest).findByRole('checkbox', { name: /^Level 1 spell slots: 1 → 2/ })).toBeTruthy(); + await user.click(within(rest).getByRole('button', { name: 'Finish long rest' })); + await openTab(user, sheet, 'Spells'); + await waitFor(() => expect(within(spells()).getByRole('heading', { name: 'Level 1 slots: 2 of 2' })).toBeTruthy()); +}); + +it('creates a character with the standard array (D32)', async () => { + const user = userEvent.setup(); + render(); + await createCharacter(user, { name: 'E2E Array', family: 'srd-5.2.1', cls: /^Barbarian/ }); + await user.click(await screen.findByRole('button', { name: 'Create and save' })); + const sheet = await screen.findByRole('article', { name: 'E2E Array' }); + await openTab(user, sheet, 'Skills and saves'); + expect(within(sheet).getByRole('heading', { name: /^Strength score: 15/ })).toBeTruthy(); + expect(within(sheet).getByRole('heading', { name: /^Charisma score: 8/ })).toBeTruthy(); +}); + +it('rolls ability scores through the dice engine and assigns them (D32)', async () => { + const user = userEvent.setup(); + render(); + await startNewCharacter(user); + await user.type(await screen.findByRole('textbox', { name: 'Name' }), 'E2E Rolled'); + await user.click(screen.getByRole('radio', { name: /2024 rules/ })); + await user.click(screen.getByRole('button', { name: 'Next: class' })); + await user.click(await screen.findByRole('radio', { name: /^Barbarian/ })); + await user.click(screen.getByRole('button', { name: 'Next: ability scores' })); + await user.click(screen.getByRole('radio', { name: 'Roll' })); + await user.click(screen.getByRole('button', { name: 'Roll six scores (4d6, drop the lowest)' })); + const sets = await screen.findByRole('list', { name: 'Rolled sets' }); + const lines = within(sets).getAllByRole('listitem').map((li) => li.textContent!); + expect(lines).toHaveLength(6); + // Each line's total is the sum of the three kept dice (the fourth is dropped). + const totals: number[] = []; + for (const line of lines) { + const m = /^Roll \d: (\d+) \((\d), (\d), (\d), dropped (\d)\)$/.exec(line); + expect(m, line).not.toBeNull(); + const [total, a, b, c, dropped] = m!.slice(1).map(Number) as [number, number, number, number, number]; + expect(total).toBe(a + b + c); + expect(dropped).toBeLessThanOrEqual(Math.min(a, b, c)); + totals.push(total); + } + const group = screen.getByRole('group', { name: 'Assign the rolled scores' }); + const assigned = new Map(); + for (const label of ['Strength', 'Dexterity', 'Constitution', 'Intelligence', 'Wisdom', 'Charisma'] as const) { + const select = within(group).getByRole('combobox', { name: label }); + const free = within(select).getAllByRole('option').find((o) => !(o as HTMLOptionElement).disabled && o.textContent !== 'Choose')!; + await user.selectOptions(select, (free as HTMLOptionElement).value); + assigned.set(label, Number((free as HTMLOptionElement).value)); + } + expect(screen.getByText('Assigned: 6 of 6')).toBeTruthy(); + expect([...assigned.values()].sort((x, y) => x - y)).toEqual([...totals].sort((x, y) => x - y)); // every rolled total used once + await user.click(screen.getByRole('button', { name: 'Next: species' })); + await user.click(screen.getByRole('button', { name: 'Next: background' })); + await user.click(screen.getByRole('button', { name: 'Next: gear' })); + await user.click(screen.getByRole('button', { name: /^Skip: I'll add gear myself/ })); + await user.click(screen.getByRole('button', { name: 'Next: choices' })); + await user.click(await screen.findByRole('button', { name: 'Create and save' })); + const sheet = await screen.findByRole('article', { name: 'E2E Rolled' }); + await openTab(user, sheet, 'Skills and saves'); + // The sheet's base scores are the assigned rolled totals (increases come from content the draft does not pin). + for (const [label, value] of assigned) expect(within(sheet).getByRole('heading', { name: new RegExp(`^${label} score: ${value}\\b`) })).toBeTruthy(); +}); + +it('previews a Fighter 3 at level 5 from the level-up step: Extra Attack shows and nothing is saved (D82)', async () => { + const user = userEvent.setup(); + const created = await client.createCharacter({ + name: 'E2E Previewer', + rulesFamily: 'srd-5.2.1', + baseAbilities: { str: 16, dex: 14, con: 14, int: 10, wis: 12, cha: 8 }, + pins: [srd(1), srd(2)], + classes: [{ class: fighter(0), level: 3 }], + choices: [{ source: srd(2), choiceId: 'soldier-ability-scores', selected: [srd(4)] }], + }); + const before = (await client.getCharacter(created.character.id)).character; + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Previewer/ })); + await user.click(within(await screen.findByRole('article', { name: 'E2E Previewer' })).getByRole('button', { name: 'Level up' })); + + const form = await screen.findByRole('form', { name: 'Preview at level' }); + const level = within(form).getByRole('spinbutton', { name: 'Level to preview' }); + await user.clear(level); + await user.type(level, '5'); + await user.click(within(form).getByRole('button', { name: 'Preview' })); + const preview = await screen.findByRole('region', { name: 'Preview at level 5' }); + expect(within(preview).getByText('Extra Attack')).toBeTruthy(); + await user.click(within(preview).getByRole('button', { name: 'Close preview' })); + expect(screen.queryByRole('region', { name: 'Preview at level 5' })).toBeNull(); + + await user.click(screen.getByRole('button', { name: 'Cancel' })); + await expectStatus(/Draft discarded/); + const after = (await client.getCharacter(created.character.id)).character; + expect(after.level).toBe(3); + expect(after).toEqual(before); // the store received no write +}); + +it('levels a Cleric into Wizard: what each class gives, the prerequisite warning that never blocks, and the new class on the sheet (D99)', async () => { + const user = userEvent.setup(); + const listed = await client.listContent('srd-5.2.1'); + const named = (kind: string, name: RegExp) => listed.find((o) => o.compatible && !o.superseded && o.kind === kind && name.test(o.name))!.reference; // the list holds both families + const wizard = named('class', /^Wizard/); + const created = await client.createCharacter({ + name: 'E2E Multiclasser', + rulesFamily: 'srd-5.2.1', + baseAbilities: { str: 10, dex: 12, con: 14, int: 8, wis: 15, cha: 10 }, + pins: [named('species', /^Dwarf/), named('background', /^Soldier/)], + classes: [{ class: named('class', /^Cleric/), level: 1 }], + }); + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Multiclasser/ })); + await user.click(within(await screen.findByRole('article', { name: 'E2E Multiclasser' })).getByRole('button', { name: 'Level up' })); + + // The character's own class says what it gives at its next level; the new class waits behind "Another class…". + expect(await screen.findByRole('radio', { name: /^Cleric 2 — what you get: / })).toBeTruthy(); + await user.click(await screen.findByRole('radio', { name: 'Another class…' })); + const select = await screen.findByRole('combobox', { name: 'Class to start' }); + await user.selectOptions(select, await within(select).findByRole('option', { name: 'Wizard' })); + expect(await screen.findByText('Wizard — needs Intelligence 13 (you have 8). You can still take it.')).toBeTruthy(); + + const next = screen.getByRole('button', { name: 'Next: choices' }); + expect(next.getAttribute('aria-disabled')).toBeNull(); // advice, never a block + await user.click(next); + await user.click(await screen.findByRole('button', { name: 'Save level-up' })); + + const sheet = await screen.findByRole('article', { name: 'E2E Multiclasser' }); + expect(within(sheet).getByText('Level 2')).toBeTruthy(); + const saved = (await client.getCharacter(created.character.id)).character; + expect(saved.classes.map((c) => [c.class.contentId, c.level])).toContainEqual([wizard.contentId, 1]); +}); + +it('tries the sample from the chooser, plays it and removes it (D95)', async () => { + const user = userEvent.setup(); + // The DevHost is shared, so Home is not empty here (the welcome card is covered by HomePanel's tests): the sample is reached + // through the chooser, which offers it while no sample exists. A leftover sample from a failed run is removed first. + for (const c of await client.listCharacters()) { + if (c.origin !== 'sample') continue; + try { + await client.deleteSample(c.id); + } catch (error) { + // Archiving it would hide "Try the sample" in the chooser, so the test cannot go on either way. + if (error instanceof TomeStackError && error.code === 'character.sample-has-snapshots') { + throw new Error('A leftover sample with snapshots is in the DevHost data; remove it by hand.', { cause: error }); + } + throw error; + } + } + + render(); + await user.click(await screen.findByRole('button', { name: '+ Add a character' })); + const choice = await screen.findByRole('radio', { name: /^Try the sample/ }); + await user.click(choice); + await user.click(screen.getByRole('button', { name: 'Continue' })); + + const sheet = await screen.findByRole('article', { name: 'Wren Ashdown' }); + expect(within(sheet).getByRole('tab', { name: 'Play' }).getAttribute('aria-selected')).toBe('true'); + await waitFor(() => expect(summaryValue(sheet, 'Armor Class')).toMatch(/^16/)); + expect(within(sheet).getByText('This is a sample character.')).toBeTruthy(); + + // Remove sample asks first: focus goes to Keep, Keep puts it back on Remove sample and leaves the character alone. + await user.click(within(sheet).getByRole('button', { name: 'Remove sample' })); + const dialog = await within(sheet).findByRole('alertdialog', { name: 'Remove Wren Ashdown?' }); + expect(within(dialog).getByText('Remove Wren Ashdown? This cannot be undone.')).toBeTruthy(); + await waitFor(() => expect(document.activeElement).toBe(within(dialog).getByRole('button', { name: 'Keep' }))); + await user.click(within(dialog).getByRole('button', { name: 'Keep' })); + expect(within(sheet).queryByRole('alertdialog')).toBeNull(); + expect(document.activeElement).toBe(within(sheet).getByRole('button', { name: 'Remove sample' })); + + await user.click(within(sheet).getByRole('button', { name: 'Remove sample' })); + await user.click(within(await within(sheet).findByRole('alertdialog')).getByRole('button', { name: 'Remove' })); + + // Back home, the sample is gone from the sidebar and from the service. + await waitFor(() => expect(screen.queryByRole('article', { name: 'Wren Ashdown' })).toBeNull()); + await waitFor(() => expect(screen.queryByRole('button', { name: /^Wren Ashdown/ })).toBeNull()); + expect((await client.listCharacters()).some((c) => c.origin === 'sample')).toBe(false); +}); + +it('builds a 2014 Cleric with its kit: seven steps, option a gives AC 16 with the shield, Mace on Play, the kit on Gear (Wave 3, D97)', async () => { + const user = userEvent.setup(); + render(); + let preview = ''; + await createCharacter(user, { + name: 'E2E Kitted', + family: 'srd-5.1', + scores: { Dexterity: 10 }, // scale mail 14 + 0 Dex + shield 2 + cls: /^Cleric/, + kit: true, + beforeChoices: async () => { + // The Gear step shows the live Armor Class for the kit as chosen (option a for every pick). + await waitFor(() => expect(screen.getByText(/^AC with this gear: 16/)).toBeTruthy()); + preview = screen.getByText(/^AC with this gear:/).textContent ?? ''; + }, + }); + expect(preview).toMatch(/16/); + await user.click(await screen.findByRole('button', { name: 'Create and save' })); + + const sheet = await screen.findByRole('article', { name: 'E2E Kitted' }); + await waitFor(() => expect(summaryValue(sheet, 'Armor Class')).toMatch(/^16/)); + await openTab(user, sheet, 'Play'); + expect(within(sheet).getAllByText(/Mace/).length).toBeGreaterThan(0); + await openTab(user, sheet, 'Gear'); + const equipment = screen.getByRole('region', { name: 'Equipment' }); + for (const item of [/Mace/, /Scale mail/, /Shield/]) expect(within(equipment).getAllByText(item).length).toBeGreaterThan(0); +}, 180_000); + +it('a 2024 class taking gold has coins and no kit items (Wave 3, D97)', async () => { + const user = userEvent.setup(); + render(); + await createCharacter(user, { + name: 'E2E Goldtaker', + family: 'srd-5.2.1', + cls: /^Barbarian/, + background: /^Soldier/, + kit: true, + beforeChoices: async () => { + // Option b of the Barbarian's kit is gold only, and so is the Soldier's. + const classKit = await screen.findByRole('region', { name: /^From your class/ }); + await user.click(within(classKit).getByRole('radio', { name: /Instead: 75 gp/ })); + const backgroundKit = screen.getByRole('region', { name: /^From your background/ }); + await user.click(within(backgroundKit).getByRole('radio', { name: /Instead: 50 gp/ })); + }, + }); + await user.click(await screen.findByRole('button', { name: 'Create and save' })); + + const sheet = await screen.findByRole('article', { name: 'E2E Goldtaker' }); + await openTab(user, sheet, 'Gear'); + const equipment = screen.getByRole('region', { name: 'Equipment' }); + expect(within(equipment).queryAllByRole('checkbox', { name: /^Equip / })).toHaveLength(0); + const gold = await screen.findByRole('spinbutton', { name: 'Gold (gp)' }); + expect(gold.value).toBe('125'); +}, 180_000); diff --git a/src/Ui/e2e/character-import.e2e.tsx b/src/Ui/e2e/character-import.e2e.tsx new file mode 100644 index 00000000..85cad1fa --- /dev/null +++ b/src/Ui/e2e/character-import.e2e.tsx @@ -0,0 +1,382 @@ +// End-to-end UI flow against the real DevHost (same CommandDispatcher as the shell). Only the transport differs from the desktop +// app: HTTP to loopback instead of the WebView2 bridge, so export takes the download fallback instead of the native Save dialog. +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, expect, it, vi } from 'vitest'; +import { App } from '../src/App'; +import { client } from '../src/api/client'; +import { expectStatus, openTab, summaryValue } from './helpers'; + +vi.mock('../src/api/client', async (importOriginal) => { + const { inject } = await import('vitest'); + const { createHttpTransport } = await import('../src/api/transport'); + const original = await importOriginal(); + const { endpoint, token } = inject('devHost'); + return { ...original, client: original.createClient(createHttpTransport(endpoint, { 'X-TomeStack-Token': token })) }; +}); + +vi.mock('../src/files', async (importOriginal) => ({ + ...(await importOriginal()), + downloadBase64: vi.fn(), +})); + +afterEach(() => { + cleanup(); + // One jsdom window serves the whole file: a preference or `html` attribute left by one test would leak into the next. + // The per-character tab memory stays (ids are unique per test and the deep-link test relies on it). + for (const key of Object.keys(localStorage)) if (key.startsWith('tomestack.') && !key.startsWith('tomestack.sheetTab.')) localStorage.removeItem(key); + for (const key of Object.keys(document.documentElement.dataset)) delete document.documentElement.dataset[key]; +}); + +// ---- character import from a character sheet PDF: a D&D Beyond export or the fillable 2014 sheet (features/ddb-pdf-import.md S4, item 14) ---- +// The committed sheet is invented: "Testy McFixture", an original fixture Arcanist 3 / Chanter 2 whose spell "Fixture Veil" +// is on both casters' lists. The DevHost has no Open dialog, so the file input sends the bytes (ddb.readData). + +const ddbSheet = () => readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-ddb-sheet.pdf')); + +async function startDdbImport(user: ReturnType) { + await user.click(await screen.findByRole('button', { name: '+ Add a character' })); + const sheet = await screen.findByRole('radio', { name: 'From a character sheet (PDF or text)' }); + await waitFor(() => expect(sheet.disabled).toBe(false)); // needs app.info + await user.click(sheet); + await user.click(screen.getByRole('button', { name: 'Continue' })); +} + +const wotcSheet = () => readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-wotc-sheet.pdf')); + +async function readDdbSheet(user: ReturnType) { + await user.click(await screen.findByRole('button', { name: 'Choose PDF…' })); + await user.upload(screen.getByLabelText('Character sheet PDF file'), new File([ddbSheet()], 'fixture-ddb-sheet.pdf', { type: 'application/pdf' })); + expect(await screen.findByText('Fixture Arcanist 3 / Fixture Chanter 2', {}, { timeout: 30000 })).toBeTruthy(); +} + +// ---- item 16 (D16(c)): unmatched features that carry text become reference drafts ---- + +async function toDdbSummary(user: ReturnType) { + await startDdbImport(user); + await readDdbSheet(user); + await nextWhenReady(user, 'Next: rules'); + await nextWhenReady(user, 'Next: matches'); + const matches = await screen.findByRole('region', { name: 'Matches' }); + const veil = await within(matches).findByRole('combobox', { name: 'Match for Fixture Veil' }); + await user.selectOptions(veil, '1'); // the option labels are the same for both casters once a character exists, so pick by position + await nextWhenReady(user, 'Next: numbers'); + await nextWhenReady(user, 'Next: summary'); +} + +/** Every revision (drafts too) in the import-derived source, from the call the studio uses; 0 while the source does not exist yet. */ +async function importSourceRevisions(): Promise { + const source = (await client.listSources()).find((s) => s.title === 'Characters imported from sheets'); + return source ? (await client.contentBySource(source.id)).reduce((n, entry) => n + entry.revisions.length, 0) : 0; +} + +/** The Cancel path: tick Publish at the summary, then Cancel; nothing is written (no source, no draft). Unmounts when done. */ +async function cancelAtSummary(user: ReturnType) { + const sources = (await client.listSources()).map((s) => s.id).sort(); + const revisions = await importSourceRevisions(); + const { unmount } = render(); + await toDdbSummary(user); + const section = await screen.findByRole('region', { name: 'Reference drafts' }); + await user.click(within(section).getByRole('checkbox', { name: /^Make these \d+ reference drafts available to characters$/ })); + + await user.click(screen.getByRole('button', { name: 'Cancel' })); + + await expectStatus(/Import cancelled\. Nothing was saved\./); + expect((await client.listSources()).map((s) => s.id).sort()).toEqual(sources); + expect(await importSourceRevisions()).toBe(revisions); + unmount(); +} + +// One test, Cancel path first and then a fresh import: the service does not draft an entry the import-derived source holds +// already (R106), so the drafts exist only for the first import of this sheet. No earlier test may import +// fixture-ddb-sheet.pdf before this one (and none does: the main import test below runs after it). + +it('Cancel writes no reference drafts; a fresh import lists them unticked and publishing makes them studio content', async () => { + const user = userEvent.setup(); + await cancelAtSummary(user); + const revisions = await importSourceRevisions(); + render(); + await toDdbSummary(user); + + const section = await screen.findByRole('region', { name: 'Reference drafts' }); + expect(section.textContent).toContain('Fixture Steady Breath'); + expect(section.textContent).toContain('An invented line of fixture description.'); + const tick = within(section).getByRole('checkbox', { name: /^Make these \d+ reference drafts available to characters$/ }); + expect(tick.checked).toBe(false); + expect(within(section).getByRole('note').textContent).toContain('Features are kept as reference content in Homebrew; the gap notes stay on the character.'); + expect((await client.listContent('srd-5.1')).some((o) => o.name === 'Fixture Steady Breath')).toBe(false); + + await user.click(tick); + expect(document.activeElement).toBe(tick); + const create = await screen.findByRole('button', { name: 'Create character' }); + await waitFor(() => expect(create.disabled).toBe(false)); + await user.click(create); + + await expectStatus(/Character created from the character sheet/); + expect((await client.listContent('srd-5.1')).some((o) => o.name === 'Fixture Steady Breath')).toBe(true); + expect(await importSourceRevisions()).toBeGreaterThan(revisions); +}); + +it('imports a D&D Beyond sheet, resolves a choice, keeps one sheet number as an override and creates the character', async () => { + const user = userEvent.setup(); + render(); + await startDdbImport(user); + await readDdbSheet(user); + + await user.click(screen.getByRole('button', { name: 'Next: rules' })); + // The 2014-style layout suggests SRD 5.1; the user could pick the other family. + expect(screen.getByRole('radio', { name: /2014 rules/ }).checked).toBe(true); + await user.click(screen.getByRole('radio', { name: "Use the character sheet's values" })); // D16h preset + await user.click(screen.getByRole('button', { name: 'Next: matches' })); + + const matches = await screen.findByRole('region', { name: 'Matches' }); + const veil = await within(matches).findByRole('combobox', { name: 'Match for Fixture Veil' }); + await user.click(within(matches).getByRole('radio', { name: 'Needs a choice' })); + expect(within(matches).getAllByRole('rowheader').map((h) => h.textContent)).toEqual(['Fixture Veil']); + // The caster names come from content.list, which can answer after the rows show (more bundled packs make it slower). + const chanter = await waitFor(() => { + const option = within(veil).getAllByRole('option').find((o) => /Fixture Chanter/.test(o.textContent ?? '')); + expect(option).toBeDefined(); + return option!; + }); + await user.selectOptions(veil, chanter); + await waitFor(() => expect(within(matches).queryAllByRole('rowheader')).toHaveLength(0)); + // Not installed (the background, a feat, two items, the features): listed, and kept as gap notes. + await user.click(within(matches).getByRole('radio', { name: 'Not found' })); + expect(within(matches).getByRole('rowheader', { name: 'Fixture Archivist' })).toBeTruthy(); + + // Next waits while the proposal for the latest choice is loading. + const nextStep = async (name: string) => { + const next = screen.getByRole('button', { name }); + await waitFor(() => expect(next.disabled).toBe(false)); + await user.click(next); + }; + await nextStep('Next: numbers'); + const armorClass = await screen.findByRole('radiogroup', { name: 'Armor Class' }); + expect(within(screen.getByRole('radiogroup', { name: 'Armor Class' })).getByRole('radio', { name: "Keep the sheet's number" }).checked).toBe(true); // pre-filled by the preset + await user.click(within(armorClass).getByRole('radio', { name: "Keep the sheet's number" })); + await nextStep('Next: summary'); + + const create = await screen.findByRole('button', { name: 'Create character' }); + await waitFor(() => expect(create.disabled).toBe(false)); + await user.click(create); + + await expectStatus(/Character created from the character sheet: 3 numbers set by hand, \d+ gap note\(s\)/); + const sheet = await screen.findByRole('article', { name: 'Testy McFixture' }); + expect(summaryValue(sheet, 'Armor Class')).toContain('(set by hand)'); + await openTab(user, sheet, 'Skills and saves'); + expect(within(sheet).getByRole('heading', { name: /^Armor Class:/ }).textContent).toContain('set by hand (calculated'); +}); + +it('imports the fillable 2014 sheet through the same entry: the layout is named, prose lands in session notes and the details fill', async () => { + const user = userEvent.setup(); + render(); + await startDdbImport(user); + await user.click(await screen.findByRole('button', { name: 'Choose PDF…' })); + await user.upload(screen.getByLabelText('Character sheet PDF file'), new File([wotcSheet()], 'fixture-wotc-sheet.pdf', { type: 'application/pdf' })); + expect(await screen.findByText('Fixture Arcanist 3', {}, { timeout: 30000 })).toBeTruthy(); + expect(screen.getByText('the fillable 2014 sheet')).toBeTruthy(); + + const nextStep = async (name: string) => { + const next = await screen.findByRole('button', { name }); + await waitFor(() => expect(next.disabled).toBe(false)); + await user.click(next); + }; + await nextStep('Next: rules'); + await nextStep('Next: matches'); + await nextStep('Next: numbers'); + await nextStep('Next: summary'); + expect(await screen.findByRole('region', { name: 'Not brought over' })).toBeTruthy(); + const create = await screen.findByRole('button', { name: 'Create character' }); + await waitFor(() => expect(create.disabled).toBe(false)); + await user.click(create); + + await expectStatus(/Character created from the character sheet: \d+ numbers? set by hand, \d+ gap note\(s\)/); + const sheet = await screen.findByRole('article', { name: 'Testy McFixture' }); + await openTab(user, sheet, 'Journal'); + expect(await within(sheet).findByText(/Testy backstory\./)).toBeTruthy(); + expect(within(within(sheet).getByRole('form', { name: 'Details' })).getByRole('textbox', { name: 'Alignment' }).value).toBe('Fixture Neutral'); +}); + +it('cancelling the D&D Beyond import at each step leaves the character list unchanged', async () => { + const user = userEvent.setup(); + const before = (await client.listCharacters()).map((c) => c.id).sort(); + render(); + const next = ['Next: rules', 'Next: matches', 'Next: numbers', 'Next: summary']; + + for (let step = 1; step <= 5; step++) { + await startDdbImport(user); + await readDdbSheet(user); + for (const label of next.slice(0, step - 1)) { + const button = await screen.findByRole('button', { name: label }); + await waitFor(() => expect(button.disabled).toBe(false)); + await user.click(button); + } + await screen.findByRole('heading', { name: ['Choose the sheet', 'Rules and campaign', 'Matches', 'Numbers', 'Create'][step - 1] }); + await user.click(screen.getByRole('button', { name: 'Cancel' })); + await waitFor(() => expect(screen.queryByRole('button', { name: 'Choose PDF…' })).toBeNull()); + await waitFor(() => expect(screen.queryByRole('heading', { name: 'Create' })).toBeNull()); + await expectStatus(/Import cancelled\. Nothing was saved\./); + } + + expect((await client.listCharacters()).map((c) => c.id).sort()).toEqual(before); +}); + +// ---- item 19a (D37): character import from pasted or file text ---- +// The text is invented. "Barbarian 1" is an installed SRD class with no choice to answer at level 1. + +const fixtureText = [ + '# Testy Texter', + 'Class: Barbarian 1', + 'STR 16 DEX 14 CON 14 INT 8 WIS 9 CHA 10', + 'Gold: 12', + 'Languages: Common, Fixturish', + 'Some line the reader cannot place', +].join('\n'); + +it('imports a character from pasted text: the unreadable line is listed and kept as a session note, and a too-large file is refused by size', async () => { + const user = userEvent.setup(); + render(); + await startDdbImport(user); + + await user.click(await screen.findByRole('button', { name: 'Import a character from text…' })); + const box = await screen.findByRole('textbox', { name: 'Character text' }); + await waitFor(() => expect(document.activeElement).toBe(box)); + + // A file over the limit is refused by its size alone, before any of it is read. + const big = new File(['x'], 'big-fixture.txt', { type: 'text/plain' }); + Object.defineProperty(big, 'size', { value: 300_000 }); + await user.upload(screen.getByLabelText('Character text file'), big); + expect((await screen.findByRole('alert')).textContent).toContain('300,000'); + expect(box.value).toBe(''); + + await user.click(box); + await user.paste(fixtureText); + await user.click(screen.getByRole('button', { name: 'Read the text' })); + expect(await screen.findByText('pasted or file text')).toBeTruthy(); + + await nextWhenReady(user, 'Next: rules'); + await nextWhenReady(user, 'Next: matches'); + await nextWhenReady(user, 'Next: numbers'); + await nextWhenReady(user, 'Next: summary'); + const notRead = await screen.findByRole('region', { name: 'Lines not read' }); + expect(notRead.textContent).toContain('Some line the reader cannot place'); + const tick = within(notRead).getByRole('checkbox', { name: 'Keep the lines that were not read as session notes' }); + expect(tick.checked).toBe(true); + + const create = await screen.findByRole('button', { name: 'Create character' }); + await waitFor(() => expect(create.disabled).toBe(false)); + await user.click(create); + + await expectStatus(/Character created from the character sheet/); + const sheet = await screen.findByRole('article', { name: 'Testy Texter' }); + await openTab(user, sheet, 'Journal'); + expect(await within(sheet).findByText(/Some line the reader cannot place/)).toBeTruthy(); +}); + +// ---- item 19b (D37, ADR-013): a PDF with no form fields is read as text through the same entry ---- +// The committed sheet is a generated text-only PDF (no form): "Testy Printout", an invented Fixture Arcanist 3. + +const textSheet = () => readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-text-sheet.pdf')); + +it('imports a PDF that has no form fields: its page text is read, the layout says so, and the character is created', async () => { + const user = userEvent.setup(); + render(); + await startDdbImport(user); + await user.click(await screen.findByRole('button', { name: 'Choose PDF…' })); + await user.upload(screen.getByLabelText('Character sheet PDF file'), new File([textSheet()], 'fixture-text-sheet.pdf', { type: 'application/pdf' })); + expect(await screen.findByText('Fixture Arcanist 3', {}, { timeout: 30000 })).toBeTruthy(); + expect(screen.getByText('text from the PDF')).toBeTruthy(); + + await nextWhenReady(user, 'Next: rules'); + await nextWhenReady(user, 'Next: matches'); + await nextWhenReady(user, 'Next: numbers'); + await nextWhenReady(user, 'Next: summary'); + const create = await screen.findByRole('button', { name: 'Create character' }); + await waitFor(() => expect(create.disabled).toBe(false)); + await user.click(create); + + await expectStatus(/Character created from the character sheet/); + expect(await screen.findByRole('article', { name: 'Testy Printout' })).toBeTruthy(); +}); + +// ---- item 15 (D35): a class the sheet names that TomeStack does not have, offered as a homebrew class ---- +// The generated sheet names the invented "Fixture Tinkerer" 3 with hit dice 3d8; no installed content has it. + +const tinkererSheet = () => readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-tinkerer-sheet.pdf')); + +async function readTinkererSheet(user: ReturnType) { + await user.click(await screen.findByRole('button', { name: 'Choose PDF…' })); + await user.upload(screen.getByLabelText('Character sheet PDF file'), new File([tinkererSheet()], 'fixture-tinkerer-sheet.pdf', { type: 'application/pdf' })); + expect(await screen.findByText('Fixture Tinkerer 3', {}, { timeout: 30000 })).toBeTruthy(); +} + +async function nextWhenReady(user: ReturnType, name: string) { + const next = await screen.findByRole('button', { name }); + await waitFor(() => expect(next.disabled).toBe(false)); + await user.click(next); +} + +it('creates a draft homebrew class from an uninstalled class, leaves Publish it unticked and the character gets nothing from it', async () => { + const user = userEvent.setup(); + const before = new Set((await client.listCharacters()).map((c) => c.id)); + render(); + await startDdbImport(user); + await readTinkererSheet(user); + await nextWhenReady(user, 'Next: rules'); + await nextWhenReady(user, 'Next: matches'); + + const matches = await screen.findByRole('region', { name: 'Matches' }); + const box = await within(matches).findByRole('checkbox', { name: /Create a homebrew class Fixture Tinkerer/ }); + expect(box.getAttribute('aria-disabled')).toBeNull(); + await user.click(box); + await waitFor(() => expect(within(matches).getByRole('checkbox', { name: /Create a homebrew class/ }).checked).toBe(true)); + await waitFor(() => expect(within(matches).getByText(/A homebrew class is created for it/)).toBeTruthy()); + + await nextWhenReady(user, 'Next: numbers'); + await nextWhenReady(user, 'Next: summary'); + const stub = await screen.findByRole('region', { name: 'Homebrew class to create' }); + for (const text of ['Fixture Tinkerer', 'd8', 'Strength', 'Characters imported from sheets']) expect(stub.textContent).toContain(text); + expect(within(stub).getByRole('checkbox', { name: 'Make it available to characters' }).checked).toBe(false); + expect(within(stub).getByRole('note').textContent).toBe('The class is a draft: the character gets nothing from it until you make it available to characters in Homebrew and accept the update on the character.'); + + const create = await screen.findByRole('button', { name: 'Create character' }); + await waitFor(() => expect(create.disabled).toBe(false)); + await user.click(create); + + await expectStatus(/Character created from the character sheet/); + await screen.findByRole('article', { name: 'Testy Tinker' }); + const created = (await client.listCharacters()).find((c) => !before.has(c.id) && c.name === 'Testy Tinker')!; + const view = await client.getCharacter(created.id); + expect(view.sheet.diagnostics.map((d) => d.code)).toContain('content.unpublished'); + const source = (await client.listSources()).find((s) => s.title === 'Characters imported from sheets')!; + expect(source.importDerived).toBe(true); + expect(source.redistributable).toBe(false); +}); + +it('cancelling after choosing to create a homebrew class writes nothing: no character, no source', async () => { + const user = userEvent.setup(); + const characters = (await client.listCharacters()).map((c) => c.id).sort(); + const sources = (await client.listSources()).map((s) => s.id).sort(); + render(); + await startDdbImport(user); + await readTinkererSheet(user); + await nextWhenReady(user, 'Next: rules'); + await nextWhenReady(user, 'Next: matches'); + const matches = await screen.findByRole('region', { name: 'Matches' }); + await user.click(await within(matches).findByRole('checkbox', { name: /Create a homebrew class Fixture Tinkerer/ })); + await waitFor(() => expect(within(matches).getByRole('checkbox', { name: /Create a homebrew class/ }).checked).toBe(true)); + await nextWhenReady(user, 'Next: numbers'); + await nextWhenReady(user, 'Next: summary'); + await screen.findByRole('region', { name: 'Homebrew class to create' }); + + await user.click(screen.getByRole('button', { name: 'Cancel' })); + + await expectStatus(/Import cancelled\. Nothing was saved\./); + expect((await client.listCharacters()).map((c) => c.id).sort()).toEqual(characters); + expect((await client.listSources()).map((s) => s.id).sort()).toEqual(sources); + // No draft check here: no client call lists drafts without a content id, and listContent shows published content only. + // DdbStubClassTests (cancel at every step) counts sources, revisions, characters and notes. +}); diff --git a/src/Ui/e2e/core.e2e.tsx b/src/Ui/e2e/core.e2e.tsx new file mode 100644 index 00000000..72c44007 --- /dev/null +++ b/src/Ui/e2e/core.e2e.tsx @@ -0,0 +1,425 @@ +// End-to-end UI flow against the real DevHost (same CommandDispatcher as the shell). Only the transport differs from the desktop +// app: HTTP to loopback instead of the WebView2 bridge, so export takes the download fallback instead of the native Save dialog. +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, expect, it, vi } from 'vitest'; +import { readZipEntry } from './zip'; +import { App } from '../src/App'; +import { client } from '../src/api/client'; +import { downloadBase64 } from '../src/files'; +import { bytesOf, createCharacter, expectStatus, goHome, openMore, openTab, startNewCharacter } from './helpers'; + +vi.mock('../src/api/client', async (importOriginal) => { + const { inject } = await import('vitest'); + const { createHttpTransport } = await import('../src/api/transport'); + const original = await importOriginal(); + const { endpoint, token } = inject('devHost'); + return { ...original, client: original.createClient(createHttpTransport(endpoint, { 'X-TomeStack-Token': token })) }; +}); + +vi.mock('../src/files', async (importOriginal) => ({ + ...(await importOriginal()), + downloadBase64: vi.fn(), +})); + +afterEach(() => { + cleanup(); + // One jsdom window serves the whole file: a preference or `html` attribute left by one test would leak into the next. + // The per-character tab memory stays (ids are unique per test and the deep-link test relies on it). + for (const key of Object.keys(localStorage)) if (key.startsWith('tomestack.') && !key.startsWith('tomestack.sheetTab.')) localStorage.removeItem(key); + for (const key of Object.keys(document.documentElement.dataset)) delete document.documentElement.dataset[key]; +}); + +it('creates a character, shows its traced sheet, overrides, exports and re-imports it', async () => { + const user = userEvent.setup(); + render(); + + // Create (the default scores: Dex 14) + await createCharacter(user, { name: 'E2E Pell', family: 'srd-5.1', scores: {}, species: /^Fixture Quickfoot/ }); + expect(await screen.findByText('Nothing to choose at this level.')).toBeTruthy(); + await user.click(screen.getByRole('button', { name: 'Create and save' })); + + // Sheet with a source-aware trace: Dex 14 + 2 (Fixture Quickfoot, species under 2014 rules) = 16 -> +3 + const sheet = await screen.findByRole('article', { name: 'E2E Pell' }); + await waitFor(() => expect(document.activeElement).toBe(within(sheet).getByRole('heading', { level: 1, name: 'E2E Pell' }))); + await openTab(user, sheet, 'Skills and saves'); + const initiative = within(sheet).getByRole('region', { name: /^Initiative:/ }); + expect(within(initiative).getByRole('heading').textContent).toContain('+3'); + expect(within(sheet).getByRole('heading', { name: /^Dexterity score: 16/ })).toBeTruthy(); + await user.click(within(initiative).getByRole('heading')); // expand the field (summary) + const trace = within(initiative).getByRole('table', { name: 'How initiative is calculated' }); + expect(within(trace).getByText(/TomeStack Fixtures: 2014 Family, p\. 1/)).toBeTruthy(); + + // Override (labeled, keeps the computed value) + await user.type(within(initiative).getByRole('spinbutton', { name: 'Number to set by hand' }), '9'); + await user.type(within(initiative).getByRole('textbox', { name: 'Reason (optional)' }), 'Table ruling'); + await user.click(within(initiative).getByRole('button', { name: 'Set by hand' })); + await waitFor(() => expect(screen.getByRole('heading', { name: /^Initiative:/ }).textContent).toContain('set by hand (calculated +3)')); + + // D22: a session note on Notes is the player's journal; the share preview below must not list it. + await openTab(user, sheet, 'Journal'); + const journal = within(sheet).getByRole('form', { name: 'New session note' }); + await user.type(within(journal).getByRole('textbox', { name: 'Note' }), 'Private session note for the share test.'); + await user.click(within(journal).getByRole('button', { name: 'Save session note' })); + await within(sheet).findByText('Private session note for the share test.'); + + // Item 17, D36: the Details form on Notes. Save is held until something changes; the details then show on Stats. + const detailsForm = within(sheet).getByRole('form', { name: 'Details' }); + const saveDetails = within(detailsForm).getByRole('button', { name: 'Save details' }); + expect(saveDetails.getAttribute('aria-disabled')).toBe('true'); + await user.type(within(detailsForm).getByRole('textbox', { name: 'Alignment' }), 'E2E neutral'); + await user.type(within(detailsForm).getByRole('textbox', { name: 'Languages' }), 'E2E tongue{Enter}E2E signs'); + expect(saveDetails.getAttribute('aria-disabled')).toBeNull(); + await user.click(saveDetails); + await expectStatus(/Details saved/); + expect(saveDetails.getAttribute('aria-disabled')).toBe('true'); // nothing differs now + expect(document.activeElement).toBe(saveDetails); // focus stays on the button + await openTab(user, sheet, 'Skills and saves'); + expect(within(within(sheet).getByRole('list', { name: 'Languages' })).getAllByRole('listitem').map((li) => li.textContent)).toEqual(['E2E tongue', 'E2E signs']); + await user.click(within(sheet).getByRole('button', { name: 'Edit in Journal → Details' })); + expect(within(sheet).getByRole('tab', { name: 'Journal' }).getAttribute('aria-selected')).toBe('true'); + await waitFor(() => expect(document.activeElement).toBe(within(sheet).getByRole('heading', { name: 'Details' }))); + + // Export (DevHost has no native dialog: package.saveAs -> unsupported -> download fallback) + await openMore(user, sheet, 'Export…'); + await user.click(screen.getByRole('button', { name: 'Export TomeStack file' })); + await waitFor(() => expect(downloadBase64).toHaveBeenCalledTimes(1)); + const [fileName, base64] = vi.mocked(downloadBase64).mock.calls[0]!; + expect(fileName).toBe('E2E-Pell-personal-backup.tomestack.zip'); // default purpose: personal backup (ADR-007) + + // Share: the preview says what is left out (nothing here: the fixture sources may be shared), then exports. + await user.click(screen.getByRole('radio', { name: /Share with someone/ })); + const leftOut = await screen.findByRole('region', { name: 'Left out of the shared TomeStack file' }); + expect(leftOut.textContent).toMatch(/Nothing is left out/); + expect(leftOut.textContent).not.toMatch(/session note/i); + // L5: the one sharing rule's list is there, and Export waits for it. + const shareCheck = await screen.findByRole('region', { name: 'Preflight: shared TomeStack file' }); + expect(shareCheck.textContent).toMatch(/Nothing is left out/); + await waitFor(() => expect(screen.getByRole('button', { name: 'Export TomeStack file' }).disabled).toBe(false)); + await user.click(screen.getByRole('button', { name: 'Export TomeStack file' })); + await waitFor(() => expect(downloadBase64).toHaveBeenCalledTimes(2)); + expect(vi.mocked(downloadBase64).mock.calls[1]![0]).toBe('E2E-Pell.tomestack.zip'); + // D36 in the files themselves: the backup holds the details and the journal; the share keeps the details and drops the journal. + const characterEntry = /^characters\/.+\.json$/; + const backupCharacter = readZipEntry(bytesOf(base64), characterEntry)!; + expect(backupCharacter).toContain('E2E tongue'); + expect(backupCharacter).toContain('Private session note for the share test.'); + const sharedCharacter = readZipEntry(bytesOf(vi.mocked(downloadBase64).mock.calls[1]![1]), characterEntry)!; + expect(sharedCharacter).toContain('E2E tongue'); + expect(sharedCharacter).not.toContain('Private session note for the share test.'); + + // Import: preview first, then apply. The character already exists, so the local copy is backed up. + const file = new File([bytesOf(base64)], fileName, { type: 'application/zip' }); + await user.upload(screen.getByLabelText('TomeStack file'), file); + const preview = await screen.findByRole('region', { name: 'Import a TomeStack file' }); + expect(within(preview).getByText(/already exists and will be replaced/)).toBeTruthy(); + await user.click(within(preview).getByRole('button', { name: 'Apply import' })); + + const status = await expectStatus(/1 replaced/); + expect(status.getAttribute('role')).toBe('status'); + expect(status.textContent).toMatch(/backed up to backups\/pre-import-/); + await openTab(user, await screen.findByRole('article', { name: 'E2E Pell' }), 'Skills and saves'); + await waitFor(() => expect(screen.getByRole('heading', { name: /^Initiative:/ }).textContent).toContain('set by hand (calculated +3)')); +}); + +it('takes a snapshot of a character, previews the restore, restores it and keeps an undo snapshot (M5 slice 8)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Snapshots', ['srd-5.2.1']); + const feat = ( + await client.publish( + await client.saveDraft({ + contentId: crypto.randomUUID(), + revisionId: '00000000-0000-0000-0000-000000000000', + kind: 'feat', + name: 'E2E Snapshot Feat', + rulesFamilies: ['srd-5.2.1'], + provenance: { sourceId: source.id }, + status: 'draft', + effects: [{ type: 'modifier', id: 'quick', operation: 'bonus', target: 'initiative', value: '3' }], + }), + ) + ).published; + const created = (await client.createCharacter({ name: 'E2E Snapshot Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [feat] })).character; + const hero = (await client.saveCharacter({ ...created, currency: { cp: 0, sp: 12, ep: 0, gp: 3, pp: 0 } })).character; // D21: coins the restore puts back + + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Snapshot Hero/ })); + await openMore(user, await screen.findByRole('article', { name: 'E2E Snapshot Hero' }), 'Snapshots'); + const panel = () => screen.getByRole('region', { name: 'Snapshots' }); + await user.type(await within(await screen.findByRole('region', { name: 'Snapshots' })).findByRole('textbox', { name: /^Snapshot name/ }), 'E2E with the feat'); + await user.click(within(panel()).getByRole('button', { name: 'Take snapshot' })); + await expectStatus(/Took a snapshot of E2E Snapshot Hero: E2E with the feat/); + + // The character changes: the feat goes, and the coins change. + await client.saveCharacter({ ...(await client.getCharacter(hero.id)).character, pins: [], currency: { cp: 0, sp: 0, ep: 0, gp: 40, pp: 0 } }); + // Leave the character on a real tab (not the Play default), so the reopen below proves the tab is remembered. + await openTab(user, await screen.findByRole('article', { name: 'E2E Snapshot Hero' }), 'Features'); + cleanup(); + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Snapshot Hero/ })); + + // ADR-014: the sheet reopens on the tab used last for this character. (The retired "manage" id falling back to Play is covered + // by sheetTab.test.ts and CharacterSheet.test.tsx.) The Snapshots panel is not kept open, so it is opened again from More. + const reopened = await screen.findByRole('article', { name: 'E2E Snapshot Hero' }); + expect(within(reopened).getByRole('tab', { name: 'Features' }).getAttribute('aria-selected')).toBe('true'); + await openMore(user, reopened, 'Snapshots'); + await user.click(await within(await screen.findByRole('region', { name: 'Snapshots' })).findByRole('button', { name: 'Restore E2E with the feat…' })); + const preview = await within(panel()).findByRole('region', { name: 'Restore E2E with the feat?' }); + await waitFor(() => expect(document.activeElement).toBe(within(preview).getByRole('heading', { name: 'Restore E2E with the feat?' }))); + expect(within(preview).getByRole('table', { name: 'Calculated values that change' }).textContent).toMatch(/Initiative\s*0\s*3/); + // D22: the restore preview names the coin change, through the service's real field names. + expect(preview.textContent).toMatch(/Coins go back to 3 gp, 12 sp \(now 40 gp\)\./); + expect((await client.getCharacter(hero.id)).character.pins).toEqual([]); // the preview changed nothing + + // "Keep the current state" closes the preview and returns focus to the button that opened it (accessibility item 23). + await user.click(within(preview).getByRole('button', { name: 'Keep the current state' })); + const reopen = within(panel()).getByRole('button', { name: 'Restore E2E with the feat…' }); + await waitFor(() => expect(document.activeElement).toBe(reopen)); + expect(within(panel()).queryByRole('region', { name: 'Restore E2E with the feat?' })).toBeNull(); + expect((await client.getCharacter(hero.id)).character.pins).toEqual([]); + + await user.click(reopen); + const again = await within(panel()).findByRole('region', { name: 'Restore E2E with the feat?' }); + await user.click(within(again).getByRole('button', { name: 'Restore' })); + await expectStatus(/Restored the snapshot/); + expect((await client.getCharacter(hero.id)).character.pins).toEqual([feat]); + expect((await client.getCharacter(hero.id)).character.currency).toEqual({ cp: 0, sp: 12, ep: 0, gp: 3, pp: 0 }); + expect(await within(panel()).findByRole('button', { name: /^Restore Before restoring/ })).toBeTruthy(); // the undo snapshot +}); + +it('reaches the primary actions by keyboard alone', async () => { + const user = userEvent.setup(); + render(); + // user-event walks a radio group with CSS.escape, which jsdom lacks; the group name needs no escaping. + const w = window as unknown as { CSS?: { escape?: (s: string) => string } }; + w.CSS ??= {}; + w.CSS.escape ??= (s: string) => s; + const addCharacter = await screen.findByRole('button', { name: '+ Add a character' }); + + await user.tab(); + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Hide sidebar' })); // the shell's first header control + // Owner (2026-10-12): no second close control inside the sidebar; the header's "Hide sidebar" is the only one. + expect(screen.queryByRole('button', { name: 'Close sidebar' })).toBeNull(); + await user.tab(); + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'TomeStack, your characters' })); // the way home + // Spec 3.1: "+ Add a character" heads the sidebar, ahead of the character list. + await user.tab(); + expect(document.activeElement).toBe(addCharacter); + await user.keyboard('{Enter}'); + expect(await screen.findByRole('heading', { level: 1, name: 'Add a character' })).toBeTruthy(); + + // The chooser's radio group is a single Tab stop. Nothing is chosen yet, so Continue does nothing until a radio is ticked. + const make = await screen.findByRole('radio', { name: 'Make a new one' }); + await waitFor(() => expect(make.disabled).toBe(false)); + for (let i = 0; i < 200 && document.activeElement !== make; i++) await user.tab(); + expect(document.activeElement).toBe(make); + await user.keyboard(' '); + expect(make.checked).toBe(true); + await user.tab(); + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Continue' })); + await user.keyboard('{Enter}'); + + expect(await screen.findByRole('heading', { name: 'New character' })).toBeTruthy(); + await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('textbox', { name: 'Name' }))); +}); + +it('opens Help from the sidebar with its h1 focused, lists a sheet gap note there, and Open lands on Features', async () => { + const user = userEvent.setup(); + const created = await client.createCharacter({ name: 'E2E Help Gaps', rulesFamily: 'srd-5.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [] }); + // A field every sheet has (the service refuses a field the sheet does not show). + await client.addGapNote(created.character.id, { kind: 'field', fieldId: 'initiative' }, 'Help screen note from the sheet.'); + render(); + await user.click(within(await screen.findByRole('navigation', { name: 'Main' })).getByRole('button', { name: 'Help' })); + const h1 = await screen.findByRole('heading', { level: 1, name: 'Help' }); + await waitFor(() => expect(document.activeElement).toBe(h1)); + const section = screen.getByRole('region', { name: 'Gap notes' }); + expect(await within(section).findByText('Help screen note from the sheet.')).toBeTruthy(); + await user.click(within(section).getAllByRole('button', { name: 'Open E2E Help Gaps' })[0]!); + const sheet = await screen.findByRole('article', { name: 'E2E Help Gaps' }); + expect(within(sheet).getByRole('tab', { name: 'Features' }).getAttribute('aria-selected')).toBe('true'); +}); + +it('the Backups screen says what a full backup holds, and needs the desktop app to write or restore one (M2.1)', async () => { + const user = userEvent.setup(); + render(); + + await user.click(await screen.findByRole('button', { name: 'Backups' })); + const panel = await screen.findByRole('region', { name: 'Backups' }); + // Earlier flows in this run created characters, homebrew drafts, a campaign and a PDF copy: the counts come from the service. + const contents = await within(panel).findByRole('list', { name: 'What the backup contains' }); + expect(contents.textContent).toMatch(/\d+ character\(s\), \d+ campaign\(s\), \d+ gap note\(s\)/); + expect(contents.textContent).toMatch(/\d+ published and [1-9]\d* draft entries/); + expect(contents.textContent).toMatch(/Not included: text read from PDFs/); + + // D77: daily copies are on by default; the setting is kept by the service (DevHost takes no copies itself). + const daily = await within(panel).findByRole('checkbox', { name: 'Keep 7 daily copies' }); + expect((daily as HTMLInputElement).checked).toBe(true); + await user.click(daily); + await waitFor(() => expect((daily as HTMLInputElement).checked).toBe(false)); + expect((await client.dailyCopies()).on).toBe(false); + await user.click(daily); // back on, for the flows after this one + await waitFor(() => expect((daily as HTMLInputElement).checked).toBe(true)); + + // DevHost has no native Save or Open dialog, so both say what they need instead of doing nothing. + await user.click(within(panel).getByRole('button', { name: 'Back up everything…' })); + expect((await screen.findByRole('alert')).textContent).toMatch(/Backing up everything needs the TomeStack desktop app/); + await user.click(within(panel).getByRole('button', { name: 'Choose a full backup…' })); + await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/Restoring a full backup needs the TomeStack desktop app/)); +}); + +it('archives a character after a preview, lists it apart, and brings it back (SPEC C-08)', async () => { + const user = userEvent.setup(); + render(); + await createCharacter(user, { name: 'E2E Archivist', family: 'srd-5.1', scores: {}, species: /^Fixture Quickfoot/ }); + await user.click(await screen.findByRole('button', { name: 'Create and save' })); + const sheet = await screen.findByRole('article', { name: 'E2E Archivist' }); + const characters = screen.getByRole('navigation', { name: 'Main' }); + await openMore(user, sheet, 'Archive'); + + // Preview first: focus moves into it, and Escape (or "Keep it") changes nothing and returns focus. + await user.click(within(sheet).getByRole('button', { name: 'Archive…' })); + let confirm = await screen.findByRole('alertdialog', { name: 'Archive E2E Archivist?' }); + expect(confirm.textContent).toMatch(/Nothing is deleted/); + await waitFor(() => expect(document.activeElement).toBe(within(confirm).getByRole('button', { name: 'Archive' }))); + await user.keyboard('{Escape}'); + expect(screen.queryByRole('alertdialog')).toBeNull(); + await waitFor(() => expect(document.activeElement).toBe(within(sheet).getByRole('button', { name: 'Archive…' }))); + await user.click(within(sheet).getByRole('button', { name: 'Archive…' })); + confirm = await screen.findByRole('alertdialog', { name: 'Archive E2E Archivist?' }); + await user.click(within(confirm).getByRole('button', { name: 'Keep it' })); + expect(screen.queryByRole('alertdialog')).toBeNull(); + expect(within(characters).getByRole('button', { name: /E2E Archivist/ })).toBeTruthy(); + + // Confirmed: the character moves to the collapsed "Archived" list, and its sheet says so. + await user.click(within(sheet).getByRole('button', { name: 'Archive…' })); + confirm = await screen.findByRole('alertdialog', { name: 'Archive E2E Archivist?' }); + await user.click(within(confirm).getByRole('button', { name: 'Archive' })); + await expectStatus(/Archived E2E Archivist/); + const archivedList = await within(characters).findByRole('list', { name: 'Archived characters' }); + expect(within(archivedList).getByRole('button', { name: /E2E Archivist/ })).toBeTruthy(); + expect(archivedList.closest('details')!.open).toBe(false); + await waitFor(() => expect(within(screen.getByRole('article', { name: 'E2E Archivist' })).getByRole('heading', { name: 'Archived' })).toBeTruthy()); + // The pressed button is gone; focus lands on the control that replaced it, not on . + await waitFor(() => expect(document.activeElement).toBe(within(screen.getByRole('article', { name: 'E2E Archivist' })).getByRole('button', { name: 'Unarchive' }))); + + // Unarchive: back in the main list. + await user.click(within(screen.getByRole('article', { name: 'E2E Archivist' })).getByRole('button', { name: 'Unarchive' })); + await expectStatus(/back in the character list/); + await waitFor(() => expect(within(characters).queryByRole('list', { name: 'Archived characters' })).toBeNull()); + expect(within(characters).getByRole('button', { name: /E2E Archivist/ })).toBeTruthy(); + await waitFor(() => expect(document.activeElement).toBe(within(screen.getByRole('article', { name: 'E2E Archivist' })).getByRole('button', { name: 'Archive…' }))); +}); + +it('keeps the theme picked in Settings when the app is rendered again (ADR-015)', async () => { + const user = userEvent.setup(); + const { unmount } = render(); + await user.click(await screen.findByRole('button', { name: 'Settings' })); + await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('heading', { level: 1, name: 'Settings' }))); + await user.click(screen.getByRole('radio', { name: 'Violet' })); + expect(document.documentElement.dataset.theme).toBe('violet'); + await user.click(screen.getByRole('radio', { name: 'Dark' })); + expect(document.documentElement.dataset.appearance).toBe('dark'); + await user.selectOptions(screen.getByRole('combobox', { name: 'Text size' }), '125'); + expect(document.documentElement.dataset.textSize).toBe('125'); + unmount(); + // so the final check proves the mount effect re-applied the saved preferences + delete document.documentElement.dataset.theme; + delete document.documentElement.dataset.appearance; + delete document.documentElement.dataset.textSize; + render(); + await screen.findByRole('button', { name: 'Settings' }); + expect(document.documentElement.dataset.theme).toBe('violet'); + expect(document.documentElement.dataset.appearance).toBe('dark'); + expect(document.documentElement.dataset.textSize).toBe('125'); +}); + +it('keeps the Custom accent and its hue when the app is rendered again, and a preset replaces it (D40)', async () => { + const user = userEvent.setup(); + const { unmount } = render(); + await user.click(await screen.findByRole('button', { name: 'Settings' })); + await user.click(screen.getByRole('radio', { name: 'Custom accent' })); + const slider = screen.getByRole('slider', { name: 'Accent hue' }); + fireEvent.change(slider, { target: { value: '120' } }); + expect(slider.getAttribute('aria-valuetext')).toBe('Lime, 120 degrees'); + expect(document.documentElement.dataset.theme).toBe('custom'); + unmount(); + delete document.documentElement.dataset.theme; + render(); + await screen.findByRole('button', { name: 'Settings' }); + expect(document.documentElement.dataset.theme).toBe('custom'); + await user.click(screen.getByRole('button', { name: 'Settings' })); + expect(screen.getByRole('slider', { name: 'Accent hue' }).value).toBe('120'); + await user.click(screen.getByRole('radio', { name: 'Tide' })); + expect(screen.queryByRole('slider')).toBeNull(); + expect(document.documentElement.dataset.theme).toBe('tide'); +}); + +it('hides and shows the sidebar from the header and by Ctrl+B, moves focus out of a hidden sidebar, and remembers the state (ADR-015)', async () => { + const user = userEvent.setup(); + const { unmount } = render(); + const toggle = await screen.findByRole('button', { name: 'Hide sidebar' }); + expect(toggle.getAttribute('aria-expanded')).toBe('true'); + expect(screen.getByRole('navigation', { name: 'Main' })).toBeTruthy(); + + await user.click(toggle); + expect(screen.getByRole('button', { name: 'Show sidebar' }).getAttribute('aria-expanded')).toBe('false'); + expect(screen.queryByRole('navigation', { name: 'Main' })).toBeNull(); + + await user.keyboard('{Control>}b{/Control}'); + expect(screen.getByRole('navigation', { name: 'Main' })).toBeTruthy(); + + // Another keyboard layout: Ctrl + the physical B key reports a different character, so the shortcut follows `code`. + fireEvent.keyDown(document, { key: 'и', code: 'KeyB', ctrlKey: true }); + expect(screen.queryByRole('navigation', { name: 'Main' })).toBeNull(); + fireEvent.keyDown(document, { key: 'и', code: 'KeyB', ctrlKey: true }); + expect(screen.getByRole('navigation', { name: 'Main' })).toBeTruthy(); + + // Owner (2026-10-12): the header toggle is the only close control; the sidebar has none of its own. + expect(screen.queryByRole('button', { name: 'Close sidebar' })).toBeNull(); + expect(within(screen.getByRole('navigation', { name: 'Main' })).getByRole('list', { name: 'Characters' })).toBeTruthy(); + + // Focus inside the sidebar, then hide it by the shortcut: focus must land on the toggle, not on . + screen.getByRole('button', { name: '+ Add a character' }).focus(); + await user.keyboard('{Control>}b{/Control}'); + await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Show sidebar' }))); + + unmount(); + render(); + expect(await screen.findByRole('button', { name: 'Show sidebar' })).toBeTruthy(); + expect(screen.queryByRole('navigation', { name: 'Main' })).toBeNull(); + await user.click(screen.getByRole('button', { name: 'Show sidebar' })); + expect(localStorage.getItem('tomestack.sidebar')).toBeNull(); + + // A focused checkbox or radio must not block the shortcut (WCAG 2.1.1); a text field keeps Ctrl+B. + await user.click(screen.getByRole('button', { name: 'Settings' })); + for (const control of [screen.getByRole('checkbox', { name: 'Animate dice' }), screen.getByRole('radio', { name: 'Violet' })]) { + control.focus(); + await user.keyboard('{Control>}b{/Control}'); + expect(screen.queryByRole('navigation', { name: 'Main' })).toBeNull(); + await user.keyboard('{Control>}b{/Control}'); + expect(screen.getByRole('navigation', { name: 'Main' })).toBeTruthy(); + } + await startNewCharacter(user); + const name = await screen.findByRole('textbox', { name: /^Name/ }); + name.focus(); + await user.keyboard('{Control>}b{/Control}'); + expect(screen.getByRole('navigation', { name: 'Main' })).toBeTruthy(); // ignored in a text field +}); + +it('opens the Characters home screen with a card per character and opens one from it (D25)', async () => { + const user = userEvent.setup(); + render(); + const home = await screen.findByRole('region', { name: 'Your characters' }); // the start screen + expect(within(home).getByRole('heading', { level: 1, name: 'Your characters' })).toBeTruthy(); + const cards = await within(home).findAllByRole('listitem'); // earlier tests created characters + expect(cards.length).toBeGreaterThan(0); + expect(within(home).getByRole('list', { name: 'Characters' })).toBeTruthy(); + const first = cards[0]!; + const name = within(first).getByRole('button', { name: /^Open / }).textContent!.replace(/^Open /, ''); + expect(first.textContent).toMatch(/Level \d+/); + await user.click(within(first).getByRole('button', { name: `Open ${name}` })); + expect(await screen.findByRole('article', { name })).toBeTruthy(); + await goHome(user); + const back = await screen.findByRole('region', { name: 'Your characters' }); + await waitFor(() => expect(document.activeElement).toBe(within(back).getByRole('heading', { level: 1, name: 'Your characters' }))); +}); diff --git a/src/Ui/e2e/flow.e2e.tsx b/src/Ui/e2e/flow.e2e.tsx deleted file mode 100644 index 918b990d..00000000 --- a/src/Ui/e2e/flow.e2e.tsx +++ /dev/null @@ -1,3887 +0,0 @@ -// End-to-end UI flow against the real DevHost (same CommandDispatcher as the shell): create -> sheet -> override -// -> export -> import. Only the transport differs from the desktop app: HTTP to loopback instead of the WebView2 -// bridge, so export takes the download fallback instead of the native Save dialog. -import { readdirSync, readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { afterEach, expect, inject, it, vi } from 'vitest'; -import { readZipEntry, zip } from './zip'; -import { App } from '../src/App'; -import { client } from '../src/api/client'; -import { TomeStackError } from '../src/api/transport'; -import { downloadBase64 } from '../src/files'; -import { fromTemplate, templates } from '../src/templates'; - -vi.mock('../src/api/client', async (importOriginal) => { - const { inject } = await import('vitest'); - const { createHttpTransport } = await import('../src/api/transport'); - const original = await importOriginal(); - const { endpoint, token } = inject('devHost'); - return { ...original, client: original.createClient(createHttpTransport(endpoint, { 'X-TomeStack-Token': token })) }; -}); - -vi.mock('../src/files', async (importOriginal) => ({ - ...(await importOriginal()), - downloadBase64: vi.fn(), -})); - -afterEach(() => { - cleanup(); - // One jsdom window serves the whole file: a preference or `html` attribute left by one test would leak into the next. - // The per-character tab memory stays (ids are unique per test and the deep-link test relies on it). - for (const key of Object.keys(localStorage)) if (key.startsWith('tomestack.') && !key.startsWith('tomestack.sheetTab.')) localStorage.removeItem(key); - for (const key of Object.keys(document.documentElement.dataset)) delete document.documentElement.dataset[key]; -}); - -/** - * A row of the review panel's Entries found list. After a filter or kind change the panel says "No entries match." until the - * new `import.candidates` reply arrives, so the list itself may not exist yet: the whole lookup is retried, never read once. - */ -const candidateButton = (panel: () => HTMLElement, name: string) => - waitFor(() => within(within(panel()).getByRole('list', { name: 'Entries found' })).getByRole('button', { name }), { timeout: 10000 }); - -/** - * Group 2 navigation: a new character goes "+ Add a character" (sidebar) > "Make a new one" > Continue. The sidebar button is - * enabled before app.info loads; the chooser disables "Make a new one" until it has, so the radio is waited on. - */ -async function startNewCharacter(user: ReturnType): Promise { - await user.click(await screen.findByRole('button', { name: '+ Add a character' })); - const make = await screen.findByRole('radio', { name: 'Make a new one' }); - await waitFor(() => expect(make.disabled).toBe(false)); - await user.click(make); - await user.click(screen.getByRole('button', { name: 'Continue' })); -} - -/** Add-ons live in Settings now (no sidebar entry): opens Settings and waits for the lazy Add-ons section. */ -async function openAddOns(user: ReturnType): Promise { - await user.click(await screen.findByRole('button', { name: 'Settings' })); - await screen.findByRole('heading', { name: 'Add-ons' }); -} - -/** The brand button in the window title area always goes home (the sidebar's "All characters" shows only with 2+ characters). */ -async function goHome(user: ReturnType): Promise { - await user.click(await screen.findByRole('button', { name: 'TomeStack, your characters' })); -} - -function bytesOf(base64: string): Uint8Array { - return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); -} - -/** - * Waits until the status line says `text`. The status line stays on screen, so `findByRole('status')` would return at - * once with the previous message (lint forbids it here). - */ -async function expectStatus(text: RegExp): Promise { - await waitFor(() => expect(appStatus().textContent).toMatch(text)); - return appStatus(); -} - -/** - * The app's status line. On a sheet the "Last roll" is a second `role="status"` node (D96), so a plain - * `getByRole('status')` finds two; this excludes it by name and expects exactly one line left. - */ -function appStatus(): HTMLElement { - const lines = screen.getAllByRole('status').filter((el) => el.getAttribute('aria-label') !== 'Last roll'); - if (lines.length !== 1) throw new Error(`Expected one status line, found ${lines.length}.`); - return lines[0]!; -} - -/** - * Activates one tab of a character sheet (ADR-014). Inactive panels are hidden, so a query finds only the active - * tab's sections; a test must open the tab a user would open. A no-op when the tab is already selected. - */ -async function openTab(user: ReturnType, sheet: HTMLElement, name: string): Promise { - const tab = within(sheet).getByRole('tab', { name }); - if (tab.getAttribute('aria-selected') !== 'true') await user.click(tab); -} - -/** Opens the sheet's More disclosure and chooses one item (Choices, Print…, Export…, Snapshots, Updates, Archive). */ -async function openMore(user: ReturnType, sheet: HTMLElement, item: string): Promise { - await user.click(within(sheet).getByRole('button', { name: 'More' })); - await user.click(within(sheet).getByRole('button', { name: item })); -} - -/** Opens the "Opening this in an older TomeStack?" disclosure inside `scope`, then picks the radio for `release` (e.g. "0.7.0"). */ -async function chooseOlderTarget(user: ReturnType, scope: HTMLElement, release: string): Promise { - const summary = within(scope).getByText(/^Opening this in an older TomeStack\?/); - if (!summary.closest('details')!.open) await user.click(summary); - await user.click(within(scope).getByRole('radio', { name: release })); -} - -/** One value of the sheet's status bar: the `.status-value` beside the `.status-label` named `term` (button or plain item). */ -function summaryValue(sheet: HTMLElement, term: string): string { - const summary = within(sheet).getByRole('region', { name: 'Status' }); - const label = Array.from(summary.querySelectorAll('.status-label')).find((l) => l.textContent?.trim() === term); - if (!label) throw new Error(`No status bar item named ${term}`); - return label.parentElement!.querySelector('.status-value')!.textContent!.trim(); -} - -it('creates a character, shows its traced sheet, overrides, exports and re-imports it', async () => { - const user = userEvent.setup(); - render(); - - // Create (the default scores: Dex 14) - await createCharacter(user, { name: 'E2E Pell', family: 'srd-5.1', scores: {}, species: /^Fixture Quickfoot/ }); - expect(await screen.findByText('Nothing to choose at this level.')).toBeTruthy(); - await user.click(screen.getByRole('button', { name: 'Create and save' })); - - // Sheet with a source-aware trace: Dex 14 + 2 (Fixture Quickfoot, species under 2014 rules) = 16 -> +3 - const sheet = await screen.findByRole('article', { name: 'E2E Pell' }); - await waitFor(() => expect(document.activeElement).toBe(within(sheet).getByRole('heading', { level: 1, name: 'E2E Pell' }))); - await openTab(user, sheet, 'Skills and saves'); - const initiative = within(sheet).getByRole('region', { name: /^Initiative:/ }); - expect(within(initiative).getByRole('heading').textContent).toContain('+3'); - expect(within(sheet).getByRole('heading', { name: /^Dexterity score: 16/ })).toBeTruthy(); - await user.click(within(initiative).getByRole('heading')); // expand the field (summary) - const trace = within(initiative).getByRole('table', { name: 'How initiative is calculated' }); - expect(within(trace).getByText(/TomeStack Fixtures: 2014 Family, p\. 1/)).toBeTruthy(); - - // Override (labeled, keeps the computed value) - await user.type(within(initiative).getByRole('spinbutton', { name: 'Number to set by hand' }), '9'); - await user.type(within(initiative).getByRole('textbox', { name: 'Reason (optional)' }), 'Table ruling'); - await user.click(within(initiative).getByRole('button', { name: 'Set by hand' })); - await waitFor(() => expect(screen.getByRole('heading', { name: /^Initiative:/ }).textContent).toContain('set by hand (calculated +3)')); - - // D22: a session note on Notes is the player's journal; the share preview below must not list it. - await openTab(user, sheet, 'Journal'); - const journal = within(sheet).getByRole('form', { name: 'New session note' }); - await user.type(within(journal).getByRole('textbox', { name: 'Note' }), 'Private session note for the share test.'); - await user.click(within(journal).getByRole('button', { name: 'Save session note' })); - await within(sheet).findByText('Private session note for the share test.'); - - // Item 17, D36: the Details form on Notes. Save is held until something changes; the details then show on Stats. - const detailsForm = within(sheet).getByRole('form', { name: 'Details' }); - const saveDetails = within(detailsForm).getByRole('button', { name: 'Save details' }); - expect(saveDetails.getAttribute('aria-disabled')).toBe('true'); - await user.type(within(detailsForm).getByRole('textbox', { name: 'Alignment' }), 'E2E neutral'); - await user.type(within(detailsForm).getByRole('textbox', { name: 'Languages' }), 'E2E tongue{Enter}E2E signs'); - expect(saveDetails.getAttribute('aria-disabled')).toBeNull(); - await user.click(saveDetails); - await expectStatus(/Details saved/); - expect(saveDetails.getAttribute('aria-disabled')).toBe('true'); // nothing differs now - expect(document.activeElement).toBe(saveDetails); // focus stays on the button - await openTab(user, sheet, 'Skills and saves'); - expect(within(within(sheet).getByRole('list', { name: 'Languages' })).getAllByRole('listitem').map((li) => li.textContent)).toEqual(['E2E tongue', 'E2E signs']); - await user.click(within(sheet).getByRole('button', { name: 'Edit in Journal → Details' })); - expect(within(sheet).getByRole('tab', { name: 'Journal' }).getAttribute('aria-selected')).toBe('true'); - await waitFor(() => expect(document.activeElement).toBe(within(sheet).getByRole('heading', { name: 'Details' }))); - - // Export (DevHost has no native dialog: package.saveAs -> unsupported -> download fallback) - await openMore(user, sheet, 'Export…'); - await user.click(screen.getByRole('button', { name: 'Export TomeStack file' })); - await waitFor(() => expect(downloadBase64).toHaveBeenCalledTimes(1)); - const [fileName, base64] = vi.mocked(downloadBase64).mock.calls[0]!; - expect(fileName).toBe('E2E-Pell-personal-backup.tomestack.zip'); // default purpose: personal backup (ADR-007) - - // Share: the preview says what is left out (nothing here: the fixture sources may be shared), then exports. - await user.click(screen.getByRole('radio', { name: /Share with someone/ })); - const leftOut = await screen.findByRole('region', { name: 'Left out of the shared TomeStack file' }); - expect(leftOut.textContent).toMatch(/Nothing is left out/); - expect(leftOut.textContent).not.toMatch(/session note/i); - // L5: the one sharing rule's list is there, and Export waits for it. - const shareCheck = await screen.findByRole('region', { name: 'Preflight: shared TomeStack file' }); - expect(shareCheck.textContent).toMatch(/Nothing is left out/); - await waitFor(() => expect(screen.getByRole('button', { name: 'Export TomeStack file' }).disabled).toBe(false)); - await user.click(screen.getByRole('button', { name: 'Export TomeStack file' })); - await waitFor(() => expect(downloadBase64).toHaveBeenCalledTimes(2)); - expect(vi.mocked(downloadBase64).mock.calls[1]![0]).toBe('E2E-Pell.tomestack.zip'); - // D36 in the files themselves: the backup holds the details and the journal; the share keeps the details and drops the journal. - const characterEntry = /^characters\/.+\.json$/; - const backupCharacter = readZipEntry(bytesOf(base64), characterEntry)!; - expect(backupCharacter).toContain('E2E tongue'); - expect(backupCharacter).toContain('Private session note for the share test.'); - const sharedCharacter = readZipEntry(bytesOf(vi.mocked(downloadBase64).mock.calls[1]![1]), characterEntry)!; - expect(sharedCharacter).toContain('E2E tongue'); - expect(sharedCharacter).not.toContain('Private session note for the share test.'); - - // Import: preview first, then apply. The character already exists, so the local copy is backed up. - const file = new File([bytesOf(base64)], fileName, { type: 'application/zip' }); - await user.upload(screen.getByLabelText('TomeStack file'), file); - const preview = await screen.findByRole('region', { name: 'Import a TomeStack file' }); - expect(within(preview).getByText(/already exists and will be replaced/)).toBeTruthy(); - await user.click(within(preview).getByRole('button', { name: 'Apply import' })); - - const status = await expectStatus(/1 replaced/); - expect(status.getAttribute('role')).toBe('status'); - expect(status.textContent).toMatch(/backed up to backups\/pre-import-/); - await openTab(user, await screen.findByRole('article', { name: 'E2E Pell' }), 'Skills and saves'); - await waitFor(() => expect(screen.getByRole('heading', { name: /^Initiative:/ }).textContent).toContain('set by hand (calculated +3)')); -}); - -/** Ticks one option of the choice whose legend starts with `legend`. */ -async function pick(user: ReturnType, legend: RegExp, option: RegExp) { - const group = await screen.findByRole('group', { name: legend }); - await user.click(await within(group).findByRole('checkbox', { name: option })); // options load after the choices -} - -/** D32: walks the seven create steps (rules, class, scores, species, background, gear, choices). `scores` uses "Enter by hand" ({} keeps the default scores); otherwise the standard array is assigned in order. */ -async function createCharacter( - user: ReturnType, - opts: { - name: string; - family?: 'srd-5.1' | 'srd-5.2.1'; - scores?: Partial>; - species?: RegExp; - cls?: RegExp; - background?: RegExp; - /** A checkbox under "Other content" on the Background step. */ - other?: RegExp; - /** Keep the starting kits on the Gear step instead of skipping it; `beforeChoices` runs there first. */ - kit?: boolean; - beforeChoices?: () => Promise; - }, -) { - await startNewCharacter(user); - await user.type(await screen.findByRole('textbox', { name: 'Name' }), opts.name); - if (opts.family) await user.click(screen.getByRole('radio', { name: opts.family === 'srd-5.2.1' ? /2024 rules/ : /2014 rules/ })); - await user.click(screen.getByRole('button', { name: 'Next: class' })); - // The class options only appear once the listing for the chosen rules family has arrived, so this pick is never dropped. - if (opts.cls) await user.click(await screen.findByRole('radio', { name: opts.cls })); - await user.click(screen.getByRole('button', { name: 'Next: ability scores' })); - if (opts.scores) { - await user.click(screen.getByRole('radio', { name: 'Enter by hand' })); - const group = screen.getByRole('group', { name: 'Base ability scores' }); - for (const [label, value] of Object.entries(opts.scores)) { - const input = within(group).getByRole('spinbutton', { name: label }); - await user.clear(input); - await user.type(input, String(value)); - } - } else { - const group = screen.getByRole('group', { name: 'Assign the standard array' }); - for (const [label, value] of [['Strength', '15'], ['Dexterity', '14'], ['Constitution', '13'], ['Intelligence', '12'], ['Wisdom', '10'], ['Charisma', '8']] as const) - await user.selectOptions(within(group).getByRole('combobox', { name: label }), value); - } - await user.click(screen.getByRole('button', { name: 'Next: species' })); - if (opts.species) await user.click(await screen.findByRole('radio', { name: opts.species })); - await user.click(screen.getByRole('button', { name: 'Next: background' })); - if (opts.background) await user.click(await screen.findByRole('radio', { name: opts.background })); - if (opts.other) { - await user.click(screen.getByText(/^Other content \(/)); // the summary, not the legend inside it - await user.click(await screen.findByRole('checkbox', { name: opts.other })); - } - await user.click(screen.getByRole('button', { name: 'Next: gear' })); - // Gear: most walks skip it so inventories stay as the test expects; `kit` keeps the guides' defaults (option a) and `beforeChoices` runs on the step. - if (opts.kit) await opts.beforeChoices?.(); - else await user.click(screen.getByRole('button', { name: /^Skip: I'll add gear myself/ })); - await user.click(screen.getByRole('button', { name: 'Next: choices' })); -} - -// The longest flow in the suite (create, two level-ups, play, rests): ~58 s alone locally (2026-10-29), so the 60 s -// default timed it out on a loaded machine; it gets 180 s, three times the suite's per-test budget. -it('builds an SRD 5.2.1 Barbarian as drafts: create, cancel a level-up, level to 3 with a subclass', async () => { - const user = userEvent.setup(); - render(); - // The M1 acceptance character Brenna (Str 15, Dex 13, Con 14, Int 8, Wis 12, Cha 10); D31: only the character's family is listed. - await createCharacter(user, { - name: 'E2E Brenna', - family: 'srd-5.2.1', - scores: { Strength: 15, Dexterity: 13, Constitution: 14, Intelligence: 8, Wisdom: 12, Charisma: 10 }, - species: /^Dwarf/, - cls: /^Barbarian/, - background: /^Soldier/, - }); - - // Level-1 choices are offered and flagged until answered; the subclass (level 3) is not offered yet. - await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('heading', { name: 'New character' }))); - expect(await screen.findByText(/2 choices still to make/)).toBeTruthy(); - expect(screen.queryByRole('group', { name: /^Barbarian: choose 1/ })).toBeNull(); - await pick(user, /^Soldier: choose 1/, /^Soldier Ability Scores: Strength \+2, Constitution \+1/); - await pick(user, /^Barbarian: choose 2/, /^Barbarian Skill: Perception/); - await pick(user, /^Barbarian: choose 2/, /^Barbarian Skill: Survival/); - expect(await screen.findByText('All choices are made.')).toBeTruthy(); - await user.click(screen.getByRole('button', { name: 'Create and save' })); - - let sheet = await screen.findByRole('article', { name: 'E2E Brenna' }); - await openTab(user, sheet, 'Skills and saves'); - expect(within(sheet).getByRole('heading', { name: /^Strength score: 17/ })).toBeTruthy(); - expect(within(sheet).queryByRole('heading', { name: 'Choices to make' })).toBeNull(); - - // A cancelled level-up draft changes nothing. - await user.click(within(sheet).getByRole('button', { name: 'Level up' })); - await user.click(await screen.findByRole('radio', { name: /^Barbarian 2\b/ })); - await user.click(screen.getByRole('button', { name: 'Next: choices' })); - expect(await screen.findByText('All choices are made.')).toBeTruthy(); // level 2 offers no new choice - await user.click(screen.getByRole('button', { name: 'Cancel' })); - await user.click(await screen.findByRole('button', { name: 'Discard' })); // a level-up pick was made: Cancel asks first - await expectStatus(/Draft discarded/); - sheet = await screen.findByRole('article', { name: 'E2E Brenna' }); - expect(within(sheet).getByText('Level 1')).toBeTruthy(); - - // Level 2, then 3: the subclass and Primal Knowledge choices appear at level 3. - for (const next of [2, 3]) { - await user.click(within(await screen.findByRole('article', { name: 'E2E Brenna' })).getByRole('button', { name: 'Level up' })); - await user.click(await screen.findByRole('radio', { name: new RegExp(`^Barbarian ${next}\\b`) })); - await user.click(screen.getByRole('button', { name: 'Next: choices' })); - if (next === 3) { - await pick(user, /^Barbarian: choose 1/, /^Path of the Berserker/); - // Leave Primal Knowledge open: the save is allowed and the sheet flags it. - expect(await screen.findByText(/1 choice still to make/)).toBeTruthy(); - } - await user.click(await screen.findByRole('button', { name: 'Save level-up' })); - } - - sheet = await screen.findByRole('article', { name: 'E2E Brenna' }); - expect(within(sheet).getByText('Level 3')).toBeTruthy(); - - // D74: Save level-up opens the sheet on Features with "What changed at level 3" focused (the level-2 list was overwritten). - const changed = within(sheet).getByRole('region', { name: 'What changed at level 3' }); - await waitFor(() => expect(document.activeElement).toBe(within(changed).getByRole('heading', { name: 'What changed at level 3' }))); - expect(within(changed).getByText(/^Hit point maximum:/)).toBeTruthy(); - expect(within(changed).getByText(/^New choice: Primal Knowledge/)).toBeTruthy(); - await user.click(within(changed).getByRole('button', { name: 'Dismiss' })); - expect(within(sheet).queryByRole('region', { name: /^What changed at level/ })).toBeNull(); - // Gone for good: leaving the sheet and opening the character again shows no panel. - await goHome(user); - await user.click(within(await screen.findByRole('navigation', { name: 'Main' })).getByRole('button', { name: /E2E Brenna/ })); - sheet = await screen.findByRole('article', { name: 'E2E Brenna' }); - expect(within(sheet).queryByRole('region', { name: /^What changed at level/ })).toBeNull(); - - const open = within(sheet).getByRole('heading', { name: 'Choices to make' }).parentElement!; - expect(open.textContent).toMatch(/Primal Knowledge: choose 1 \(0 chosen\)/); - - // Answer it from the sheet: Survival is already chosen elsewhere, so pick Animal Handling. - await user.click(within(open).getByRole('button', { name: 'Choose now' })); - await pick(user, /^Primal Knowledge: choose 1/, /^Barbarian Skill: Animal Handling/); - expect(await screen.findByRole('checkbox', { name: /^Barbarian Skill: Animal Handling/, checked: true })).toBeTruthy(); - await user.click(await screen.findByRole('button', { name: 'Save choices' })); - - // The M1 acceptance values for Brenna (m1-acceptance.md): AC 13, HP 35, Animal Handling +3. - // The builder waits for the tick's preview before saving, and the saved view opens the sheet; wait for the re-render all the same. - sheet = await screen.findByRole('article', { name: 'E2E Brenna' }); - await openTab(user, sheet, 'Skills and saves'); - expect(await within(sheet).findByRole('heading', { name: /^Armor Class: 13/ })).toBeTruthy(); - expect(await within(sheet).findByRole('heading', { name: /^Hit point maximum: 35/ })).toBeTruthy(); - expect(await within(sheet).findByRole('heading', { name: /^Animal Handling: \+3/ })).toBeTruthy(); - await waitFor(() => expect(within(sheet).queryByRole('heading', { name: 'Choices to make' })).toBeNull()); - - // M2 item 2, play: resources with calculated maximums, explicit spending, hit points, conditions and rolls. - await openTab(user, sheet, 'Play'); - const resources = within(sheet).getByRole('region', { name: 'Resources' }); - expect(within(resources).getByRole('heading', { name: 'Rages: 3 of 3' })).toBeTruthy(); - expect(within(resources).getByRole('heading', { name: 'Stonecunning: 2 of 2' })).toBeTruthy(); - await user.click(within(resources).getByRole('button', { name: 'Spend 1 Rages' })); - await waitFor(() => expect(within(screen.getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Rages: 2 of 3' })).toBeTruthy()); - - const hp = screen.getByRole('region', { name: /^Hit points:/ }); - await user.type(within(hp).getByRole('spinbutton', { name: 'Amount' }), '5'); - await user.click(within(hp).getByRole('button', { name: 'Set temporary hit points' })); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 35 of 35, 5 temporary' })).toBeTruthy()); - await user.type(within(screen.getByRole('region', { name: /^Hit points:/ })).getByRole('spinbutton', { name: 'Amount' }), '12'); - await user.click(within(screen.getByRole('region', { name: /^Hit points:/ })).getByRole('button', { name: 'Take damage' })); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 28 of 35' })).toBeTruthy()); - - // D23: Undo puts the hit points and the temporary hit points back, then the damage is taken again. - await user.click(await screen.findByRole('button', { name: 'Undo last change: damage 12' })); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 35 of 35, 5 temporary' })).toBeTruthy()); - await waitFor(() => expect(screen.getByRole('button', { name: 'Undo last change' }).disabled).toBe(true)); - const amount = () => within(screen.getByRole('region', { name: /^Hit points:/ })).getByRole('spinbutton', { name: 'Amount' }); - await user.clear(amount()); - await user.type(amount(), '12'); - await user.click(within(screen.getByRole('region', { name: /^Hit points:/ })).getByRole('button', { name: 'Take damage' })); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 28 of 35' })).toBeTruthy()); - - await user.selectOptions(screen.getByRole('combobox', { name: 'Add condition' }), 'Poisoned'); - await waitFor(() => expect(screen.getByRole('button', { name: 'Remove Poisoned' })).toBeTruthy()); - - // A feature roll shows its record, and rolling spends nothing. - await user.click(screen.getByRole('checkbox', { name: /Critical hit/ })); - await user.click(screen.getByRole('button', { name: 'Roll Frenzy extra damage (Rage Damage +2: 2d6) (2d6)' })); - const lastRoll = screen.getByRole('status', { name: 'Last roll' }); - expect(within(screen.getByRole('region', { name: 'Status' })).getByRole('status', { name: 'Last roll' })).toBe(lastRoll); - await waitFor(() => expect(lastRoll.textContent).toMatch(/Frenzy extra damage.*: \d+ \(2d6, critical\)/)); - expect(lastRoll.textContent).toMatch(/d6 \d \(critical\)/); // doubled dice are marked - expect(lastRoll.textContent).toMatch(/Frenzy \(System Reference Document 5\.2\.1, p\. \d+\)/); - - // A d20 test with advantage keeps one die and drops the other. - await user.click(screen.getByRole('radio', { name: 'Advantage' })); - await openTab(user, sheet, 'Skills and saves'); - const strSave = screen.getByRole('region', { name: /^Strength saving throw:/ }); - await user.click(within(strSave).getByRole('heading')); - await user.click(within(strSave).getByRole('button', { name: 'Roll Strength saving throw' })); - await waitFor(() => expect(lastRoll.textContent).toMatch(/Strength saving throw \(d20 test\): \d+ \(1d20, advantage\)/)); - expect(lastRoll.textContent).toMatch(/\(dropped\)/); - expect(lastRoll.textContent).toMatch(/Strength saving throw \+5/); - // D72: "Why?" sits beside the Last roll (not inside it) and explains the +5 in words, naming the proficiency bonus. - const why = within(screen.getByRole('region', { name: 'Status' })).getByText('Why?').closest('details')!; - expect(why.open).toBe(false); - expect(lastRoll.contains(why)).toBe(false); - await user.click(within(why).getByText('Why?')); - expect(why.open).toBe(true); - expect(within(why).getByRole('list', { name: 'Why this roll came out this way' }).textContent).toMatch(/proficiency bonus/i); - // D28: the roll before it is in Earlier rolls, outside the live region. - await user.click(within(sheet).getByText('Earlier rolls (1)')); - expect(within(sheet).getByText('Earlier rolls (1)').closest('details')!.textContent).toMatch(/Frenzy extra damage.*: \d+ \(2d6, critical\)/); - expect(lastRoll.textContent).not.toMatch(/Earlier rolls/); - await openTab(user, sheet, 'Play'); - expect(within(screen.getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Rages: 2 of 3' })).toBeTruthy(); - - // Features list their automation status. - await openTab(user, sheet, 'Features'); - const features = screen.getByRole('region', { name: 'Features' }); - // C2-1: the new Barbarian's Danger Sense is a worked-out Dexterity-save advantage (it was reference text before). - expect(within(features).getByText('Danger Sense').closest('li')!.textContent).toMatch(/Worked out for you/); - - // M2 item 3, long rest (D01): preview first, cancel changes nothing, then confirm. - await openTab(user, sheet, 'Play'); - await user.click(screen.getByRole('button', { name: 'Long rest…' })); - let rest = await screen.findByRole('region', { name: 'Long rest' }); - await waitFor(() => expect(document.activeElement).toBe(within(rest).getByRole('heading', { name: 'Long rest' }))); - // The heading is focused on mount; the preview's changes arrive afterwards (restPreview), so wait for them. - expect(await within(rest).findByRole('checkbox', { name: /^Hit points: 28 → 35/ })).toBeTruthy(); - expect(await within(rest).findByRole('checkbox', { name: /^Rages: 2 → 3/ })).toBeTruthy(); - await user.click(within(rest).getByRole('button', { name: 'Cancel rest' })); - expect(screen.getByRole('heading', { name: 'Hit points: 28 of 35' })).toBeTruthy(); - - await user.click(screen.getByRole('button', { name: 'Long rest…' })); - rest = await screen.findByRole('region', { name: 'Long rest' }); - await user.click(await within(rest).findByRole('checkbox', { name: /^Rages: 2 → 3/ })); // untick: keep Rages as they are - await user.click(within(rest).getByRole('button', { name: 'Finish long rest' })); - await expectStatus(/Long rest finished: 1 change applied/); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 35 of 35' })).toBeTruthy()); - expect(within(screen.getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Rages: 2 of 3' })).toBeTruthy(); - - // Short rest (D01 follow-up): spend a hit die rolled at the table (5 + Con 2 = 7), and Rage regains one use (2024). - const hpPanel = () => screen.getByRole('region', { name: /^Hit points:/ }); - await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '10'); - await user.click(within(hpPanel()).getByRole('button', { name: 'Take damage' })); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 25 of 35' })).toBeTruthy()); - expect(hpPanel().textContent).toMatch(/Hit dice: 3 of 3 \(d12\)/); - await user.click(screen.getByRole('button', { name: 'Short rest…' })); - rest = await screen.findByRole('region', { name: 'Short rest' }); - await waitFor(() => expect(document.activeElement).toBe(within(rest).getByRole('heading', { name: 'Short rest' }))); - expect(await within(rest).findByRole('checkbox', { name: /^Rages: 2 → 3/ })).toBeTruthy(); - await user.type(within(rest).getByRole('spinbutton', { name: 'd12 rolled at the table' }), '5'); - await user.click(within(rest).getByRole('button', { name: 'Add d12' })); - const spend = await within(rest).findByRole('list', { name: 'Hit dice to spend' }); - expect(spend.textContent).toMatch(/Rolled 5, Constitution modifier \+2: 7 hit point\(s\)\. Hit points 25 → 32/); - await user.click(within(rest).getByRole('button', { name: 'Finish short rest' })); - await expectStatus(/Short rest finished: 2 changes applied/); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 32 of 35' })).toBeTruthy()); - expect(hpPanel().textContent).toMatch(/Hit dice: 2 of 3 \(d12\)/); - expect(within(screen.getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Rages: 3 of 3' })).toBeTruthy(); - - // Heroic Inspiration (2024) and death saving throws (SPEC C-05): a 20 at the table regains 1 hit point. - const statusBar = () => screen.getByRole('region', { name: 'Status' }); - await user.click(within(statusBar()).getByRole('checkbox', { name: 'Heroic Inspiration' })); - await waitFor(() => expect(within(statusBar()).getByRole('checkbox', { name: 'Heroic Inspiration' }).checked).toBe(true)); - expect(screen.queryByRole('region', { name: /^Death saving throws/ })).toBeNull(); - await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '40'); - await user.click(within(hpPanel()).getByRole('button', { name: 'Take damage' })); - const deathSaves = await screen.findByRole('region', { name: /^Death saving throws: 0 of 3 successes, 0 of 3 failures/ }); - await user.click(within(deathSaves).getByRole('button', { name: 'Add a failure (damage at 0)' })); - await screen.findByRole('region', { name: /^Death saving throws: 0 of 3 successes, 1 of 3 failures/ }); - // D23: healing from 0 clears the death saves, which no command puts back, so it offers no Undo (one that silently wiped - // the failure would be worse than none). Then back to 0 hit points for the roll below. - await user.clear(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' })); - await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '1'); - await user.click(within(hpPanel()).getByRole('button', { name: 'Heal' })); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 1 of 35' })).toBeTruthy()); - expect(screen.getByRole('button', { name: 'Undo last change' }).disabled).toBe(true); - await user.clear(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' })); - await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '1'); - await user.click(within(hpPanel()).getByRole('button', { name: 'Take damage' })); - await screen.findByRole('region', { name: /^Death saving throws: 0 of 3 successes, 0 of 3 failures/ }); - await user.type(within(screen.getByRole('region', { name: /^Death saving throws/ })).getByRole('spinbutton', { name: 'd20 rolled at the table' }), '20'); - await user.click(within(screen.getByRole('region', { name: /^Death saving throws/ })).getByRole('button', { name: 'Record this roll' })); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 1 of 35' })).toBeTruthy()); - expect(screen.queryByRole('region', { name: /^Death saving throws/ })).toBeNull(); // regaining hit points cleared them - await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '34'); - await user.click(within(hpPanel()).getByRole('button', { name: 'Heal' })); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 35 of 35' })).toBeTruthy()); - - // Wave 3 item 21 (D19 amended): a resistance recorded by hand on Stats halves typed damage on Play, and Undo puts it all back. - await openTab(user, sheet, 'Skills and saves'); - const defences = () => screen.getByRole('region', { name: 'Damage resistances, immunities and vulnerabilities' }); - await user.selectOptions(within(defences()).getByRole('combobox', { name: 'Damage type' }), 'slashing'); - await user.click(within(defences()).getByRole('button', { name: 'Add' })); - await waitFor(() => expect(within(defences()).getByRole('list', { name: 'Damage defences the sheet applies' }).textContent).toMatch(/Slashing resistance from Entered by hand/)); - await openTab(user, sheet, 'Play'); - await user.selectOptions(within(hpPanel()).getByRole('combobox', { name: 'Damage type' }), 'slashing'); - await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '13'); - await user.click(within(hpPanel()).getByRole('button', { name: 'Take damage' })); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 29 of 35' })).toBeTruthy()); // 13 halved, rounded down: 6 - expect(hpPanel().textContent).toMatch(/13 slashing, halved: 6\./); - await user.click(await screen.findByRole('button', { name: 'Undo last change: damage 13 slashing (6 taken)' })); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 35 of 35' })).toBeTruthy()); - // Untyped damage ignores the resistance. - await user.selectOptions(within(hpPanel()).getByRole('combobox', { name: 'Damage type' }), ''); - await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '4'); - await user.click(within(hpPanel()).getByRole('button', { name: 'Take damage' })); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 31 of 35' })).toBeTruthy()); - await user.click(await screen.findByRole('button', { name: 'Undo last change: damage 4' })); - await waitFor(() => expect(screen.getByRole('heading', { name: 'Hit points: 35 of 35' })).toBeTruthy()); - await openTab(user, sheet, 'Skills and saves'); - await user.click(within(defences()).getByRole('button', { name: 'Remove slashing resistance' })); - await waitFor(() => expect(screen.queryByRole('list', { name: 'Damage defences the sheet applies' })).toBeNull()); - - // Wave 3 item 27: Track XP is off by default; a total at the next level's threshold shows "Level up available" (display only). - const xp = () => screen.getByRole('region', { name: 'Experience points' }); - expect(within(xp()).getByRole('checkbox', { name: 'Track XP' }).checked).toBe(false); - await user.click(within(xp()).getByRole('checkbox', { name: 'Track XP' })); - const xpBox = await within(xp()).findByRole('spinbutton', { name: 'Experience points' }); - expect(xpBox.value).toBe('0'); - expect(within(xp()).queryByText('Level up available')).toBeNull(); - const nextLevelAt = /^Next level at (\d{1,3}(,\d{3})*)$/; - const threshold = Number((await within(xp()).findByText(nextLevelAt)).textContent!.replace(nextLevelAt, '$1').replaceAll(',', '')); - await user.clear(xpBox); - await user.type(xpBox, String(threshold - 1)); - await user.click(within(xp()).getByRole('button', { name: 'Save experience points' })); - // Wait for the save to land (nothing differs, so Save is aria-disabled and focus is on the heading) before typing again: - // a reply that arrives mid-type moves focus off the box and leaves a partial number in it. - await waitFor(() => expect(within(xp()).getByRole('button', { name: 'Save experience points' }).getAttribute('aria-disabled')).toBe('true')); - expect(within(xp()).getByRole('spinbutton', { name: 'Experience points' }).value).toBe(String(threshold - 1)); - expect(within(xp()).queryByText('Level up available')).toBeNull(); - await user.clear(within(xp()).getByRole('spinbutton', { name: 'Experience points' })); - await user.type(within(xp()).getByRole('spinbutton', { name: 'Experience points' }), String(threshold)); - await user.click(within(xp()).getByRole('button', { name: 'Save experience points' })); - await within(xp()).findByText('Level up available'); - await user.click(within(xp()).getByRole('checkbox', { name: 'Track XP' })); // untick: the total and the hint go - await waitFor(() => expect(within(xp()).queryByRole('spinbutton', { name: 'Experience points' })).toBeNull()); - expect(within(xp()).queryByText('Level up available')).toBeNull(); - await openTab(user, sheet, 'Play'); - - // M2 item 4: armor replaces Unarmored Defense (13); a shield adds to it. Original fixture equipment. - await openTab(user, sheet, 'Gear'); - const equipment = () => screen.getByRole('region', { name: 'Equipment' }); - await waitFor(() => expect(within(equipment()).getByRole('option', { name: /^Fixture Scale Vest/ })).toBeTruthy()); - await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^Fixture Scale Vest/ })); - await user.click(within(equipment()).getByRole('button', { name: 'Add' })); - await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip Fixture Scale Vest' })); - await waitFor(() => expect(summaryValue(sheet, 'Armor Class')).toBe('15')); // 14 + Dex 1 - await openTab(user, sheet, 'Skills and saves'); - const ac = screen.getByRole('region', { name: /^Armor Class:/ }); - await user.click(within(ac).getByRole('heading')); - expect(within(ac).getByRole('table').textContent).toMatch(/Unarmored Defense.*not used: it applies only while no armor is worn/); - - await openTab(user, sheet, 'Gear'); - await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^Fixture Kite Shield/ })); - await user.click(within(equipment()).getByRole('button', { name: 'Add' })); - await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip Fixture Kite Shield' })); - await waitFor(() => expect(summaryValue(sheet, 'Armor Class')).toBe('17')); - await user.click(within(equipment()).getByRole('checkbox', { name: 'Equip Fixture Scale Vest' })); // take the armor off - await waitFor(() => expect(summaryValue(sheet, 'Armor Class')).toBe('15')); // Unarmored Defense 13 + shield 2 -}, 180_000); - -const srd = (n: number) => ({ - contentId: `52c00000-0000-4000-8000-${String(n).padStart(12, '0')}`, - revisionId: `52e00000-0000-4000-8000-${String(n).padStart(12, '0')}`, -}); - -it('authors a homebrew subclass in the studio, plays it, and reviews an update', async () => { - const user = userEvent.setup(); - // Setup through the client: an SRD 5.2.1 Barbarian 3 without a subclass (the builder test covers building one). - await client.createCharacter({ - name: 'E2E Storm', - rulesFamily: 'srd-5.2.1', - baseAbilities: { str: 15, dex: 13, con: 14, int: 8, wis: 12, cha: 10 }, - pins: [srd(1), srd(2)], - classes: [{ class: srd(11), level: 3 }], - choices: [ - { source: srd(2), choiceId: 'soldier-ability-scores', selected: [srd(4)] }, - { source: srd(11), choiceId: 'barbarian-skills', selected: [srd(21), srd(22)] }, - { source: srd(25), choiceId: 'primal-knowledge-skill', selected: [srd(17)] }, - ], - }); - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - - // A homebrew source for 2024 rules. - const newSource = await screen.findByRole('form', { name: 'New book or notebook' }); - await user.type(within(newSource).getByRole('textbox', { name: 'Title' }), 'E2E Homebrew'); - await user.click(within(newSource).getByRole('checkbox', { name: '2024 rules' })); - await user.click(within(newSource).getByRole('button', { name: 'Create' })); - await screen.findByRole('heading', { name: 'Content in E2E Homebrew' }); - - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - const rule = (name: RegExp) => within(editor()).getByRole('group', { name }); - async function publish(name: string) { - await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); - await waitFor(() => expect(appStatus().textContent).toBe(`Made ${name} available to characters.`)); - } - - // Feature 1: a class resource, its long-rest recovery, and a limited-use action that spends it. - await user.click(screen.getByRole('button', { name: 'New feature' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Storm Ward'); - await user.click(within(editor()).getByRole('button', { name: 'Add resource' })); - await user.type(within(rule(/^Rule 1: Resource/)).getByRole('textbox', { name: 'Resource name' }), 'Storm charges'); - await user.click(within(editor()).getByRole('button', { name: 'Add recovery' })); - await user.click(within(editor()).getByRole('button', { name: 'Add roll or action' })); - const action = rule(/^Rule 3: Roll or action/); - await user.type(within(action).getByRole('textbox', { name: 'Roll name' }), 'Storm bolt'); - await user.clear(within(action).getByRole('textbox', { name: /^Dice/ })); - await user.type(within(action).getByRole('textbox', { name: /^Dice/ }), '1d8 + 2'); - await user.selectOptions(within(action).getByRole('combobox', { name: /Uses a resource/ }), 'Storm charges'); - await publish('E2E Storm Ward'); - - // Feature 2: reference-only text. - await user.click(screen.getByRole('button', { name: 'New feature' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Sky Lore'); - await user.type(within(editor()).getByRole('textbox', { name: /^Description/ }), 'You can read tomorrow’s weather.'); - await publish('E2E Sky Lore'); - - // The subclass: offered in the SRD Barbarian's subclass choice, a modifier, and both features at level 3. - await user.click(screen.getByRole('button', { name: 'New subclass' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'Path of the E2E Storm'); - const offered = within(editor()).getByRole('combobox', { name: 'Subclass of' }); - await waitFor(() => expect(within(offered).getByRole('option', { name: /^Barbarian: Level 3: Barbarian Subclass/ })).toBeTruthy()); - await user.selectOptions(offered, within(offered).getByRole('option', { name: /^Barbarian: Level 3: Barbarian Subclass/ })); - await user.click(within(editor()).getByRole('button', { name: 'Add modifier' })); // default: Initiative +1 - await user.click(within(editor()).getByRole('button', { name: 'Grant a feature' })); - await user.selectOptions(within(rule(/^Rule 2: Granted feature/)).getByRole('combobox', { name: 'Feature' }), 'E2E Storm Ward (published)'); - await user.click(within(editor()).getByRole('button', { name: 'Grant a feature' })); - await user.selectOptions(within(rule(/^Rule 3: Granted feature/)).getByRole('combobox', { name: 'Feature' }), 'E2E Sky Lore (published)'); - await user.click(within(editor()).getByRole('button', { name: 'Check' })); - expect(await within(editor()).findByText('No problems found. It can be made available to characters.')).toBeTruthy(); - await publish('Path of the E2E Storm'); - - // Play it: the homebrew subclass is an option of the SRD choice. - await user.click(screen.getByRole('button', { name: /^E2E Storm/ })); - let sheet = await screen.findByRole('article', { name: 'E2E Storm' }); - await user.click(within(sheet).getByRole('button', { name: 'Choose now' })); - await pick(user, /^Barbarian: choose 1/, /^Path of the E2E Storm/); - await user.click(await screen.findByRole('button', { name: 'Save choices' })); - sheet = await screen.findByRole('article', { name: 'E2E Storm' }); - await openTab(user, sheet, 'Skills and saves'); - expect(within(sheet).getByRole('heading', { name: /^Initiative: \+2/ })).toBeTruthy(); // Dex +1, homebrew +1 - await openTab(user, sheet, 'Play'); - const resources = within(sheet).getByRole('region', { name: 'Resources' }); - expect(within(resources).getByRole('heading', { name: 'Storm charges: 2 of 2' })).toBeTruthy(); - await openTab(user, sheet, 'Features'); - expect(within(within(sheet).getByRole('region', { name: 'Features' })).getByText('E2E Sky Lore').closest('li')!.textContent).toMatch(/Text only/); - await openTab(user, sheet, 'Play'); - await user.click(within(sheet).getByRole('button', { name: 'Roll Storm bolt (1d8 + 2)' })); - await user.click(await screen.findByRole('button', { name: 'Spend 1 Storm charges (2 left)' })); - await waitFor(() => expect(within(screen.getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Storm charges: 1 of 2' })).toBeTruthy()); - - // Republish with +3 initiative: the character keeps +2 until the reviewed update is applied. - await user.click(screen.getByRole('button', { name: 'Homebrew' })); - // The studio opens on the first source, and the other e2e file creates its own source in the same DevHost: pick ours. - const ownSource = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await user.selectOptions(ownSource, within(ownSource).getByRole('option', { name: /^E2E Homebrew/ })); - await user.click(await screen.findByRole('button', { name: 'Edit Path of the E2E Storm' })); - const modifier = rule(/^Rule 1: Modifier/); - await user.clear(within(modifier).getByRole('textbox', { name: /^Value/ })); - await user.type(within(modifier).getByRole('textbox', { name: /^Value/ }), '3'); - await publish('Path of the E2E Storm'); - expect(await screen.findByRole('button', { name: 'Review update for E2E Storm' })).toBeTruthy(); - - // M3 C7: the sheet offers the new revision too, and nothing changes until the reviewed update is applied. - await user.click(screen.getByRole('button', { name: /^E2E Storm/ })); - sheet = await screen.findByRole('article', { name: 'E2E Storm' }); - await openTab(user, sheet, 'Skills and saves'); - expect(within(sheet).getByRole('heading', { name: /^Initiative: \+2/ })).toBeTruthy(); - await openMore(user, sheet, 'Updates'); - const updates = await within(sheet).findByRole('region', { name: 'Updates available' }); - // The setup pins the M1 SRD Barbarian revision, so the newer bundled revision is offered as well. - expect(within(updates).getByRole('button', { name: 'Review update: Barbarian' }).closest('li')!.textContent).toMatch(/bundled/); - expect(within(updates).getByRole('button', { name: 'Review update: Path of the E2E Storm' }).closest('li')!.textContent).toMatch(/your source/); - await user.click(within(updates).getByRole('button', { name: 'Review update: Path of the E2E Storm' })); - const review = await within(updates).findByRole('region', { name: 'Update E2E Storm: Path of the E2E Storm' }); - const values = await within(review).findByRole('table', { name: 'Calculated values that change' }); - expect(values.textContent).toMatch(/Initiative24/); - await user.click(within(review).getByRole('button', { name: 'Apply update' })); - await waitFor(() => expect(appStatus().textContent).toMatch(/Updated E2E Storm: Path of the E2E Storm/)); - await waitFor(() => expect(summaryValue(screen.getByRole('article', { name: 'E2E Storm' }), 'Initiative')).toBe('+4')); - const remaining = () => within(within(screen.getByRole('article', { name: 'E2E Storm' })).getByRole('region', { name: 'Updates available' })); - await waitFor(() => expect(remaining().queryByRole('button', { name: 'Review update: Path of the E2E Storm' })).toBeNull()); - expect(remaining().getByRole('button', { name: 'Review update: Barbarian' })).toBeTruthy(); // still only offered - - // Import Lab (D62 L1): the studio's Coverage view for this source counts what the engine does with the rules just authored. - await user.click(screen.getByRole('button', { name: 'Homebrew' })); - const coverageSource = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await user.selectOptions(coverageSource, within(coverageSource).getByRole('option', { name: /^E2E Homebrew/ })); - const coverage = await screen.findByRole('region', { name: 'Coverage' }); - const totals = await within(coverage).findByText(/^\d+ automatic · \d+ by hand \(assisted\) · \d+ reference · \d+ not understood$/); - expect(totals.textContent).toMatch(/ · 0 not understood$/); - expect(within(coverage).getByText(/E2E Sky Lore/).closest('li')!.textContent).toContain('1 reference'); - expect(within(coverage).getByText(/E2E Storm Ward/).closest('li')!.textContent).toMatch(/^E2E Storm Ward: 2 automatic · 1 by hand \(assisted\) · 0 reference/); // resource and recovery; the roll that spends it is assisted - expect(coverage.querySelector('[role="status"], [role="alert"], [aria-live], output')).toBeNull(); // no live region of its own - - // Import Lab (D62 L2): a class of this source opens with its 20-row progression grid once a draft is saved. - await user.click(screen.getByRole('button', { name: 'New class' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Warden'); - expect(within(editor()).getByText('Save a draft of this class to see its progression.')).toBeTruthy(); - await user.click(within(editor()).getByRole('button', { name: 'Save draft' })); - const progression = await within(editor()).findByRole('region', { name: 'Class progression, scrollable' }); - await waitFor(() => expect(within(within(progression).getByRole('table', { name: 'Class progression' })).getAllByRole('row')).toHaveLength(21)); // header + 20 levels - expect(within(editor()).getByText('Draft: not yet published')).toBeTruthy(); -}); - -it('authors a +1 weapon in the studio, equips it and rolls it, and "Why?" names the weapon bonus (MECH-X item 0)', async () => { - const user = userEvent.setup(); - await client.createCharacter({ name: 'E2E Plus Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 14, dex: 12, con: 12, int: 10, wis: 10, cha: 10 }, pins: [] }); - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - - const newSource = await screen.findByRole('form', { name: 'New book or notebook' }); - await user.type(within(newSource).getByRole('textbox', { name: 'Title' }), 'E2E Plus Book'); - await user.click(within(newSource).getByRole('checkbox', { name: '2024 rules' })); - await user.click(within(newSource).getByRole('button', { name: 'Create' })); - await screen.findByRole('heading', { name: 'Content in E2E Plus Book' }); - - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - await user.click(screen.getByRole('button', { name: 'New item' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Plus Blade'); - await user.click(within(editor()).getByRole('button', { name: 'Add weapon' })); - const weapon = within(within(editor()).getByRole('group', { name: /^Rule 1: Weapon/ })); - await user.type(weapon.getByRole('textbox', { name: /^Weapon key/ }), 'blade'); - await user.clear(weapon.getByRole('textbox', { name: /^Damage \(/ })); - await user.type(weapon.getByRole('textbox', { name: /^Damage \(/ }), '1d6'); - await user.clear(weapon.getByRole('textbox', { name: /^Damage type/ })); - await user.type(weapon.getByRole('textbox', { name: /^Damage type/ }), 'slashing'); - await user.type(weapon.getByRole('textbox', { name: /^Bonus/ }), '1'); - await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); - await waitFor(() => expect(appStatus().textContent).toBe('Made E2E Plus Blade available to characters.')); - - // Carry and equip it; both rolls name the weapon bonus under "Why?". - await user.click(screen.getByRole('button', { name: /^E2E Plus Hero/ })); - const hero = await screen.findByRole('article', { name: 'E2E Plus Hero' }); - await openTab(user, hero, 'Gear'); - const equipment = () => screen.getByRole('region', { name: 'Equipment' }); - await waitFor(() => expect(within(equipment()).getByRole('option', { name: /^E2E Plus Blade/ })).toBeTruthy()); - await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^E2E Plus Blade/ })); - await user.click(within(equipment()).getByRole('button', { name: 'Add' })); - await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip E2E Plus Blade' })); - - await openTab(user, hero, 'Play'); - const actions = () => screen.getByRole('region', { name: 'Attacks and actions' }); - const whyList = async () => { - const why = within(screen.getByRole('region', { name: 'Status' })).getByText('Why?').closest('details')!; - if (!why.open) await user.click(within(why).getByText('Why?')); - return within(why).getByRole('list', { name: 'Why this roll came out this way' }).textContent ?? ''; - }; - await waitFor(() => expect(within(actions()).getByRole('button', { name: 'Roll E2E Plus Blade attack' })).toBeTruthy()); - await user.click(within(actions()).getByRole('button', { name: 'Roll E2E Plus Blade attack' })); - await waitFor(() => expect(screen.getByRole('status', { name: 'Last roll' }).textContent).toMatch(/E2E Plus Blade attack: \d+ \(1d20\)/)); - expect(await whyList()).toMatch(/\+1 to hit \(weapon\)/); - await user.click(within(actions()).getByRole('button', { name: /^Roll E2E Plus Blade damage/ })); - await waitFor(() => expect(screen.getByRole('status', { name: 'Last roll' }).textContent).toMatch(/E2E Plus Blade damage \(slashing\): \d+/)); - expect(await whyList()).toMatch(/\+1 damage \(weapon\)/); -}); - -it('item mods: a published mod attached to one copy changes only that copy\'s attack (MECH-X item 3)', async () => { - const user = userEvent.setup(); - await client.createCharacter({ name: 'E2E Mod Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 14, dex: 12, con: 12, int: 10, wis: 10, cha: 10 }, pins: [] }); - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - - const newSource = await screen.findByRole('form', { name: 'New book or notebook' }); - await user.type(within(newSource).getByRole('textbox', { name: 'Title' }), 'E2E Mod Book'); - await user.click(within(newSource).getByRole('checkbox', { name: '2024 rules' })); - await user.click(within(newSource).getByRole('button', { name: 'Create' })); - await screen.findByRole('heading', { name: 'Content in E2E Mod Book' }); - - // The host: a plain blade. The mod: item content with an item mod effect (applies to a weapon, +2). - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - await user.click(screen.getByRole('button', { name: 'New item' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Mod Blade'); - await user.click(within(editor()).getByRole('button', { name: 'Add weapon' })); - const weapon = within(within(editor()).getByRole('group', { name: /^Rule 1: Weapon/ })); - await user.type(weapon.getByRole('textbox', { name: /^Weapon key/ }), 'modblade'); - await user.clear(weapon.getByRole('textbox', { name: /^Damage \(/ })); - await user.type(weapon.getByRole('textbox', { name: /^Damage \(/ }), '1d6'); - await user.clear(weapon.getByRole('textbox', { name: /^Damage type/ })); - await user.type(weapon.getByRole('textbox', { name: /^Damage type/ }), 'slashing'); - await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); - await waitFor(() => expect(appStatus().textContent).toBe('Made E2E Mod Blade available to characters.')); - - await user.click(screen.getByRole('button', { name: 'New item' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Keen Rune'); - await user.click(within(editor()).getByRole('button', { name: 'Add mod' })); - const mod = within(within(editor()).getByRole('group', { name: /^Rule 1: Item mod/ })); - expect((mod.getByRole('combobox', { name: 'Applies to' }) as HTMLSelectElement).value).toBe('weapon'); - await user.clear(mod.getByRole('textbox', { name: /^Bonus/ })); - await user.type(mod.getByRole('textbox', { name: /^Bonus/ }), '2'); - await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); - await waitFor(() => expect(appStatus().textContent).toBe('Made E2E Keen Rune available to characters.')); - - // Carry and equip the blade, then attach the mod to a new copy: one plain copy and one modded copy. - await user.click(screen.getByRole('button', { name: /^E2E Mod Hero/ })); - const hero = await screen.findByRole('article', { name: 'E2E Mod Hero' }); - await openTab(user, hero, 'Gear'); - const equipment = () => screen.getByRole('region', { name: 'Equipment' }); - await waitFor(() => expect(within(equipment()).getByRole('option', { name: /^E2E Mod Blade/ })).toBeTruthy()); - await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^E2E Mod Blade/ })); - await user.click(within(equipment()).getByRole('button', { name: 'Add' })); - await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip E2E Mod Blade' })); - - const attach = await within(equipment()).findByRole('combobox', { name: 'Attach a mod to E2E Mod Blade' }); - await waitFor(() => expect(within(attach).getAllByRole('option').some((o) => o.textContent?.startsWith('E2E Keen Rune'))).toBe(true)); - await user.selectOptions(attach, within(attach).getAllByRole('option').find((o) => o.textContent?.startsWith('E2E Keen Rune'))!); - await user.click(within(equipment()).getByRole('button', { name: 'Attach to a new copy of E2E Mod Blade' })); - await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip E2E Mod Blade (copy 2 of 2)' })); - await within(equipment()).findByText(/^Mods on E2E Mod Blade \(copy 2 of 2\): E2E Keen Rune/); - - // Play: two attack rows; only the modded copy carries the +2, and its trace names the mod. - await openTab(user, hero, 'Play'); - const row = async (copy: number) => { - const item = await waitFor(() => { - const found = within(screen.getByRole('region', { name: 'Attacks and actions' })).getAllByRole('listitem').find((li) => li.textContent?.includes(`E2E Mod Blade (copy ${copy} of 2): `)); - expect(found).toBeTruthy(); - return found!; - }); - return item.textContent ?? ''; - }; - const toHit = (text: string) => Number(/([+-]\d+) to hit/.exec(text)![1]); - const first = await row(1); - const second = await row(2); - expect(toHit(second)).toBe(toHit(first) + 2); - expect(second).toMatch(/E2E Keen Rune: \+2 to hit \(mod\)/); - expect(first).not.toMatch(/E2E Keen Rune/); -}); - -it('content companions: a published feature\'s companion is a card with its own pool (MECH-X item 4)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Bonded Book', ['srd-5.2.1']); - await openStudioOn(user, 'E2E Bonded Book'); - - // One feature: a pool, an attack, and a companion that lists both (the checkboxes name them by label). - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - await user.click(screen.getByRole('button', { name: 'New feature' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'Fixture Warden Bond'); - await user.click(within(editor()).getByRole('button', { name: 'Add resource' })); - const pool = within(within(editor()).getByRole('group', { name: /^Rule 1: Resource/ })); - await user.type(pool.getByRole('textbox', { name: 'Resource name' }), 'Fixture Charges'); - await user.clear(pool.getByRole('textbox', { name: /^Uses/ })); - await user.type(pool.getByRole('textbox', { name: /^Uses/ }), '3'); - await user.click(within(editor()).getByRole('button', { name: 'Add attack' })); - await user.type(within(within(editor()).getByRole('group', { name: /^Rule 2: Attack/ })).getByRole('textbox', { name: 'Attack name' }), 'Fixture Bite'); - await user.click(within(editor()).getByRole('button', { name: 'Add companion' })); - const companion = within(within(editor()).getByRole('group', { name: /^Rule 3: Companion/ })); - await user.type(companion.getByRole('textbox', { name: 'Label' }), 'Fixture Warden'); - await user.clear(companion.getByRole('textbox', { name: 'Armor Class formula' })); - await user.type(companion.getByRole('textbox', { name: 'Armor Class formula' }), '15'); - await user.clear(companion.getByRole('textbox', { name: 'Hit point maximum formula' })); - await user.type(companion.getByRole('textbox', { name: 'Hit point maximum formula' }), '20'); - await user.click(companion.getByRole('checkbox', { name: 'Fixture Bite' })); - await user.click(companion.getByRole('checkbox', { name: 'Fixture Charges' })); - await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); - await waitFor(() => expect(appStatus().textContent).toBe('Made Fixture Warden Bond available to characters.')); - - // The server stored a v12 revision with the companion and both lists. - const published = (await newestOf(source.id, 'Fixture Warden Bond'))!; - expect(published.schemaVersion).toBe(12); - expect(published.effects.find((e) => e.type === 'companion')).toMatchObject({ label: 'Fixture Warden', armorClass: '15', hitPointMaximum: '20' }); - - await client.createCharacter({ name: 'E2E Bonded Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 14, dex: 12, con: 12, int: 10, wis: 10, cha: 10 }, pins: [published] }); - cleanup(); - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Bonded Hero/ })); - const hero = await screen.findByRole('article', { name: 'E2E Bonded Hero' }); - await openTab(user, hero, 'Play'); - - // The card shows Armor Class and hit points, calculated (no Edit or Remove), with its attack and pool inside it. - const card = () => screen.getByRole('region', { name: 'Fixture Warden' }); - await waitFor(() => expect(within(card()).getByText('Armor Class 15')).toBeTruthy()); - expect(within(card()).getByText('Hit points: 20 of 20')).toBeTruthy(); - expect(within(card()).queryByRole('button', { name: /^Edit / })).toBeNull(); - expect(within(card()).queryByRole('button', { name: /^Remove / })).toBeNull(); - expect(card().textContent).toMatch(/From Fixture Warden Bond/); - expect(within(card()).getByRole('button', { name: 'Roll Fixture Bite attack' })).toBeTruthy(); - - // "Take damage" goes through the play command and lowers the hit points. - await user.type(within(card()).getByRole('spinbutton', { name: 'Amount' }), '3'); - await user.click(within(card()).getByRole('button', { name: /^Take damage/ })); - await waitFor(() => expect(within(card()).getByText('Hit points: 17 of 20')).toBeTruthy()); - - // "Spend" on its own pool lowers the pool. - expect(within(card()).getByRole('heading', { name: /^Fixture Charges: 3 of 3/ })).toBeTruthy(); - await user.click(within(card()).getByRole('button', { name: 'Spend 1 Fixture Charges' })); - await waitFor(() => expect(within(card()).getByRole('heading', { name: /^Fixture Charges: 2 of 3/ })).toBeTruthy()); - - // The attack and the pool are drawn on the card only: not in the Actions or Resources panels. - const attackRolls = screen.queryAllByRole('button', { name: /^Roll Fixture Bite attack/ }); - expect(attackRolls).toHaveLength(1); - expect(card().contains(attackRolls[0]!)).toBe(true); - const poolHeadings = screen.queryAllByRole('heading', { name: /^Fixture Charges/ }); - expect(poolHeadings).toHaveLength(1); - expect(card().contains(poolHeadings[0]!)).toBe(true); -}); - -it('attaches a PDF to a source, offers the cited page on a feature, and removes it after a warning', async () => { - const user = userEvent.setup(); - // Setup through the client: a homebrew source, a published feat citing page 7, and a character using it. - const source = await client.createHomebrewSource('E2E Book', ['srd-5.1']); - const draft = await client.saveDraft({ - contentId: crypto.randomUUID(), - revisionId: '00000000-0000-0000-0000-000000000000', - kind: 'feat', - name: 'E2E Cited Feat', - rulesFamilies: ['srd-5.1'], - provenance: { sourceId: source.id, page: { start: 7 } }, - status: 'draft', - summary: 'A feat that cites page 7.', - effects: [], - }); - const feat = (await client.publish(draft)).published; - await client.createCharacter({ name: 'E2E Reader', rulesFamily: 'srd-5.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [feat] }); - - render(); - await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); - const book = await screen.findByRole('listitem', { name: 'E2E Book' }); - expect(within(book).getByText('No PDF attached.')).toBeTruthy(); - - // DevHost has no native Open dialog, so the browser file picker sends the bytes (a managed copy). - await user.click(within(book).getByRole('button', { name: 'Attach PDF…' })); - const pdf = new File([new TextEncoder().encode('%PDF-1.4\n% e2e\n%%EOF\n')], 'e2e-book.pdf', { type: 'application/pdf' }); - await user.upload(screen.getByLabelText('PDF file'), pdf); - // The upload hashes and copies the file, then reloads every source (e2e/timeouts.setup.ts allows for that). - await waitFor(() => expect(within(screen.getByRole('listitem', { name: 'E2E Book' })).getByText(/PDF: e2e-book\.pdf .*copy in TomeStack.*available/)).toBeTruthy()); - - // SPEC I-03: pages 3-4 become a draft reference entry (nothing is extracted; it stays inactive until published). - const pages = within(screen.getByRole('listitem', { name: 'E2E Book' })).getByRole('group', { name: 'Import pages of E2E Book as reference' }); - await user.type(within(pages).getByRole('spinbutton', { name: 'First page' }), '3'); - await user.type(within(pages).getByRole('spinbutton', { name: 'Last page (optional)' }), '4'); - await user.type(within(pages).getByRole('textbox', { name: 'Title (optional)' }), 'E2E Chapter'); - await user.click(within(pages).getByRole('button', { name: 'Import pages' })); - await expectStatus(/Draft reference entry "E2E Chapter" created/); - const drafts = await client.contentBySource(source.id); - expect(drafts.find((e) => e.name === 'E2E Chapter')?.revisions[0]).toMatchObject({ status: 'draft', provenance: { page: { start: 3, end: 4 } } }); - - // The feature offers its cited page; opening needs the desktop app's viewer, which DevHost does not have. - await user.click(screen.getByRole('button', { name: /^E2E Reader/ })); - // The button appears once the sheet has fetched the source's attachment (e2e/timeouts.setup.ts allows for that). - await openTab(user, await screen.findByRole('article', { name: 'E2E Reader' }), 'Features'); - const open = await screen.findByRole('button', { name: 'Open E2E Cited Feat, p. 7' }); - await user.click(open); - expect((await screen.findByRole('alert')).textContent).toMatch(/needs the TomeStack desktop app/); - - // Removing says what breaks, and keeps the content. - await user.click(screen.getByRole('button', { name: 'Books and PDFs' })); - await user.click(within(await screen.findByRole('listitem', { name: 'E2E Book' })).getByRole('button', { name: 'Remove PDF…' })); - const confirm = await screen.findByRole('alertdialog', { name: 'Remove e2e-book.pdf?' }); - // The draft reference entry cites pages in it too. - expect(confirm.textContent).toMatch(/2 entries cite pages in it \(E2E Chapter, E2E Cited Feat\)/); - await user.click(within(confirm).getByRole('button', { name: 'Remove PDF' })); - await waitFor(() => expect(within(screen.getByRole('listitem', { name: 'E2E Book' })).getByText('No PDF attached.')).toBeTruthy()); - await user.click(screen.getByRole('button', { name: /^E2E Reader/ })); - await screen.findByRole('article', { name: 'E2E Reader' }); - await openTab(user, screen.getByRole('article', { name: 'E2E Reader' }), 'Features'); - expect(screen.queryByRole('button', { name: 'Open E2E Cited Feat, p. 7' })).toBeNull(); - expect(within(screen.getByRole('region', { name: 'Features' })).getByText('E2E Cited Feat')).toBeTruthy(); -}); - -it('marks a source as shareable after confirming it is your own work, saves a source pack and imports it (M6 slice 1)', async () => { - const user = userEvent.setup(); - // Setup through the client: your own source with a published feat, and a source a PDF was attached to. - const own = await client.createHomebrewSource('E2E Own Notes', ['srd-5.1']); - const draft = await client.saveDraft({ - contentId: crypto.randomUUID(), - revisionId: '00000000-0000-0000-0000-000000000000', - kind: 'feat', - name: 'E2E Own Feat', - rulesFamilies: ['srd-5.1'], - provenance: { sourceId: own.id }, - status: 'draft', - summary: 'An original feat.', - effects: [], - }); - await client.publish(draft); - const scanned = await client.createHomebrewSource('E2E Scanned Notes', ['srd-5.1']); - await client.attachPdfData(scanned.id, 'e2e-scan.pdf', btoa('%PDF-1.4\n% e2e\n%%EOF\n')); - - render(); - await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); - const mine = await screen.findByRole('listitem', { name: 'E2E Own Notes' }); - expect(within(mine).getByText('Not shared.')).toBeTruthy(); - // A source a PDF was attached to is import-derived for good: it offers no way to share it. - const theirs = screen.getByRole('listitem', { name: 'E2E Scanned Notes' }); - expect(within(theirs).getByText(/Holds imported material \(from a PDF or a Markdown file\): never shared/)).toBeTruthy(); - expect(within(theirs).queryByRole('button', { name: 'Mark as shareable…' })).toBeNull(); - - // Marking needs the author's confirmation. - await user.click(within(mine).getByRole('button', { name: 'Mark as shareable…' })); - const confirm = await screen.findByRole('alertdialog', { name: 'Mark E2E Own Notes as shareable?' }); - const mark = within(confirm).getByRole('button', { name: 'Mark as shareable' }); - expect(mark.disabled).toBe(true); - await user.click(within(confirm).getByRole('checkbox', { name: /The source is my own work/ })); - await user.click(mark); - await expectStatus(/E2E Own Notes is marked as shareable/); - await waitFor(() => expect(within(screen.getByRole('listitem', { name: 'E2E Own Notes' })).getByText(/Marked as shareable/)).toBeTruthy()); - - // The pack offers only shareable sources; DevHost has no Save dialog, so it downloads. - const packForm = screen.getByRole('region', { name: 'Share sources as a TomeStack file' }); - expect(within(packForm).queryByRole('checkbox', { name: 'E2E Scanned Notes' })).toBeNull(); - await user.click(within(packForm).getByRole('checkbox', { name: 'E2E Own Notes' })); - await user.click(within(packForm).getByRole('button', { name: 'Preview file' })); - const preview = await within(packForm).findByRole('region', { name: 'TomeStack file preview' }); - expect(preview.textContent).toMatch(/1 source, 1 published version/); - // L5: the preflight lists what goes (and what stays), and Save waits for it. - const preflight = await within(packForm).findByRole('region', { name: 'Preflight: TomeStack file' }); - expect(preflight.textContent).toMatch(/Included: 1 item\. Left out: 1\./); - expect(preflight.textContent).toMatch(/E2E Own Feat \(E2E Own Notes\): a draft; only published content is shared/); // the draft stays here - await waitFor(() => expect(within(preview).getByRole('button', { name: 'Save file…' }).disabled).toBe(false)); - const downloads = vi.mocked(downloadBase64).mock.calls.length; - await user.click(within(preview).getByRole('button', { name: 'Save file…' })); - await waitFor(() => expect(vi.mocked(downloadBase64).mock.calls.length).toBe(downloads + 1)); - const [fileName, base64] = vi.mocked(downloadBase64).mock.calls[downloads]!; - expect(fileName).toBe('E2E-Own-Notes-source-pack.tomestack.zip'); - - // Importing it: the preview says what a source pack is; here everything is already installed. - await user.upload(screen.getByLabelText('TomeStack file'), new File([bytesOf(base64)], fileName, { type: 'application/zip' })); - const importing = await screen.findByRole('region', { name: 'Import a TomeStack file' }); - expect(within(importing).getByText(/This TomeStack file holds sources\. Its sender stated that each source is their own work/)).toBeTruthy(); - await user.click(within(importing).getByRole('button', { name: 'Apply import' })); - await expectStatus(/unchanged/); - - // L5: a shareable source with nothing published blocks the pack, in words (the export would refuse it too). - const late = await client.createHomebrewSource('E2E Late Notes', ['srd-5.1']); - await client.setShareable(late.id, true, true); - await user.click(screen.getByRole('button', { name: 'Books and PDFs' })); - const lateForm = await screen.findByRole('region', { name: 'Share sources as a TomeStack file' }); - await user.click(await within(lateForm).findByRole('checkbox', { name: 'E2E Late Notes' })); - const blocked = await within(lateForm).findByRole('region', { name: 'Preflight: TomeStack file' }); - expect(within(blocked).getByRole('alert').textContent).toMatch(/E2E Late Notes: nothing is published yet/); -}); - -it('shares a campaign as a campaign pack that names what it leaves out, and imports it over a changed copy by choice (M6 slice 2)', async () => { - const user = userEvent.setup(); - // Setup through the client: your own shareable homebrew, homebrew you did not mark, and a campaign allowing both and the SRD. - async function homebrew(title: string, shareable: boolean) { - const source = await client.createHomebrewSource(title, ['srd-5.2.1']); - if (shareable) await client.setShareable(source.id, true, true); - const draft = await client.saveDraft({ - contentId: crypto.randomUUID(), - revisionId: '00000000-0000-0000-0000-000000000000', - kind: 'feat', - name: `${title} Feat`, - rulesFamilies: ['srd-5.2.1'], - provenance: { sourceId: source.id }, - status: 'draft', - summary: 'An original feat.', - effects: [], - }); - await client.publish(draft); - return source; - } - const harbor = await homebrew('E2E Harbor Notes', true); - const secret = await homebrew('E2E Secret Notes', false); - const campaign = await client.saveCampaign({ - id: '00000000-0000-0000-0000-000000000000', - name: 'E2E Harbor Table', - rulesFamily: 'srd-5.2.1', - allowedSources: ['52500000-0000-4000-8000-000000000001', harbor.id, secret.id], - houseRules: 'Original house rule: rests take a full day.', - }); - - render(); - const campaignsButton = await screen.findByRole('button', { name: 'Campaigns' }); - await waitFor(() => expect(campaignsButton.disabled).toBe(false)); - await user.click(campaignsButton); - await user.click(await screen.findByRole('button', { name: 'Share E2E Harbor Table…' })); - const share = await screen.findByRole('region', { name: 'Share E2E Harbor Table' }); - await waitFor(() => expect(share.textContent).toMatch(/1 source carried with 1 available version; System Reference Document 5\.2\.1 named, not copied/)); - // The guard: homebrew you did not mark as your own shareable work is only named. - const leftOut = within(share).getByRole('region', { name: 'Left out of the TomeStack file' }); - expect(leftOut.textContent).toMatch(/E2E Secret Notes .*not marked as shareable/); - - // DevHost has no Save dialog, so it downloads. - // L5: the preflight names the same source in words, and Save waits for it. - const campaignCheck = await within(share).findByRole('region', { name: 'Preflight: TomeStack file' }); - expect(campaignCheck.textContent).toMatch(/E2E Secret Notes.*not marked as your own shareable work/); - await waitFor(() => expect(within(share).getByRole('button', { name: 'Save TomeStack file…' }).disabled).toBe(false)); - const downloads = vi.mocked(downloadBase64).mock.calls.length; - await user.click(within(share).getByRole('button', { name: 'Save TomeStack file…' })); - await waitFor(() => expect(vi.mocked(downloadBase64).mock.calls.length).toBe(downloads + 1)); - const [fileName, base64] = vi.mocked(downloadBase64).mock.calls[downloads]!; - expect(fileName).toBe('E2E-Harbor-Table-campaign-pack.tomestack.zip'); - - // Here the campaign changes after the pack was made; importing it asks which version to keep. - await client.saveCampaign({ ...campaign, name: 'E2E Harbor Table (local)', allowedSources: ['52500000-0000-4000-8000-000000000001', harbor.id] }); - await user.upload(screen.getByLabelText('TomeStack file'), new File([bytesOf(base64)], fileName, { type: 'application/zip' })); - const importing = await screen.findByRole('region', { name: 'Import a TomeStack file' }); - expect(within(importing).getByText(/This TomeStack file holds a campaign/)).toBeTruthy(); - const apply = within(importing).getByRole('button', { name: 'Apply import' }); - expect(apply.disabled).toBe(true); - const decision = within(importing).getByRole('group', { name: 'Campaign “E2E Harbor Table” differs from yours' }); - expect(within(decision).getByRole('rowheader', { name: 'allowedSources' })).toBeTruthy(); - await user.click(within(decision).getByRole('radio', { name: 'Use the imported version' })); - await user.click(apply); - await expectStatus(/1 replaced.*copied to backups\/pre-import-.*\.db/); - expect((await client.listCampaigns()).find((c) => c.id === campaign.id)?.name).toBe('E2E Harbor Table'); -}); - -it('installs the sample extension after granting its permissions, runs its import and export hooks, and removes it (M6 slice 3)', async () => { - const user = userEvent.setup(); - // The external sample, packed as a user would: extension.json and transforms/ from examples/extensions. - const folder = resolve(process.cwd(), '../../examples/extensions/spell-list-and-sheet-summary'); - const files: Record = { 'extension.json': readFileSync(resolve(folder, 'extension.json')) }; - for (const name of readdirSync(resolve(folder, 'transforms'))) files[`transforms/${name}`] = readFileSync(resolve(folder, 'transforms', name)); - const extension = new File([zip(files)], 'spell-list-and-sheet-summary.tomestack-ext.zip', { type: 'application/zip' }); - await client.createCharacter({ name: 'E2E Ext Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 14, con: 12, int: 10, wis: 10, cha: 10 }, pins: [] }); - - render(); - await openAddOns(user); - // DevHost has no native Open dialog, so the browser picker is used. - await user.click(await screen.findByRole('button', { name: 'Install extension…' })); - await user.upload(screen.getByLabelText('Extension file'), extension); - const review = await screen.findByRole('region', { name: 'Install Spell list and sheet summary (sample)?' }); - const install = within(review).getByRole('button', { name: 'Install with these permissions' }); - expect(install.disabled).toBe(true); // nothing is granted until it is ticked - const permissions = within(within(review).getByRole('group', { name: 'Permissions to grant' })).getAllByRole('checkbox'); - expect(permissions).toHaveLength(4); - for (const permission of permissions) await user.click(permission); - await user.click(install); - await expectStatus(/Installed Spell list and sheet summary \(sample\) with 4 permissions/); - const item = await screen.findByRole('listitem', { name: 'Spell list and sheet summary (sample)' }); - - // Import: a CSV spell list becomes drafts in a new source; nothing is written before "Create drafts". - await user.click(within(item).getByRole('button', { name: 'Import a CSV spell list as draft spells' })); - const importRun = await screen.findByRole('region', { name: 'Run Import a CSV spell list as draft spells' }); - await user.clear(within(importRun).getByRole('textbox', { name: 'New source for the drafts' })); - await user.type(within(importRun).getByRole('textbox', { name: 'New source for the drafts' }), 'E2E Imported Spells'); - await user.click(within(importRun).getByRole('button', { name: 'Choose CSV file…' })); - const csv = readFileSync(resolve(folder, 'sample-spells.csv')); - await user.upload(screen.getByLabelText('Import a CSV spell list as draft spells: file'), new File([csv], 'sample-spells.csv', { type: 'text/csv' })); - const drafts = await within(importRun).findByRole('region', { name: 'Preview of Import a CSV spell list as draft spells' }); - expect(drafts.textContent).toMatch(/3 drafts in the new source E2E Imported Spells/); - expect(drafts.textContent).toMatch(/never shared/); - expect((await client.listSources()).some((s) => s.title === 'E2E Imported Spells')).toBe(false); - await user.click(within(drafts).getByRole('button', { name: 'Create drafts' })); - await expectStatus(/Created 3 drafts in the new source E2E Imported Spells/); - const imported = (await client.listSources()).find((s) => s.title === 'E2E Imported Spells')!; - expect(imported.importDerived).toBe(true); - expect((await client.contentBySource(imported.id)).every((e) => e.latest.status === 'draft')).toBe(true); - - // Export: the sheet summary, previewed and then saved (DevHost downloads). No local path reaches it. - await user.click(within(screen.getByRole('listitem', { name: 'Spell list and sheet summary (sample)' })).getByRole('button', { name: 'Export a sheet summary as Markdown' })); - const exportRun = await screen.findByRole('region', { name: 'Run Export a sheet summary as Markdown' }); - await user.selectOptions(within(exportRun).getByRole('combobox', { name: 'Character' }), 'E2E Ext Hero'); - await user.click(within(exportRun).getByRole('button', { name: 'Preview output' })); - const output = await within(exportRun).findByRole('region', { name: 'Preview of Export a sheet summary as Markdown' }); - expect(output.textContent).toMatch(/# E2E Ext Hero/); - const downloads = vi.mocked(downloadBase64).mock.calls.length; - await user.click(within(output).getByRole('button', { name: 'Save output…' })); - await waitFor(() => expect(vi.mocked(downloadBase64).mock.calls.length).toBe(downloads + 1)); - const [fileName, base64] = vi.mocked(downloadBase64).mock.calls[downloads]!; - expect(fileName).toBe('E2E-Ext-Hero-sheet-markdown.md'); - const markdown = new TextDecoder().decode(bytesOf(base64)); - expect(markdown).toMatch(/## Sources and licenses/); - expect(markdown.toLowerCase().replaceAll('\\', '/')).not.toContain(inject('devHost').dataDir.toLowerCase().replaceAll('\\', '/')); - - // Remove: its permissions and file go; its drafts stay. - await user.click(within(screen.getByRole('listitem', { name: 'Spell list and sheet summary (sample)' })).getByRole('button', { name: 'Remove Spell list and sheet summary (sample)…' })); - await user.click(within(await screen.findByRole('alertdialog', { name: 'Remove Spell list and sheet summary (sample)?' })).getByRole('button', { name: 'Remove' })); - await expectStatus(/Removed Spell list and sheet summary \(sample\)/); - expect(await client.listExtensions()).toEqual([]); - expect(await client.contentBySource(imported.id)).toHaveLength(3); -}); - -it('exports a character for Foundry VTT and as sheet JSON after a preview, with no local path in either file (M6 slice 4)', async () => { - const user = userEvent.setup(); - const character = await client.createCharacter({ name: 'E2E VTT Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 14, con: 12, int: 10, wis: 10, cha: 10 }, pins: [] }); - render(); - await user.click(await screen.findByRole('button', { name: /^E2E VTT Hero/ })); - const sheet = await screen.findByRole('article', { name: 'E2E VTT Hero' }); - await openMore(user, sheet, 'Export…'); - const panel = within(sheet).getByRole('region', { name: 'Export for a virtual tabletop' }); - const dataDir = inject('devHost').dataDir.toLowerCase().replaceAll('\\', '/'); - - // Foundry VTT (dnd5e): the preview names the pinned release, then DevHost downloads the file. - await user.click(within(panel).getByRole('radio', { name: /Foundry VTT \(dnd5e system\)/ })); - await user.click(within(panel).getByRole('button', { name: 'Preview export' })); - const preview = await within(panel).findByRole('region', { name: 'Export preview' }); - expect(preview.textContent).toMatch(/E2E-VTT-Hero\.foundry-dnd5e\.json.*checked against Foundry VTT 14\.367 with dnd5e 6\.0\.6/); - expect(preview.textContent).toMatch(/not affiliated with Foundry Gaming LLC/); - const downloads = vi.mocked(downloadBase64).mock.calls.length; - await within(panel).findByRole('region', { name: 'Preflight: shared sheet' }); - await waitFor(() => expect(within(preview).getByRole('button', { name: 'Save export file…' }).disabled).toBe(false)); - await user.click(within(preview).getByRole('button', { name: 'Save export file…' })); - await waitFor(() => expect(vi.mocked(downloadBase64).mock.calls.length).toBe(downloads + 1)); - const [foundryName, foundry64] = vi.mocked(downloadBase64).mock.calls[downloads]!; - expect(foundryName).toBe('E2E-VTT-Hero.foundry-dnd5e.json'); - const actorText = new TextDecoder().decode(bytesOf(foundry64)); - const actor = JSON.parse(actorText) as { type: string; name: string; _stats: { systemVersion: string } }; - expect([actor.type, actor.name, actor._stats.systemVersion]).toEqual(['character', 'E2E VTT Hero', '6.0.6']); - expect(actorText.toLowerCase().replaceAll('\\\\', '/').replaceAll('\\', '/')).not.toContain(dataDir); - - // The neutral sheet JSON. - await user.click(within(panel).getByRole('radio', { name: /TomeStack sheet \(JSON\)/ })); - await user.click(within(panel).getByRole('button', { name: 'Preview export' })); - const sheetPreview = await within(panel).findByRole('region', { name: 'Export preview' }); - await waitFor(() => expect(within(sheetPreview).getByRole('button', { name: 'Save export file…' }).disabled).toBe(false)); - await user.click(within(sheetPreview).getByRole('button', { name: 'Save export file…' })); - await waitFor(() => expect(vi.mocked(downloadBase64).mock.calls.length).toBe(downloads + 2)); - const [sheetName, sheet64] = vi.mocked(downloadBase64).mock.calls[downloads + 1]!; - expect(sheetName).toBe('E2E-VTT-Hero.tomestack-sheet.json'); - const model = JSON.parse(new TextDecoder().decode(bytesOf(sheet64))) as { format: string; formatVersion: number; character: { name: string } }; - expect([model.format, model.formatVersion, model.character.name]).toEqual(['tomestack.sheet', 1, 'E2E VTT Hero']); - expect(character.character.id).toBeTruthy(); -}); - -it('follows the authoring guides: the extension guide, packed as written, installs, is granted and exports its features with every notice (M6 slice 5)', async () => { - const user = userEvent.setup(); - // docs/authoring/extension.md, its tagged blocks exactly as the guide shows them. - const guide = readFileSync(resolve(process.cwd(), '../../docs/authoring/extension.md'), 'utf8'); - const files: Record = {}; - for (const match of guide.matchAll(/```json tomestack-example:([^\r\n]+)\r?\n([\s\S]*?)\r?\n```/g)) { - const name = match[1]!.trim(); - if (name === 'extension.json' || name.startsWith('transforms/')) files[name] = new TextEncoder().encode(match[2]!); - } - expect(Object.keys(files).sort()).toEqual(['extension.json', 'transforms/features-md.json']); - // A class, so the file has feature lines and an SRD notice. - await client.createCharacter({ name: 'E2E Guide Reader', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [], classes: [{ class: srd(11), level: 1 }] }); - - render(); - await openAddOns(user); - await user.click(await screen.findByRole('button', { name: 'Install extension…' })); - await user.upload(screen.getByLabelText('Extension file'), new File([zip(files)], 'example-feature-list.tomestack-ext.zip', { type: 'application/zip' })); - // "Tick the permissions and choose Install with these permissions." - const review = await screen.findByRole('region', { name: 'Install Example feature list?' }); - for (const permission of within(within(review).getByRole('group', { name: 'Permissions to grant' })).getAllByRole('checkbox')) await user.click(permission); - await user.click(within(review).getByRole('button', { name: 'Install with these permissions' })); - await expectStatus(/Installed Example feature list with 2 permissions/); - // "Then choose the hook (Export features as Markdown), pick a character …, choose Preview output, and Save output…" - await user.click(within(await screen.findByRole('listitem', { name: 'Example feature list' })).getByRole('button', { name: 'Export features as Markdown' })); - const run = await screen.findByRole('region', { name: 'Run Export features as Markdown' }); - await user.selectOptions(within(run).getByRole('combobox', { name: 'Character' }), 'E2E Guide Reader'); - await user.click(within(run).getByRole('button', { name: 'Preview output' })); - const output = await within(run).findByRole('region', { name: 'Preview of Export features as Markdown' }); - expect(output.textContent).toMatch(/# Features of E2E Guide Reader/); - const downloads = vi.mocked(downloadBase64).mock.calls.length; - await user.click(within(output).getByRole('button', { name: 'Save output…' })); - await waitFor(() => expect(vi.mocked(downloadBase64).mock.calls.length).toBe(downloads + 1)); - const [fileName, base64] = vi.mocked(downloadBase64).mock.calls[downloads]!; - expect(fileName).toBe('E2E-Guide-Reader-features-md.md'); - const text = new TextDecoder().decode(bytesOf(base64)); - expect(text).toMatch(/^- .+ \([a-z]+\), from .+$/m); // at least one feature line - expect(text).toMatch(/## Sources and licenses\n- .+CC-BY-4\.0/); - await client.removeExtension((await client.listExtensions()).find((x) => x.manifest.name === 'Example feature list')!.id); -}); - -// The gate runs in srd-5.1. It publishes the placeholder class's features ("Fixture Beacon" and the like), and an installed feature of -// a class-table name in the same rules family is linked instead of becoming a stub candidate. The PDF tests import fixture-import.pdf -// into srd-5.2.1 sources and expect 19 candidates, so keeping this test's content in the other family leaves them untouched wherever -// this test sits in the file. -it('D60 gate: a Markdown class is reviewed, accepted with its confirm tick and published, then its coverage and 20-level grid open in the studio', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Gate Book', ['srd-5.1']); - const markdown = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/lab/placeholder-class.md')); - await client.startMarkdownImportData(source.id, 'placeholder-class.md', markdown.toString('base64')); - - render(); - await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); - const reader = () => within(screen.getByRole('listitem', { name: 'E2E Gate Book' })).getByRole('region', { name: 'Read the text of E2E Gate Book' }); - await screen.findByRole('listitem', { name: 'E2E Gate Book' }); - await user.click(await within(reader()).findByRole('button', { name: /^Review \d+ entr(y|ies) found$/ }, { timeout: 30000 })); - const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Gate Book' }); - await within(reader()).findByRole('region', { name: 'Entries found in E2E Gate Book' }); - await user.selectOptions(within(panel()).getByRole('combobox', { name: 'Kind' }), 'class'); - await user.click(await candidateButton(panel, 'Placeholder')); - const details = () => within(panel()).getByRole('region', { name: 'Entry: Placeholder' }); - await waitFor(() => expect(within(details()).getByRole('region', { name: 'Check before keeping' })).toBeTruthy()); - - // Keep stays held until the hit die is confirmed against the page; the proficiencies are left as reference. - await waitFor(() => expect(within(details()).getByRole('button', { name: 'Keep, with its rules' }).getAttribute('aria-disabled')).toBe('true')); - await user.click(await waitFor(() => within(details()).getByRole('checkbox', { name: /^Confirm the hit die/ }))); - await waitFor(() => expect(within(details()).getByRole('button', { name: 'Keep, with its rules' }).getAttribute('aria-disabled')).toBeNull()); - await user.click(within(details()).getByRole('button', { name: 'Keep, with its rules' })); - await waitFor(() => expect(appStatus().textContent).toMatch(/Placeholder is now a draft granting 10 features in Homebrew/)); - const drafts = await client.contentBySource(source.id); - expect(drafts).toHaveLength(11); - expect(drafts.every((e) => e.latest.status === 'draft')).toBe(true); - expect(drafts.find((e) => e.name === 'Placeholder')!.latest.effects.find((e) => e.type === 'hitDie')!.automation).toBe('automatic'); - - // Publish all drafts of the source through the studio panel. - await user.click(screen.getByRole('button', { name: 'Homebrew' })); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Gate Book/ })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Gate Book/ })); - await user.click(await screen.findByRole('button', { name: 'Make all drafts in this source available to characters…' })); - const region = screen.getByRole('region', { name: 'Make drafts of E2E Gate Book available to characters' }); - const publish = await within(region).findByRole('button', { name: 'Make 11 drafts available to characters' }); - await waitFor(() => expect(publish.getAttribute('aria-disabled')).toBeNull()); - await user.click(publish); - await within(region).findByText('Made 11 drafts available to characters.'); - expect((await client.contentBySource(source.id)).every((e) => e.latest.status === 'published')).toBe(true); - - // Coverage: the totals the fixture plants, and the features whose text sounds like a mechanic are flagged for hand play. - const coverage = await screen.findByRole('region', { name: 'Coverage' }); - const totals = '1 automatic · 0 by hand (assisted) · 14 reference · 0 not understood'; - await waitFor(() => expect(within(coverage).getAllByText(totals)).toHaveLength(2)); // the source line and the class line - const flagged = (name: string) => within(coverage).getByText(new RegExp(`^${name}:`)).closest('li')!.textContent!; - for (const name of ['Fixture Pool', 'Fixture Lull', 'Fixture Finale']) expect(flagged(name)).toContain('May need a mechanic'); - expect(flagged('Fixture Edge')).not.toContain('May need a mechanic'); - expect(coverage.textContent).not.toContain("can't calculate this"); - - // The class opens with its 20-row grid; level 20 grants the finale, and a level with no feature shows a dash. - await user.click(await screen.findByRole('button', { name: 'Edit Placeholder' })); - const progression = await screen.findByRole('region', { name: 'Class progression, scrollable' }); - const grid = within(progression).getByRole('table', { name: 'Class progression' }); - await waitFor(() => expect(within(grid).getAllByRole('row')).toHaveLength(21)); // header + 20 levels - const row = (level: number) => within(grid).getByRole('rowheader', { name: String(level) }).closest('tr')!; - expect(within(row(20)).getByRole('button', { name: 'Edit Fixture Finale' })).toBeTruthy(); - expect(within(row(1)).getByRole('button', { name: 'Edit Fixture Pool' })).toBeTruthy(); - expect(row(4).textContent).toContain('—'); -}); - -it('reads the fixture PDF, reviews its candidates, and publishes an accepted one through the studio', async () => { - // M4 D5 (SPEC I-02): the original fixture book, read by the real worker next to the DevHost. - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Grimoire', ['srd-5.2.1']); - // jsdom gives import.meta.url no file scheme; the e2e run starts in src/Ui (npm --prefix). - const book = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-import.pdf')); - await client.attachPdfData(source.id, 'fixture-import.pdf', book.toString('base64')); - - render(); - await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); - const reader = () => within(screen.getByRole('listitem', { name: 'E2E Grimoire' })).getByRole('region', { name: 'Read the text of E2E Grimoire' }); - await user.click(within(await screen.findByRole('listitem', { name: 'E2E Grimoire' })).getByRole('button', { name: 'Read the whole document' })); - // M4 stays experimental until a real third-party PDF and the SRD measurements pass (ROADMAP M4). - expect(within(reader()).getByRole('heading', { name: /Find entries in this PDF Experimental/ })).toBeTruthy(); - const reviewButton = await within(reader()).findByRole('button', { name: 'Review 19 entries found' }, { timeout: 30000 }); - // Page 6 (of 7) has no text layer: the worker tries Windows OCR where a language is installed, and finds nothing either way. - expect(within(reader()).getByText(/whole document: completed, 7 pages read, (1 by OCR, )?1 without text, 19 entries found\./)).toBeTruthy(); - - // SPEC I-03: the read text is searchable within this source. - await user.type(within(reader()).getByRole('textbox', { name: 'Search the text of E2E Grimoire' }), 'hookblade'); - await user.click(within(reader()).getByRole('button', { name: 'Search' })); - expect((await within(reader()).findByRole('list', { name: 'Search results' })).textContent).toMatch(/p\. 4.*Fixture Hookblade/); - - await user.click(reviewButton); - const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Grimoire' }); - const list = () => within(panel()).getByRole('list', { name: 'Entries found' }); - await within(reader()).findByRole('region', { name: 'Entries found in E2E Grimoire' }); - await waitFor(() => expect(within(list()).getAllByRole('listitem')).toHaveLength(19)); - const kind = within(panel()).getByRole('combobox', { name: 'Kind' }); - const detail = (name: string) => within(panel()).findByRole('region', { name: `Entry: ${name}` }); - - // A clean spell: excerpt, page, what was read; the check passes; keeping makes a draft. - await user.selectOptions(kind, 'spell'); - await waitFor(() => expect(within(list()).getAllByRole('listitem')).toHaveLength(2)); - await user.click(await candidateButton(panel, 'Fixture Ember Lance')); // a slow PDF worker may still be filling the list - const ember = await detail('Fixture Ember Lance'); - await waitFor(() => expect(document.activeElement).toBe(within(ember).getByRole('heading', { name: 'Entry: Fixture Ember Lance' }))); - expect(within(ember).getByRole('figure').textContent).toMatch(/Excerpt from p\. 2.*Fixture Ember Lance.*3d6 Fire/s); - expect(ember.querySelector('dl[aria-label="What was read"]')!.textContent).toMatch(/level2schoolevocationcastingtimeAction/); - await user.click(within(ember).getByRole('button', { name: 'Open page 2' })); - expect((await screen.findByRole('alert')).textContent).toMatch(/needs the TomeStack desktop app/); - const acceptEmber = within(ember).getByRole('button', { name: 'Keep, with its rules' }); - await waitFor(() => expect(acceptEmber.getAttribute('aria-disabled')).toBeNull()); - await user.click(acceptEmber); - await waitFor(() => expect(appStatus().textContent).toMatch(/Fixture Ember Lance is now a draft in Homebrew/)); - // It left the "to review" list with its details, so focus goes back to the list (WCAG 2.4.3). - await waitFor(() => expect(document.activeElement).toBe(within(panel()).getByRole('heading', { name: 'Entries found in E2E Grimoire' }))); - // The review says what happens next and offers the studio (item 2); the flow below still goes by the sidebar. - expect(within(panel()).getByRole('button', { name: 'Open E2E Grimoire in Homebrew' })).toBeTruthy(); - - // Ignore the other spell. - await user.click(await candidateButton(panel, 'Fixture Frost Veil')); - await user.click(within(await detail('Fixture Frost Veil')).getByRole('button', { name: 'Ignore' })); - await waitFor(() => expect(appStatus().textContent).toMatch(/Ignored Fixture Frost Veil/)); - - // An unresolved reference blocks "Keep, with its rules"; "Keep as text only" keeps the text and page only. - await user.selectOptions(kind, 'feature'); - await user.click(await candidateButton(panel, 'Fixture Stormcall')); - const stormcall = await detail('Fixture Stormcall'); - expect(within(within(stormcall).getByRole('group', { name: 'Unresolved references' })).getByRole('checkbox', { name: 'Dismiss Fixture Thunder Word' })).toBeTruthy(); - await within(stormcall).findByRole('list', { name: 'Blocks keeping' }); - expect(within(stormcall).getByRole('button', { name: 'Keep, with its rules' }).getAttribute('aria-disabled')).toBe('true'); - await user.click(within(stormcall).getByRole('button', { name: 'Keep as text only' })); - await waitFor(() => expect(appStatus().textContent).toMatch(/Fixture Stormcall is now a draft reference entry/)); - - // The feat: kept as a draft, then published in the studio, which validates it again. - await user.selectOptions(kind, 'feat'); - await user.click(await candidateButton(panel, 'Fixture Keen Watcher')); - const feat = await detail('Fixture Keen Watcher'); - const acceptFeat = within(feat).getByRole('button', { name: 'Keep, with its rules' }); - await waitFor(() => expect(acceptFeat.getAttribute('aria-disabled')).toBeNull()); - await user.click(acceptFeat); - await waitFor(() => expect(appStatus().textContent).toMatch(/Fixture Keen Watcher is now a draft/)); - - // Only drafts exist: nothing is active until it is published. - const entries = await client.contentBySource(source.id); - expect(entries.map((e) => [e.name, e.latest.status]).sort()).toEqual([ - ['Fixture Ember Lance', 'draft'], - ['Fixture Keen Watcher', 'draft'], - ['Fixture Stormcall', 'draft'], - ]); - expect(entries.find((e) => e.name === 'Fixture Keen Watcher')!.latest.effects.every((e) => e.automation === 'reference')).toBe(true); - - const studio = screen.getByRole('button', { name: 'Homebrew' }); - await user.click(studio); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Grimoire/ })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Grimoire/ })); - await user.click(await screen.findByRole('button', { name: 'Edit Fixture Keen Watcher' })); - const editor = screen.getByRole('region', { name: /^Edit Fixture Keen Watcher/ }); - await user.click(within(editor).getByRole('button', { name: 'Make available to characters' })); - await waitFor(() => expect(appStatus().textContent).toBe('Made Fixture Keen Watcher available to characters.')); - expect((await client.contentBySource(source.id)).find((e) => e.name === 'Fixture Keen Watcher')!.latest.status).toBe('published'); -}); - -it('imports a fixture class: the table is checked, the hit die and slots are confirmed, and the class is saved with its linked features (item 11, D34)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Class Book', ['srd-5.2.1']); - const book = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-import.pdf')); - await client.attachPdfData(source.id, 'fixture-import.pdf', book.toString('base64')); - - render(); - await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); - const reader = () => within(screen.getByRole('listitem', { name: 'E2E Class Book' })).getByRole('region', { name: 'Read the text of E2E Class Book' }); - await user.click(within(await screen.findByRole('listitem', { name: 'E2E Class Book' })).getByRole('button', { name: 'Read the whole document' })); - await user.click(await within(reader()).findByRole('button', { name: 'Review 19 entries found' }, { timeout: 30000 })); - const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Class Book' }); - await within(reader()).findByRole('region', { name: 'Entries found in E2E Class Book' }); - await user.selectOptions(within(panel()).getByRole('combobox', { name: 'Kind' }), 'class'); - await user.click(await candidateButton(panel, 'Fixture Lamplighter')); - const lamplighter = await within(panel()).findByRole('region', { name: 'Entry: Fixture Lamplighter' }); - - // The slot table and the linked features are on screen to check against the page. - const table = await within(lamplighter).findByRole('table', { name: 'Spell slots by class level, as read from the page' }); - expect(within(table).getAllByRole('rowheader')).toHaveLength(20); - expect(within(lamplighter).getByRole('button', { name: 'Open page 7' })).toBeTruthy(); - const linked = await within(lamplighter).findByRole('list', { name: 'Linked features' }); - await waitFor(() => expect(within(linked).getAllByRole('listitem').length).toBeGreaterThan(3)); - - // The spell list name is the detector's guess: saving the edit settles it. Keep stays held until the confirmations are ticked. - await user.click(within(lamplighter).getByRole('button', { name: 'Save edit' })); - await waitFor(() => expect(appStatus().textContent).toMatch(/Saved your edit of Fixture Lamplighter/)); - // The details are rebuilt from the saved edit, and checked again. - await waitFor(() => expect(within(panel()).getByRole('region', { name: 'Entry: Fixture Lamplighter' })).not.toBe(lamplighter)); - const again = within(panel()).getByRole('region', { name: 'Entry: Fixture Lamplighter' }); - await waitFor(() => expect(within(again).getByRole('region', { name: 'Check before keeping' }).textContent).not.toMatch(/unsure/)); - const accept = within(again).getByRole('button', { name: 'Keep, with its rules' }); - expect(accept.getAttribute('aria-disabled')).toBe('true'); - await user.click(within(again).getByRole('checkbox', { name: /^Confirm the hit die/ })); - await user.click(within(again).getByRole('checkbox', { name: 'Confirm the spell slot table' })); - await waitFor(() => expect(accept.getAttribute('aria-disabled')).toBeNull()); - await user.click(accept); - await waitFor(() => expect(appStatus().textContent).toMatch(/Fixture Lamplighter is now a draft granting \d+ features in Homebrew/)); - const granting = Number(/granting (\d+) features/.exec(appStatus().textContent ?? '')![1]); - - const entries = await client.contentBySource(source.id); - const cls = entries.find((e) => e.name === 'Fixture Lamplighter')!; - expect(entries.length).toBeGreaterThan(3); - expect(entries.every((e) => e.latest.status === 'draft')).toBe(true); - expect(cls.latest.effects.find((e) => e.type === 'hitDie')!.automation).toBe('automatic'); - // The status counts exactly the features the class draft grants. - const grants = cls.latest.effects.filter((e) => e.type === 'grant' && e.grant === 'content').length; - expect(grants).toBeGreaterThan(3); - expect(granting).toBe(grants); -}); - -it('selects a proposed effect of a fixture class and sees its lines highlighted on the stored page text (D64)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Span Book', ['srd-5.2.1']); - const book = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-import.pdf')); - await client.attachPdfData(source.id, 'fixture-import.pdf', book.toString('base64')); - - render(); - await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); - const reader = () => within(screen.getByRole('listitem', { name: 'E2E Span Book' })).getByRole('region', { name: 'Read the text of E2E Span Book' }); - await user.click(within(await screen.findByRole('listitem', { name: 'E2E Span Book' })).getByRole('button', { name: 'Read the whole document' })); - await user.click(await within(reader()).findByRole('button', { name: 'Review 19 entries found' }, { timeout: 30000 })); - const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Span Book' }); - await within(reader()).findByRole('region', { name: 'Entries found in E2E Span Book' }); - await user.selectOptions(within(panel()).getByRole('combobox', { name: 'Kind' }), 'class'); - await user.click(await candidateButton(panel, 'Fixture Lamplighter')); - const lamplighter = await within(panel()).findByRole('region', { name: 'Entry: Fixture Lamplighter' }); - - // Before a choice the whole excerpt shows, as always. - expect(lamplighter.querySelector('pre.excerpt')).not.toBeNull(); - const effects = within(lamplighter).getByRole('list', { name: /^Proposed effects/ }); - await user.click(within(effects).getByRole('button', { name: /^The hit die/ })); - const region = await within(lamplighter).findByRole('region', { name: /^The hit die/ }); - expect(within(region).getByText(/^Lines \d+–\d+$/)).toBeTruthy(); - expect(region.querySelector('mark')!.textContent!.length).toBeGreaterThan(0); - expect(lamplighter.querySelector('pre.excerpt')).toBeNull(); -}); - -it('imports a fixture Markdown class into a source with no PDF: pages only, candidates to review, and the stored page text opens in the app (D67)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Markdown Book', ['srd-5.2.1']); - const markdown = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/lab/placeholder-class.md')); - const job = await client.startMarkdownImportData(source.id, 'placeholder-class.md', markdown.toString('base64')); - expect(job.format).toBe('markdown'); - - render(); - await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); - const reader = () => within(screen.getByRole('listitem', { name: 'E2E Markdown Book' })).getByRole('region', { name: 'Read the text of E2E Markdown Book' }); - // No PDF: the Markdown import is offered, the PDF reads are not. - expect(within(await screen.findByRole('listitem', { name: 'E2E Markdown Book' })).getByRole('button', { name: 'Import a Markdown file…' })).toBeTruthy(); - expect(within(reader()).queryByRole('button', { name: 'Read the whole document' })).toBeNull(); - - const review = await within(reader()).findByRole('button', { name: /^Review \d+ entr(y|ies) found$/ }, { timeout: 30000 }); - expect(Number(/\d+/.exec(review.textContent ?? '')?.[0])).toBeGreaterThan(0); - expect(within(reader()).getByText(/^Markdown file: completed, \d+ pages? read/)).toBeTruthy(); - expect(within(reader()).queryByRole('button', { name: 'Resume' })).toBeNull(); - - // The candidates list opens and holds a row for each candidate found (awaited: the list appears with the first reply). - await user.click(review); - const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Markdown Book' }); - await within(reader()).findByRole('region', { name: 'Entries found in E2E Markdown Book' }); - const rows = await waitFor(() => within(within(panel()).getByRole('list', { name: 'Entries found' })).getAllByRole('listitem')); - expect(rows.length).toBeGreaterThan(0); - expect(within(rows[0]!).getByRole('button')).toBeTruthy(); - - // The read text is searchable, and "Open page" shows what was stored, since there is no PDF to open. - await user.type(within(reader()).getByRole('textbox', { name: 'Search the text of E2E Markdown Book' }), 'Placeholder Class'); - await user.click(within(reader()).getByRole('button', { name: 'Search' })); - const results = await within(reader()).findByRole('list', { name: 'Search results' }); - await user.click(within(results).getAllByRole('button', { name: /^Open page \d+$/ })[0]!); - const stored = await within(reader()).findByRole('region', { name: /^Stored text of page \d+ of E2E Markdown Book$/ }); - expect(stored.textContent).toContain('Placeholder Class'); - expect(await client.attachment(source.id)).toBeUndefined(); // import pages only: nothing was attached -}); - -it('accepts two fixture candidates in bulk, publishes both through the studio panel, and the builder offers them (item 9, D33)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Bulk Book', ['srd-5.2.1']); - const book = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-import.pdf')); - await client.attachPdfData(source.id, 'fixture-import.pdf', book.toString('base64')); - - render(); - await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); - const reader = () => within(screen.getByRole('listitem', { name: 'E2E Bulk Book' })).getByRole('region', { name: 'Read the text of E2E Bulk Book' }); - await user.click(within(await screen.findByRole('listitem', { name: 'E2E Bulk Book' })).getByRole('button', { name: 'Read the whole document' })); - await user.click(await within(reader()).findByRole('button', { name: 'Review 19 entries found' }, { timeout: 30000 })); - const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Bulk Book' }); - await within(reader()).findByRole('region', { name: 'Entries found in E2E Bulk Book' }); - await waitFor(() => expect(within(within(panel()).getByRole('list', { name: 'Entries found' })).getAllByRole('listitem')).toHaveLength(19)); - - // Nothing is selected yet: the bulk buttons are held with their reason. - const bulk = within(panel()).getByRole('button', { name: 'Keep selected, with their rules' }); - expect(bulk.getAttribute('aria-disabled')).toBe('true'); - await user.click(within(panel()).getByRole('checkbox', { name: 'Select Fixture Ember Lance' })); - await user.click(within(panel()).getByRole('checkbox', { name: 'Select Fixture Keen Watcher' })); - expect(within(panel()).getByText('2 selected', { selector: '[aria-live="polite"]' })).toBeTruthy(); - await user.click(bulk); - await waitFor(() => expect(appStatus().textContent).toMatch(/^Kept 2\./)); - const drafts = (await client.contentBySource(source.id)).filter((e) => e.latest.status === 'draft').map((e) => e.name).sort(); - expect(drafts).toEqual(['Fixture Ember Lance', 'Fixture Keen Watcher']); - - await user.click(screen.getByRole('button', { name: 'Homebrew' })); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Bulk Book/ })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Bulk Book/ })); - await user.click(await screen.findByRole('button', { name: 'Make all drafts in this source available to characters…' })); - const region = screen.getByRole('region', { name: 'Make drafts of E2E Bulk Book available to characters' }); - await waitFor(() => expect(document.activeElement).toBe(within(region).getByRole('heading', { name: 'Make drafts of E2E Bulk Book available to characters' }))); - const publish = await within(region).findByRole('button', { name: 'Make 2 drafts available to characters' }); - await waitFor(() => expect(publish.getAttribute('aria-disabled')).toBeNull()); - await user.click(publish); - - const result = await within(region).findByText('Made 2 drafts available to characters.'); - await waitFor(() => expect(document.activeElement).toBe(result)); // an effect moves focus to the result, so it can land after the text - expect((await client.contentBySource(source.id)).map((e) => e.latest.status)).toEqual(['published', 'published']); - // A second press would find nothing pending: the button is gone with the drafts. - await waitFor(() => expect(screen.queryByRole('button', { name: 'Make all drafts in this source available to characters…' })).toBeNull()); - expect((await client.listContent('srd-5.2.1')).some((o) => o.name === 'Fixture Ember Lance')).toBe(true); -}); - -it('adds the wizard list to a fixture spell candidate in bulk, accepts and publishes it, and the builder offers it to a wizard (item 10)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Lists Book', ['srd-5.2.1']); - const book = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-import.pdf')); - await client.attachPdfData(source.id, 'fixture-import.pdf', book.toString('base64')); - - render(); - await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); - const reader = () => within(screen.getByRole('listitem', { name: 'E2E Lists Book' })).getByRole('region', { name: 'Read the text of E2E Lists Book' }); - await user.click(within(await screen.findByRole('listitem', { name: 'E2E Lists Book' })).getByRole('button', { name: 'Read the whole document' })); - await user.click(await within(reader()).findByRole('button', { name: 'Review 19 entries found' }, { timeout: 30000 })); - const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Lists Book' }); - await within(reader()).findByRole('region', { name: 'Entries found in E2E Lists Book' }); - await waitFor(() => expect(within(within(panel()).getByRole('list', { name: 'Entries found' })).getAllByRole('listitem')).toHaveLength(19)); - - // The fixture spell is level 2, which a level 1 wizard has no slot for; the reviewer lowers it to level 1 first (setup, through the API). - const [job] = await client.listImports(source.id); - const ember = (await client.candidates(job!.id, { kind: 'spell' })).items.find((c) => c.candidate.proposedName === 'Fixture Ember Lance')!; - const effects = ember.candidate.proposedEffects.map((e) => (e.type === 'spell' ? { ...e, level: 1 } : e)); - await client.editCandidate(ember.id, { effects, expected: ember.etag }); - - // Nothing is ticked: the list button is held with its reason. - const open = within(panel()).getByRole('button', { name: 'Add to a spell list…' }); - expect(open.getAttribute('aria-disabled')).toBe('true'); - await user.click(within(panel()).getByRole('checkbox', { name: 'Select Fixture Ember Lance' })); - await user.click(within(panel()).getByRole('button', { name: 'Add 1 spell to a spell list…' })); - const key = within(panel()).getByRole('combobox', { name: 'Spell list key' }); - await waitFor(() => expect(document.activeElement).toBe(key)); - await user.type(key, ' Wizard'); - expect(within(panel()).getByText('Saved as: wizard')).toBeTruthy(); - await user.click(within(panel()).getByRole('button', { name: 'Add 1 spell to this list' })); - await waitFor(() => expect(appStatus().textContent).toMatch(/^Added the spell list wizard to 1 spell/)); - const stored = (await client.candidates(job!.id, { kind: 'spell' })).items.find((c) => c.id === ember.id)!; - const lists = (stored.edited ?? stored.candidate).proposedEffects.flatMap((e) => (e.type === 'spell' ? (e.lists as string[]) : [])); - expect(lists).toContain('wizard'); - - // Keep it as a draft (the bulk button), then publish through the studio panel. - const row = within(panel()).getByRole('checkbox', { name: 'Select Fixture Ember Lance' }); - if (!row.checked) await user.click(row); - const accept = within(panel()).getByRole('button', { name: 'Keep selected, with their rules' }); - await waitFor(() => expect(accept.getAttribute('aria-disabled')).toBeNull()); - await user.click(accept); - await waitFor(() => expect(appStatus().textContent).toMatch(/^Kept 1\./)); - - await user.click(screen.getByRole('button', { name: 'Homebrew' })); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Lists Book/ })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Lists Book/ })); - await user.click(await screen.findByRole('button', { name: 'Make all drafts in this source available to characters…' })); - const region = screen.getByRole('region', { name: 'Make drafts of E2E Lists Book available to characters' }); - const publish = await within(region).findByRole('button', { name: 'Make 1 draft available to characters' }); - await waitFor(() => expect(publish.getAttribute('aria-disabled')).toBeNull()); - await user.click(publish); - await within(region).findByText('Made 1 draft available to characters.'); - - // The published spell is on the wizard list, so the builder offers it to a wizard. - const keys = await client.spellListKeys(); - expect(keys.find((k) => k.key === 'wizard')!.spells).toBeGreaterThan(0); - await goHome(user); - await createCharacter(user, { name: 'E2E Listed Wizard', family: 'srd-5.2.1', cls: /^Wizard/ }); - const picker = await screen.findByRole('group', { name: /^Spellcasting spells/ }); // the SRD wizard's rule is named "Spellcasting" - expect(within(picker).getByRole('checkbox', { name: /^Fixture Ember Lance/ })).toBeTruthy(); -}); - -/** Opens the studio on the named homebrew source (item 12 flows). */ -async function openStudioOn(user: ReturnType, title: string) { - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: new RegExp(`^${title}`) })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: new RegExp(`^${title}`) })); - await screen.findByRole('heading', { name: `Content in ${title}` }); -} - -const newestOf = async (sourceId: string, name: string) => (await client.contentBySource(sourceId)).find((e) => e.name === name)?.latest; - -it('authors a species with a Strength increase and a skill in the studio, publishes it, and the builder offers it (item 12)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Folk Book', ['srd-5.1']); - await openStudioOn(user, 'E2E Folk Book'); - - await user.click(screen.getByRole('button', { name: 'New species' })); - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Folk'); - await user.type(within(editor()).getByRole('textbox', { name: 'Strength' }), '2'); - await user.click(within(editor()).getByRole('checkbox', { name: 'Athletics' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Speed (feet)' }), '25'); // items 12, 24 - await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); - await waitFor(async () => expect((await newestOf(source.id, 'E2E Folk'))?.status).toBe('published')); - // The speed is a content v10 replace modifier, so publishing it writes a v10 revision. - const published = (await newestOf(source.id, 'E2E Folk'))!; - expect(published.effects.filter((e) => e.type === 'modifier' && e.target === 'speed')).toMatchObject([{ operation: 'replace', value: '25' }]); - expect(published.schemaVersion).toBe(10); - - await goHome(user); - await createCharacter(user, { name: 'E2E Folk Child', family: 'srd-5.1', species: /^E2E Folk/ }); - expect(await screen.findByRole('heading', { name: /^Choices/ })).toBeTruthy(); -}); - -it('authors a newer-rules background with three ability increases: the option features are drafts, Publish all makes them live, and the builder offers it (item 12)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Wanderer Book', ['srd-5.2.1']); - await openStudioOn(user, 'E2E Wanderer Book'); - - await user.click(screen.getByRole('button', { name: 'New background' })); - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Wanderer'); - for (const name of ['Strength', 'Dexterity', 'Constitution']) await user.click(within(editor()).getByRole('checkbox', { name })); - await user.click(within(editor()).getByRole('button', { name: 'Save draft' })); - await waitFor(async () => expect((await newestOf(source.id, 'E2E Wanderer'))?.status).toBe('draft')); - const entries = await client.contentBySource(source.id); - expect(entries.filter((e) => e.kind === 'feature' && e.name.startsWith('E2E Wanderer Ability Scores'))).toHaveLength(7); - - // R61: Publish is not held; a linked note says the entry points at drafts and that Publish all publishes them together. - const publish = await within(editor()).findByRole('button', { name: 'Make available to characters' }); - await waitFor(() => expect(publish.getAttribute('aria-disabled')).toBeNull()); - const note = document.getElementById('editor-pins'); - expect(note?.textContent).toBe('Points at 7 drafts not yet available to characters. Making all drafts available makes them available together and re-points this entry.'); - expect((publish.getAttribute('aria-describedby') ?? '').split(' ')).toContain('editor-pins'); - await user.click(await screen.findByRole('button', { name: 'Make all drafts in this source available to characters…' })); - const region = screen.getByRole('region', { name: 'Make drafts of E2E Wanderer Book available to characters' }); - const publishAll = await within(region).findByRole('button', { name: 'Make 8 drafts available to characters' }); - await waitFor(() => expect(publishAll.getAttribute('aria-disabled')).toBeNull()); - await user.click(publishAll); - await within(region).findByText('Made 8 drafts available to characters.'); - expect((await newestOf(source.id, 'E2E Wanderer'))?.status).toBe('published'); - // The open editor showed the superseded draft: it closes with a status instead of saving over the published version. - await waitFor(() => expect(screen.queryByRole('region', { name: /^New |^Edit / })).toBeNull()); - - await goHome(user); - await createCharacter(user, { name: 'E2E Wanderer Child', family: 'srd-5.2.1', background: /^E2E Wanderer/ }); - expect(await screen.findByRole('heading', { name: /^Choices/ })).toBeTruthy(); -}); - -it('authors a cantrip on a new spell list in the studio, publishes it, and the list shows in the spell list keys (item 12)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Spark Book', ['srd-5.2.1']); - await openStudioOn(user, 'E2E Spark Book'); - - await user.click(screen.getByRole('button', { name: 'New spell' })); - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Spark'); - await user.selectOptions(within(editor()).getByRole('combobox', { name: 'Level' }), '0'); - await user.type(within(editor()).getByRole('combobox', { name: 'Add a spell list' }), 'E2E Spark List'); - expect(within(editor()).getByText('Saved as: e2e-spark-list')).toBeTruthy(); - await user.click(within(editor()).getByRole('button', { name: 'Add list' })); - await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); - await waitFor(async () => expect((await newestOf(source.id, 'E2E Spark'))?.status).toBe('published')); - - const keys = await client.spellListKeys(); - expect(keys.find((k) => k.key === 'e2e-spark-list')?.spells).toBe(1); -}); - -it('shows different allowed content for two campaign profiles, and records a reasoned exception', async () => { - const user = userEvent.setup(); - render(); - const campaignsButton = await screen.findByRole('button', { name: 'Campaigns' }); - await waitFor(() => expect(campaignsButton.disabled).toBe(false)); - await user.click(campaignsButton); - - async function createCampaign(name: string, sources: RegExp[]) { - await user.click(await screen.findByRole('button', { name: 'New campaign' })); - const form = screen.getByRole('form', { name: 'Campaign' }); - await user.type(within(form).getByRole('textbox', { name: 'Campaign name' }), name); - await user.click(within(form).getByRole('radio', { name: /2024 rules/ })); - for (const source of sources) await user.click(within(form).getByRole('checkbox', { name: source })); - await user.click(within(form).getByRole('button', { name: 'Save campaign' })); - await waitFor(() => expect(appStatus().textContent).toBe(`Saved the campaign ${name}.`)); - } - await createCampaign('E2E Strict', [/^System Reference Document 5\.2\.1/]); - await createCampaign('E2E Open', [/^System Reference Document 5\.2\.1/, /^TomeStack Fixtures: 2024 Family/]); - - // The campaign is chosen on the Rules step; the backgrounds it governs are on the Background step (D32), so this flow - // walks the steps by hand instead of through `createCharacter`. - await startNewCharacter(user); - await user.type(await screen.findByRole('textbox', { name: 'Name' }), 'E2E Campaigner'); - const courier = () => screen.getByRole('radio', { name: /^Fixture Courier/ }); - const courierOff = () => courier().getAttribute('aria-disabled') === 'true'; // inert, never natively disabled (2.4.3) - const soldier = () => screen.getAllByRole('radio', { name: /^Soldier/ }).find((r) => r.getAttribute('aria-disabled') !== 'true'); - const toBackground = async () => { - await user.click(screen.getByRole('button', { name: 'Next: class' })); - await user.click(screen.getByRole('button', { name: 'Next: ability scores' })); - await user.click(screen.getByRole('radio', { name: 'Enter by hand' })); // the default method needs all six scores assigned - for (const next of ['Next: species', 'Next: background']) await user.click(screen.getByRole('button', { name: next })); - }; - const toRules = async () => { - for (let i = 0; i < 4; i++) await user.click(screen.getByRole('button', { name: 'Back' })); - }; - - // Profile 1: SRD only. The fixture background is listed but not allowed; the SRD one is. - // The Campaign picker appears once the campaign list arrives, which can be after the name is typed. - await user.selectOptions(await screen.findByRole('combobox', { name: 'Campaign' }), 'E2E Strict (2024 rules)'); - await toBackground(); - await waitFor(() => expect(courierOff()).toBe(true)); - expect(courier().closest('label')!.textContent).toMatch(/not allowed in this campaign/); - expect(soldier()).toBeTruthy(); - - // Profile 2: SRD and the 2024 fixtures. The same background is allowed. - await toRules(); - await user.selectOptions(screen.getByRole('combobox', { name: 'Campaign' }), 'E2E Open (2024 rules)'); - await toBackground(); - await waitFor(() => expect(courierOff()).toBe(false)); - - // Back to profile 1, with a deliberate exception: a reason is required before outside content can be picked. - await toRules(); - await user.selectOptions(screen.getByRole('combobox', { name: 'Campaign' }), 'E2E Strict (2024 rules)'); - await toBackground(); - await waitFor(() => expect(courierOff()).toBe(true)); - const sources = screen.getByRole('group', { name: 'Campaign sources' }); - await user.click(within(sources).getByRole('checkbox', { name: 'Use content from outside the campaign' })); - expect(courierOff()).toBe(true); // no reason yet - await user.type(within(sources).getByRole('textbox', { name: /^Reason/ }), 'DM approved'); - await waitFor(() => expect(courierOff()).toBe(false)); - await user.click(courier()); - await user.click(screen.getByRole('button', { name: 'Next: gear' })); - await user.click(screen.getByRole('button', { name: 'Next: choices' })); - await user.click(await screen.findByRole('button', { name: 'Create and save' })); - - const sheet = await screen.findByRole('article', { name: 'E2E Campaigner' }); - expect(within(sheet).getByText('Campaign: E2E Strict', { selector: '.tag' })).toBeTruthy(); - const notes = within(sheet).getByRole('region', { name: 'Campaign: E2E Strict' }); - expect(notes.textContent).toMatch(/Fixture Courier.*used by exception: DM approved/); -}); - -it('keeps a resource linked to its recovery when the resource is renamed in the studio', async () => { - const user = userEvent.setup(); - await client.createHomebrewSource('E2E Renames', ['srd-5.2.1']); - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Renames/ })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Renames/ })); - await screen.findByRole('heading', { name: 'Content in E2E Renames' }); - - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - await user.click(screen.getByRole('button', { name: 'New feature' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Fury'); - await user.click(within(editor()).getByRole('button', { name: 'Add resource' })); - const name = within(within(editor()).getByRole('group', { name: /^Rule 1: Resource/ })).getByRole('textbox', { name: 'Resource name' }); - await user.type(name, 'Fury'); - await user.click(within(editor()).getByRole('button', { name: 'Add recovery' })); - // Renamed after the recovery points at it: the recovery must still restore this resource. - await user.type(name, ' points'); - await user.click(within(editor()).getByRole('button', { name: 'Check' })); - - const results = await within(editor()).findByRole('region', { name: 'Check results' }); - expect(results.textContent).not.toMatch(/does not define/); -}); - -it('finds a problem in a source with the debugger, shows its rule, and clears it in the editor (M5 slice 2)', async () => { - const user = userEvent.setup(); - await client.createHomebrewSource('E2E Debugger', ['srd-5.2.1']); - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Debugger/ })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Debugger/ })); - await screen.findByRole('heading', { name: 'Content in E2E Debugger' }); - - // A draft feature whose resource nothing spends or recovers. - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - await user.click(screen.getByRole('button', { name: 'New feature' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Dead Well'); - await user.click(within(editor()).getByRole('button', { name: 'Add resource' })); - await user.type(within(within(editor()).getByRole('group', { name: /^Rule 1: Resource/ })).getByRole('textbox', { name: 'Resource name' }), 'Echoes'); - await user.click(within(editor()).getByRole('button', { name: 'Save draft' })); - await expectStatus(/Saved a draft of E2E Dead Well/); - await user.click(within(editor()).getByRole('button', { name: 'Close editor' })); - - await user.click(await screen.findByRole('button', { name: 'Find problems in E2E Debugger' })); - const findings = await screen.findByRole('region', { name: 'Debugger findings for E2E Debugger' }); - expect(findings.textContent).toMatch(/Warning in E2E Dead Well: Resource 'resource-1' is never spent/); - - // "Show" opens the entry and moves focus to the rule the finding is about. - await user.click(within(findings).getByRole('button', { name: 'Show rule resource-1 of E2E Dead Well' })); - await screen.findByRole('heading', { name: 'Edit E2E Dead Well' }); - await waitFor(() => expect(document.activeElement).toBe(within(editor()).getByRole('group', { name: /^Rule 1: Resource/ }))); - - // With the entry already open, Show keeps its unsaved edits and moves focus again (review fix). - const description = within(editor()).getByRole('textbox', { name: /^Description/ }); - await user.type(description, 'Unsaved words'); - await user.click(within(screen.getByRole('region', { name: 'Debugger findings for E2E Debugger' })).getByRole('button', { name: 'Show rule resource-1 of E2E Dead Well' })); - await waitFor(() => expect(document.activeElement).toBe(within(editor()).getByRole('group', { name: /^Rule 1: Resource/ }))); - expect((within(editor()).getByRole('textbox', { name: /^Description/ }) as HTMLTextAreaElement).value).toBe('Unsaved words'); - - // A recovery fixes it; the editor's own debugger checks the unsaved revision. - await user.click(within(editor()).getByRole('button', { name: 'Add recovery' })); - await user.click(within(editor()).getByRole('button', { name: 'Find problems' })); - const own = await within(editor()).findByRole('region', { name: 'Debugger findings' }); - await waitFor(() => expect(own.textContent).toMatch(/The debugger found no problems/)); -}); - -it('tries a draft class at a chosen level on a blank character without saving anything (M5 slice 3)', async () => { - const user = userEvent.setup(); - await client.createHomebrewSource('E2E Sandbox', ['srd-5.2.1']); - const charactersBefore = (await client.listCharacters()).length; - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Sandbox/ })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Sandbox/ })); - await screen.findByRole('heading', { name: 'Content in E2E Sandbox' }); - - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - await user.click(screen.getByRole('button', { name: 'New class' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Trial Class'); - await user.selectOptions(within(editor()).getByRole('combobox', { name: 'Hit die' }), 'd10'); - - const sandbox = within(editor()).getByRole('region', { name: 'Try it' }); - await user.type(within(sandbox).getByRole('textbox', { name: /^Level in this class/ }), '3'); - await user.click(within(sandbox).getByRole('button', { name: 'Try it' })); - const results = await within(sandbox).findByRole('region', { name: 'Try it results' }); - expect(results.textContent).toMatch(/Unsaved blank character at total level 3/); - expect(results.textContent).toMatch(/Hit point maximum: 22/); // d10: 10, then 6 per level, Con +0 - expect(results.textContent).not.toMatch(/Spell save DC/); // not a caster - - // An edit hides the result until it is tried again, and nothing was saved. - await user.selectOptions(within(editor()).getByRole('combobox', { name: 'Hit die' }), 'd6'); - expect(within(sandbox).queryByRole('region', { name: 'Try it results' })).toBeNull(); - expect((await client.listCharacters()).length).toBe(charactersBefore); - expect(await client.contentBySource((await client.listSources()).find((s) => s.title === 'E2E Sandbox')!.id)).toEqual([]); -}); - -it('compares the published revision with the unsaved one by rules, text and on a character copy (M5 slice 4)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Diffs', ['srd-5.2.1']); - const draft = await client.saveDraft({ - contentId: crypto.randomUUID(), - revisionId: '00000000-0000-0000-0000-000000000000', - kind: 'feat', - name: 'E2E Diff Feat', - rulesFamilies: ['srd-5.2.1'], - provenance: { sourceId: source.id }, - status: 'draft', - summary: 'Old line', - effects: [{ type: 'modifier', id: 'quick', operation: 'bonus', target: 'initiative', value: '1' }], - }); - const published = (await client.publish(draft)).published; - const hero = await client.createCharacter({ name: 'E2E Diff Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [published] }); - - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Diffs/ })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Diffs/ })); - await user.click(await screen.findByRole('button', { name: 'Edit E2E Diff Feat' })); - - const editor = () => screen.getByRole('region', { name: /^Edit / }); - const description = within(editor()).getByRole('textbox', { name: /^Description/ }); - await user.clear(description); - await user.type(description, 'New line'); - const value = within(within(editor()).getByRole('group', { name: /^Rule 1: Modifier/ })).getByRole('textbox', { name: /^Value/ }); - await user.clear(value); - await user.type(value, '3'); - - const panel = within(editor()).getByRole('region', { name: 'Compare versions' }); - await user.click(await within(panel).findByRole('checkbox', { name: 'E2E Diff Hero' })); // the character list loads after the panel opens - await user.click(within(panel).getByRole('button', { name: 'Compare' })); - const results = await within(panel).findByRole('region', { name: 'Comparison results' }); - expect(within(results).getByRole('table', { name: 'Rule changes' }).textContent).toMatch(/quick.*changed/); - expect(results.textContent).toMatch(/removed: Old line/); - expect(results.textContent).toMatch(/added: New line/); - const run = within(results).getByRole('table', { name: 'Calculated values that change for E2E Diff Hero' }); - expect(run.textContent).toMatch(/Initiative\s*1\s*3/); - - // Nothing was applied: the character still uses the published revision. - expect((await client.getCharacter(hero.character.id)).sheet.fields.find((f) => f.field === 'initiative')?.value).toBe(1); - - // A new entry has nothing stored to compare with until its first save; then the saved draft is "From" (review fix). - await user.click(within(editor()).getByRole('button', { name: 'Close editor' })); - await user.click(screen.getByRole('button', { name: 'New feat' })); - const fresh = () => screen.getByRole('region', { name: /^New / }); - expect(within(fresh()).queryByRole('region', { name: 'Compare versions' })).toBeNull(); - await user.type(within(fresh()).getByRole('textbox', { name: 'Name' }), 'E2E Fresh Feat'); - await user.click(within(fresh()).getByRole('button', { name: 'Save draft' })); - await expectStatus(/Saved a draft of E2E Fresh Feat/); - const freshPanel = await within(fresh()).findByRole('region', { name: 'Compare versions' }); - await user.click(within(freshPanel).getByRole('button', { name: 'Compare' })); - expect((await within(freshPanel).findByRole('region', { name: 'Comparison results' })).textContent).toMatch(/The rules are the same/); -}); - -it('shows an entry\'s relationships as a keyboard tree and jumps from a node to its rule (M5 slice 5)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Trees', ['srd-5.2.1']); - const draft = await client.saveDraft({ - contentId: crypto.randomUUID(), - revisionId: '00000000-0000-0000-0000-000000000000', - kind: 'feature', - name: 'E2E Tree Feature', - rulesFamilies: ['srd-5.2.1'], - provenance: { sourceId: source.id }, - status: 'draft', - effects: [ - { type: 'resource', id: 'embers', resourceId: 'embers', label: 'Embers', maximum: 'PB' }, - { type: 'roll', id: 'flare', rollId: 'flare', label: 'Flare', dice: '1d6', resourceId: 'embers', timing: 'onRoll', automation: 'assisted' }, - { type: 'recovery', id: 'rekindle', resourceId: 'embers', on: 'longRest', amount: 'all', timing: 'onLongRest' }, - ], - }); - await client.publish(draft); - - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Trees/ })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Trees/ })); - await user.click(await screen.findByRole('button', { name: 'Edit E2E Tree Feature' })); - const editor = () => screen.getByRole('region', { name: /^Edit / }); - - await user.click(within(editor()).getByRole('button', { name: 'Show relationships' })); - const tree = await within(editor()).findByRole('tree', { name: 'Relationships of E2E Tree Feature' }); - const root = within(tree).getAllByRole('treeitem')[0]!; - expect(root.getAttribute('aria-level')).toBe('1'); - expect(root.getAttribute('aria-expanded')).toBe('true'); - expect(root.tabIndex).toBe(0); - - // Keyboard only, from the button: Tab enters the tree at its one tab stop (the root). - await user.tab(); - expect(document.activeElement).toBe(root); - await user.keyboard('{ArrowDown}'); - const resource = within(tree).getByRole('treeitem', { name: 'Resource: Embers (uses PB)' }); // named by its own label only - expect(document.activeElement).toBe(resource); - expect([resource.getAttribute('aria-level'), resource.getAttribute('aria-posinset'), resource.getAttribute('aria-setsize')]).toEqual(['2', '1', '1']); - expect(resource.getAttribute('aria-expanded')).toBe('false'); - // Space opens and closes; Right opens, then goes to the first child. - await user.keyboard(' '); - expect(resource.getAttribute('aria-expanded')).toBe('true'); - await user.keyboard(' '); - expect(resource.getAttribute('aria-expanded')).toBe('false'); - await user.keyboard('{ArrowRight}'); - expect(resource.getAttribute('aria-expanded')).toBe('true'); - await user.keyboard('{ArrowRight}'); - const roll = within(resource).getByRole('treeitem', { name: 'Roll: Flare (1d6), spends it' }); - expect((document.activeElement as HTMLElement).id).toBe(roll.id); - expect([roll.getAttribute('aria-level'), roll.getAttribute('aria-posinset'), roll.getAttribute('aria-setsize')]).toEqual(['3', '1', '2']); - // End goes to the last visible item (the recovery), Home to the root, Up and Down between items. - await user.keyboard('{End}'); - expect(document.activeElement).toBe(within(resource).getByRole('treeitem', { name: 'Recovery on a long rest: all' })); - await user.keyboard('{Home}'); - expect(document.activeElement).toBe(root); - await user.keyboard('{ArrowDown}{ArrowDown}'); - expect((document.activeElement as HTMLElement).id).toBe(roll.id); - await user.keyboard('{ArrowUp}'); - expect(document.activeElement).toBe(resource); - await user.keyboard('{ArrowDown}'); - // Enter shows the rule in the editor; Left from a child goes back to its parent. - await user.keyboard('{Enter}'); - await waitFor(() => expect(document.activeElement).toBe(within(editor()).getByRole('group', { name: /^Rule 2: Roll or action/ }))); - await user.click(within(tree).getByRole('treeitem', { name: 'Roll: Flare (1d6), spends it' })); - await user.keyboard('{ArrowLeft}'); - expect(document.activeElement).toBe(resource); -}); - -it('starts homebrew from a template as an unsaved draft, publishes a stance, and a skeleton waits for its slots (M5 slice 6)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Templates', ['srd-5.2.1']); - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Templates/ })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Templates/ })); - await screen.findByRole('heading', { name: 'Content in E2E Templates' }); - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - - // The stance: a toggle that spends a use, and a bonus only while it is on. Nothing is stored until it is saved. - await user.selectOptions(screen.getByRole('combobox', { name: 'Start from a template' }), 'A stance you switch on and off'); - await user.click(screen.getByRole('button', { name: 'Use template' })); - expect(await client.contentBySource(source.id)).toEqual([]); - expect(within(editor()).getByRole('group', { name: /^Rule 3: Toggle/ })).toBeTruthy(); - expect((within(within(editor()).getByRole('group', { name: /^Rule 4: Modifier/ })).getByRole('combobox', { name: 'Applies' }) as HTMLSelectElement).value).toBe('stance'); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Stance'); - await user.click(within(editor()).getByRole('button', { name: 'Check' })); - expect((await within(editor()).findByRole('region', { name: 'Check results' })).textContent).toMatch(/No problems found/); - await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); - await expectStatus(/Made E2E Stance available to characters/); - - // The class skeleton: its hit die, saves and subclass choice are set; its improvement slots block publishing until filled. - await user.selectOptions(screen.getByRole('combobox', { name: 'Start from a template' }), 'A class skeleton'); - await user.click(screen.getByRole('button', { name: 'Use template' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Skeleton Class'); - expect((within(editor()).getByRole('combobox', { name: 'Hit die' }) as HTMLSelectElement).value).toBe('8'); - await user.click(within(editor()).getByRole('button', { name: 'Check' })); - const results = await within(editor()).findByRole('region', { name: 'Check results' }); - expect(results.textContent).toMatch(/improvement-4' grants content but names none/); - await user.click(within(editor()).getByRole('button', { name: 'Save draft' })); - await expectStatus(/Saved a draft of E2E Skeleton Class/); - expect((await client.contentBySource(source.id)).find((e) => e.name === 'E2E Skeleton Class')?.latest.status).toBe('draft'); - - // Every template passes the server's checks; only the skeletons' empty slots are errors (review fix). - for (const t of templates) { - const draft = { ...fromTemplate(t.id, source.id, ['srd-5.2.1'], crypto.randomUUID()), name: `E2E ${t.label}`, revisionId: crypto.randomUUID() }; - expect(draft.summary).toBeUndefined(); // a template never writes the description shown on the sheet - const report = await client.validateRevision(draft); - expect(report.errors.filter((e) => e.code !== 'validate.grant-content-missing')).toEqual([]); - expect(report.errors.length > 0).toBe(t.id === 'subclass-skeleton' || t.id === 'class-skeleton'); - } - - // Removing the stance's toggle turns its bonus back to always on, so nothing names a missing toggle (review fix). - await user.selectOptions(screen.getByRole('combobox', { name: 'Start from a template' }), 'A stance you switch on and off'); - await user.click(screen.getByRole('button', { name: 'Use template' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Loose Stance'); - await user.click(within(within(editor()).getByRole('group', { name: /^Rule 3: Toggle/ })).getByRole('button', { name: 'Remove rule 3' })); - // D43 S4: the source's other entries (E2E Stance above) offer their toggles, so the choice stays, and it reads "Always". - expect((within(editor()).getByRole('combobox', { name: 'Applies' }) as HTMLSelectElement).value).toBe(''); - await user.click(within(editor()).getByRole('button', { name: 'Check' })); - await waitFor(() => expect(within(editor()).getByRole('region', { name: 'Check results' }).textContent).toMatch(/No problems found/)); -}); - -it('shows design feedback only once it is switched on, as hints that do not block (M5 slice 7)', async () => { - const user = userEvent.setup(); - await client.createHomebrewSource('E2E Feedback', ['srd-5.2.1']); - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Feedback/ })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Feedback/ })); - await screen.findByRole('heading', { name: 'Content in E2E Feedback' }); - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - - // Off by default: the editor has no feedback section. - const toggle = screen.getByRole('checkbox', { name: 'Show design feedback' }); - expect((toggle as HTMLInputElement).checked).toBe(false); - await user.click(screen.getByRole('button', { name: 'New class' })); - expect(within(editor()).queryByRole('region', { name: 'Design feedback' })).toBeNull(); - - try { - await user.click(toggle); - expect(localStorage.getItem('tomestack.designFeedback')).toBe('on'); - const section = within(editor()).getByRole('region', { name: 'Design feedback' }); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Hinted Class'); - await user.click(within(section).getByRole('button', { name: 'Get design hints' })); - const hints = await within(section).findByRole('region', { name: 'Design hints' }); - expect(hints.textContent).toMatch(/Class level\(s\) .* give no feature or choice, although every bundled SRD class gives one there/); - - // The choice is remembered for next time (this machine only): a fresh studio starts with it on. - cleanup(); - render(); - const again = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(again.disabled).toBe(false)); - await user.click(again); - expect((await screen.findByRole('checkbox', { name: 'Show design feedback' })).checked).toBe(true); - - // Off again: the choice is forgotten. - await user.click(screen.getByRole('checkbox', { name: 'Show design feedback' })); - expect(localStorage.getItem('tomestack.designFeedback')).toBeNull(); - } finally { - localStorage.removeItem('tomestack.designFeedback'); // later flows start from the default, off - } -}); - -it('takes a snapshot of a character, previews the restore, restores it and keeps an undo snapshot (M5 slice 8)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Snapshots', ['srd-5.2.1']); - const feat = ( - await client.publish( - await client.saveDraft({ - contentId: crypto.randomUUID(), - revisionId: '00000000-0000-0000-0000-000000000000', - kind: 'feat', - name: 'E2E Snapshot Feat', - rulesFamilies: ['srd-5.2.1'], - provenance: { sourceId: source.id }, - status: 'draft', - effects: [{ type: 'modifier', id: 'quick', operation: 'bonus', target: 'initiative', value: '3' }], - }), - ) - ).published; - const created = (await client.createCharacter({ name: 'E2E Snapshot Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [feat] })).character; - const hero = (await client.saveCharacter({ ...created, currency: { cp: 0, sp: 12, ep: 0, gp: 3, pp: 0 } })).character; // D21: coins the restore puts back - - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Snapshot Hero/ })); - await openMore(user, await screen.findByRole('article', { name: 'E2E Snapshot Hero' }), 'Snapshots'); - const panel = () => screen.getByRole('region', { name: 'Snapshots' }); - await user.type(await within(await screen.findByRole('region', { name: 'Snapshots' })).findByRole('textbox', { name: /^Snapshot name/ }), 'E2E with the feat'); - await user.click(within(panel()).getByRole('button', { name: 'Take snapshot' })); - await expectStatus(/Took a snapshot of E2E Snapshot Hero: E2E with the feat/); - - // The character changes: the feat goes, and the coins change. - await client.saveCharacter({ ...(await client.getCharacter(hero.id)).character, pins: [], currency: { cp: 0, sp: 0, ep: 0, gp: 40, pp: 0 } }); - // Leave the character on a real tab (not the Play default), so the reopen below proves the tab is remembered. - await openTab(user, await screen.findByRole('article', { name: 'E2E Snapshot Hero' }), 'Features'); - cleanup(); - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Snapshot Hero/ })); - - // ADR-014: the sheet reopens on the tab used last for this character. (The retired "manage" id falling back to Play is covered - // by sheetTab.test.ts and CharacterSheet.test.tsx.) The Snapshots panel is not kept open, so it is opened again from More. - const reopened = await screen.findByRole('article', { name: 'E2E Snapshot Hero' }); - expect(within(reopened).getByRole('tab', { name: 'Features' }).getAttribute('aria-selected')).toBe('true'); - await openMore(user, reopened, 'Snapshots'); - await user.click(await within(await screen.findByRole('region', { name: 'Snapshots' })).findByRole('button', { name: 'Restore E2E with the feat…' })); - const preview = await within(panel()).findByRole('region', { name: 'Restore E2E with the feat?' }); - await waitFor(() => expect(document.activeElement).toBe(within(preview).getByRole('heading', { name: 'Restore E2E with the feat?' }))); - expect(within(preview).getByRole('table', { name: 'Calculated values that change' }).textContent).toMatch(/Initiative\s*0\s*3/); - // D22: the restore preview names the coin change, through the service's real field names. - expect(preview.textContent).toMatch(/Coins go back to 3 gp, 12 sp \(now 40 gp\)\./); - expect((await client.getCharacter(hero.id)).character.pins).toEqual([]); // the preview changed nothing - - // "Keep the current state" closes the preview and returns focus to the button that opened it (accessibility item 23). - await user.click(within(preview).getByRole('button', { name: 'Keep the current state' })); - const reopen = within(panel()).getByRole('button', { name: 'Restore E2E with the feat…' }); - await waitFor(() => expect(document.activeElement).toBe(reopen)); - expect(within(panel()).queryByRole('region', { name: 'Restore E2E with the feat?' })).toBeNull(); - expect((await client.getCharacter(hero.id)).character.pins).toEqual([]); - - await user.click(reopen); - const again = await within(panel()).findByRole('region', { name: 'Restore E2E with the feat?' }); - await user.click(within(again).getByRole('button', { name: 'Restore' })); - await expectStatus(/Restored the snapshot/); - expect((await client.getCharacter(hero.id)).character.pins).toEqual([feat]); - expect((await client.getCharacter(hero.id)).character.currency).toEqual({ cp: 0, sp: 12, ep: 0, gp: 3, pp: 0 }); - expect(await within(panel()).findByRole('button', { name: /^Restore Before restoring/ })).toBeTruthy(); // the undo snapshot -}); - -it('drops picks that do not fit when the rules family changes, in the builder and in a campaign', async () => { - const user = userEvent.setup(); - render(); - - // Builder: an SRD 5.1 species, then SRD 5.2.1. The 5.1 pick is cleared and no longer listed. - await startNewCharacter(user); - await user.type(await screen.findByRole('textbox', { name: 'Name' }), 'E2E Switcher'); // the name is required to leave the Rules step - await user.click(screen.getByRole('radio', { name: /2014 rules/ })); - await user.click(screen.getByRole('button', { name: 'Next: class' })); - await user.click(screen.getByRole('button', { name: 'Next: ability scores' })); - await user.click(screen.getByRole('radio', { name: 'Enter by hand' })); - await user.click(screen.getByRole('button', { name: 'Next: species' })); - const species = screen.getByRole('group', { name: 'Species' }); - const halfOrc = () => within(species).getByRole('radio', { name: /^Half-Orc/ }); - await waitFor(() => expect(halfOrc().getAttribute('aria-disabled')).toBeNull()); - await user.click(halfOrc()); - expect(halfOrc().checked).toBe(true); - for (let i = 0; i < 3; i++) await user.click(screen.getByRole('button', { name: 'Back' })); // species, scores, class, rules - await user.click(screen.getByRole('radio', { name: /2024 rules/ })); - await user.click(screen.getByRole('button', { name: 'Next: class' })); - await user.click(screen.getByRole('button', { name: 'Next: ability scores' })); - await user.click(screen.getByRole('button', { name: 'Next: species' })); - // D31: the 5.1 species leaves the list altogether, and the pick is cleared. - await waitFor(() => expect(within(screen.getByRole('group', { name: 'Species' })).queryByRole('radio', { name: /^Half-Orc/ })).toBeNull()); - expect(within(screen.getByRole('group', { name: 'Species' })).getByRole('radio', { name: 'None' }).checked).toBe(true); - await user.click(screen.getByRole('button', { name: 'Cancel' })); - await user.click(await screen.findByRole('button', { name: 'Discard' })); // the rules family was changed: Cancel asks first - - // Campaign: an SRD 5.1 source, then SRD 5.2.1. The hidden 5.1 source is not saved with the campaign. - await user.click(screen.getByRole('button', { name: 'Campaigns' })); - await user.click(await screen.findByRole('button', { name: 'New campaign' })); - const form = screen.getByRole('form', { name: 'Campaign' }); - await user.type(within(form).getByRole('textbox', { name: 'Campaign name' }), 'E2E Switched'); - await user.click(within(form).getByRole('radio', { name: /2014 rules/ })); - await user.click(within(form).getByRole('checkbox', { name: /^System Reference Document 5\.1/ })); - await user.click(within(form).getByRole('radio', { name: /2024 rules/ })); - await user.click(within(form).getByRole('button', { name: 'Save campaign' })); - await waitFor(() => expect(appStatus().textContent).toBe('Saved the campaign E2E Switched.')); - const saved = screen.getAllByRole('listitem').find((li) => li.textContent?.startsWith('E2E Switched'))!; - expect(saved.textContent).toMatch(/0 allowed sources/); -}); - -it('reaches the primary actions by keyboard alone', async () => { - const user = userEvent.setup(); - render(); - // user-event walks a radio group with CSS.escape, which jsdom lacks; the group name needs no escaping. - const w = window as unknown as { CSS?: { escape?: (s: string) => string } }; - w.CSS ??= {}; - w.CSS.escape ??= (s: string) => s; - const addCharacter = await screen.findByRole('button', { name: '+ Add a character' }); - - await user.tab(); - expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Hide sidebar' })); // the shell's first header control - // Owner (2026-10-12): no second close control inside the sidebar; the header's "Hide sidebar" is the only one. - expect(screen.queryByRole('button', { name: 'Close sidebar' })).toBeNull(); - await user.tab(); - expect(document.activeElement).toBe(screen.getByRole('button', { name: 'TomeStack, your characters' })); // the way home - // Spec 3.1: "+ Add a character" heads the sidebar, ahead of the character list. - await user.tab(); - expect(document.activeElement).toBe(addCharacter); - await user.keyboard('{Enter}'); - expect(await screen.findByRole('heading', { level: 1, name: 'Add a character' })).toBeTruthy(); - - // The chooser's radio group is a single Tab stop. Nothing is chosen yet, so Continue does nothing until a radio is ticked. - const make = await screen.findByRole('radio', { name: 'Make a new one' }); - await waitFor(() => expect(make.disabled).toBe(false)); - for (let i = 0; i < 200 && document.activeElement !== make; i++) await user.tab(); - expect(document.activeElement).toBe(make); - await user.keyboard(' '); - expect(make.checked).toBe(true); - await user.tab(); - expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Continue' })); - await user.keyboard('{Enter}'); - - expect(await screen.findByRole('heading', { name: 'New character' })).toBeTruthy(); - await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('textbox', { name: 'Name' }))); -}); - -it('equips a weapon: the attack uses finesse and proficiency, rolls, and actions are grouped', async () => { - // SPEC C-02, C-04 with the original fixtures "Fixture Duelist" (simple and martial weapons) and "Fixture Needle" (finesse). - const user = userEvent.setup(); - render(); - await createCharacter(user, { name: 'E2E Blade', scores: { Strength: 14, Dexterity: 16 }, cls: /^Fixture Duelist/ }); - await pick(user, /^Fixture Duelist: choose 2/, /^Duelist Skill: Acrobatics/); - await pick(user, /^Fixture Duelist: choose 2/, /^Duelist Skill: Insight/); - await user.click(await screen.findByRole('button', { name: 'Create and save' })); - const blade = await screen.findByRole('article', { name: 'E2E Blade' }); - - await openTab(user, blade, 'Gear'); - const equipment = () => screen.getByRole('region', { name: 'Equipment' }); - await waitFor(() => expect(within(equipment()).getByRole('option', { name: /^Fixture Needle/ })).toBeTruthy()); - await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^Fixture Needle/ })); - await user.click(within(equipment()).getByRole('button', { name: 'Add' })); - await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip Fixture Needle' })); - - // Dex +3 (finesse beats Str +2) + PB 2 = +5; damage 1d4 + 3. - await openTab(user, blade, 'Play'); - const actions = () => screen.getByRole('region', { name: 'Attacks and actions' }); - await waitFor(() => expect(within(actions()).getByText(/\+5 to hit, 1d4\+3 piercing/)).toBeTruthy()); - await user.click(within(actions()).getByRole('button', { name: 'Roll Fixture Needle attack' })); - const lastRoll = screen.getByRole('status', { name: 'Last roll' }); - await waitFor(() => expect(lastRoll.textContent).toMatch(/Fixture Needle attack: \d+ \(1d20\)/)); - expect(lastRoll.textContent).toMatch(/Fixture Needle to hit \+5/); - const reactions = within(actions()).getByRole('region', { name: 'Reactions' }); - expect(within(reactions).getByRole('button', { name: 'Roll Riposte damage (1d6)' })).toBeTruthy(); -}); - -it('adds an attack of your own on Inventory, rolls it on Play with advantage, and the roll shows in Last roll (item 18)', async () => { - const user = userEvent.setup(); - render(); - await createCharacter(user, { name: 'E2E Sling', scores: {}, cls: /^Fixture Duelist/ }); - await pick(user, /^Fixture Duelist: choose 2/, /^Duelist Skill: Acrobatics/); - await pick(user, /^Fixture Duelist: choose 2/, /^Duelist Skill: Insight/); - await user.click(await screen.findByRole('button', { name: 'Create and save' })); - const hero = await screen.findByRole('article', { name: 'E2E Sling' }); - - // Inventory: an item and an attack of your own. Neither changes a calculation. - await openTab(user, hero, 'Gear'); - const armorClass = summaryValue(hero, 'Armor Class'); - const items = () => screen.getByRole('region', { name: 'Your own items' }); - await user.click(within(items()).getByRole('button', { name: 'Add an item of your own' })); - await user.type(within(items()).getByRole('textbox', { name: 'Name' }), 'Testy Rope'); - await user.click(within(items()).getByRole('button', { name: 'Save item' })); - await expectStatus(/^Added Testy Rope\.$/); - await waitFor(() => expect(document.activeElement).toBe(within(items()).getByRole('button', { name: 'Edit Testy Rope' }))); // focus can land a tick after the status text - - const own = () => screen.getByRole('region', { name: 'Your own attacks' }); - await user.click(within(own()).getByRole('button', { name: 'Add an attack of your own' })); - await user.type(within(own()).getByRole('textbox', { name: 'Name' }), 'Testy Sling'); - await user.clear(within(own()).getByRole('spinbutton', { name: 'To hit bonus' })); - await user.type(within(own()).getByRole('spinbutton', { name: 'To hit bonus' }), '5'); - // The dice engine's own message for bad damage, linked to the field; nothing is saved. - const damage = within(own()).getByRole('textbox', { name: 'Damage (optional)' }); - await user.type(damage, '5'); - await user.click(within(own()).getByRole('button', { name: 'Save attack' })); - await waitFor(() => expect(damage.getAttribute('aria-invalid')).toBe('true')); - expect(document.getElementById(damage.getAttribute('aria-describedby')!.split(' ').at(-1)!)?.textContent).toMatch(/dice/i); - await user.clear(damage); - await user.type(damage, '1d6+2'); - await user.selectOptions(within(own()).getByRole('combobox', { name: 'Damage type (optional)' }), 'Bludgeoning'); - await user.click(within(own()).getByRole('button', { name: 'Save attack' })); - await expectStatus(/^Added Testy Sling\.$/); - expect(summaryValue(hero, 'Armor Class')).toBe(armorClass); - - // Play: the attack is listed (the panel shows for a character with only custom attacks) and rolled with advantage. - await openTab(user, hero, 'Play'); - const actions = () => screen.getByRole('region', { name: 'Attacks and actions' }); - expect(within(actions()).getAllByRole('button', { name: 'Roll Testy Sling attack' })).toHaveLength(1); - await user.click(screen.getByRole('radio', { name: 'Advantage' })); - await user.click(within(actions()).getByRole('button', { name: 'Roll Testy Sling attack' })); - const lastRoll = screen.getByRole('status', { name: 'Last roll' }); - await waitFor(() => expect(lastRoll.textContent).toMatch(/Testy Sling attack: \d+ \(1d20, advantage\)/)); - expect(lastRoll.textContent).toMatch(/Testy Sling to hit \+5/); - await user.click(within(actions()).getByRole('button', { name: 'Roll Testy Sling damage' })); - await waitFor(() => expect(lastRoll.textContent).toMatch(/Testy Sling damage \(bludgeoning\): \d+ \(1d6\+2\)/)); -}); - -it('switches a toggled effect on and off, spends a chosen amount, and a long rest proposes the toggle off', async () => { - // M3 B2 (content v6) with the original fixture feat "Fixture Radiant Stance": a stance (+2 AC, spends 1 radiance) and a - // variable-cost surge. PB 2 at level 1, so 2 radiance. - const user = userEvent.setup(); - render(); - await createCharacter(user, { name: 'E2E Stance', scores: {}, cls: /^Fixture Duelist/, other: /^Fixture Radiant Stance/ }); - await pick(user, /^Fixture Duelist: choose 2/, /^Duelist Skill: Acrobatics/); - await pick(user, /^Fixture Duelist: choose 2/, /^Duelist Skill: Insight/); - await user.click(await screen.findByRole('button', { name: 'Create and save' })); - const stance = await screen.findByRole('article', { name: 'E2E Stance' }); - - const armorClass = () => Number(/^(\d+)/.exec(summaryValue(stance, 'Armor Class'))![1]); - const before = armorClass(); - const actions = () => screen.getByRole('region', { name: 'Attacks and actions' }); - await user.click(within(actions()).getByRole('checkbox', { name: /^Radiant stance/ })); - await waitFor(() => expect(armorClass()).toBe(before + 2)); - const resources = () => screen.getByRole('region', { name: 'Resources' }); - expect(within(resources()).getByRole('heading', { name: 'Radiance: 1 of 2' })).toBeTruthy(); - - // The surge spends a chosen amount (1 to the cost or what is left): here only 1 is left. - await user.click(within(actions()).getByRole('button', { name: 'Roll Radiant surge (1d6)' })); - const lastRoll = screen.getByRole('status', { name: 'Last roll' }); - await user.type(await within(lastRoll).findByRole('spinbutton', { name: 'Radiance to spend (1 to 1)' }), '1'); - await user.click(within(lastRoll).getByRole('button', { name: /^Spend 1 Radiance/ })); - await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Radiance: 0 of 2' })).toBeTruthy()); - - // The long rest proposes switching it off (and restores radiance). - await user.click(screen.getByRole('button', { name: 'Long rest…' })); - const rest = await screen.findByRole('region', { name: 'Long rest' }); - expect(await within(rest).findByRole('checkbox', { name: /^Radiant stance: 1 → 0/ })).toBeTruthy(); - await user.click(within(rest).getByRole('button', { name: 'Finish long rest' })); - await waitFor(() => expect(armorClass()).toBe(before)); - expect(within(actions()).getByRole('checkbox', { name: /^Radiant stance/ }).checked).toBe(false); -}); - -it('records a gap note on a field and a feature, resolves one, and deletes one after confirming', async () => { - // M3 B3: session feedback, stored locally and never changing the character. - const user = userEvent.setup(); - render(); - await createCharacter(user, { name: 'E2E Gaps', family: 'srd-5.1', scores: {}, species: /^Fixture Quickfoot/ }); - await user.click(await screen.findByRole('button', { name: 'Create and save' })); - const sheet = await screen.findByRole('article', { name: 'E2E Gaps' }); - const armorClass = summaryValue(sheet, 'Armor Class'); - await openTab(user, sheet, 'Skills and saves'); - const armorClassHeading = screen.getByRole('heading', { name: /^Armor Class:/ }).textContent; - - await openTab(user, sheet, 'Features'); // gap notes end the Features tab - const gaps = () => screen.getByRole('region', { name: /^Gap notes/ }); - expect(await within(gaps()).findByText('No gap notes yet.')).toBeTruthy(); - const form = within(gaps()).getByRole('form', { name: 'New gap note' }); - const about = within(form).getByRole('combobox', { name: /^About/ }); - const text = within(form).getByRole('textbox', { name: /^What was missing or wrong/ }); - - await user.selectOptions(about, within(about).getByRole('option', { name: 'Armor Class' })); - await user.type(text, 'The table grants a cover bonus here.'); - await user.click(within(form).getByRole('button', { name: 'Save note' })); - await waitFor(() => expect(appStatus().textContent).toBe('Gap note saved for Armor Class.')); - expect(within(gaps()).getByText('The table grants a cover bonus here.')).toBeTruthy(); - - // M3 C5: "Report a gap" on a feature pre-fills the picker and moves focus to the note's text. - await openTab(user, sheet, 'Features'); - const features = within(screen.getByRole('article', { name: 'E2E Gaps' })).getByRole('region', { name: 'Features' }); - await user.click(within(features).getByRole('button', { name: 'Report a gap: Fixture Quickfoot' })); - expect((about as HTMLSelectElement).selectedOptions[0]!.textContent).toBe('Fixture Quickfoot'); - await waitFor(() => expect(document.activeElement).toBe(text)); - expect(within(sheet).getByRole('tab', { name: 'Features' }).getAttribute('aria-selected')).toBe('true'); - await user.type(text, 'Speed bonus should apply while unarmored only.'); - await user.click(within(form).getByRole('button', { name: 'Save note' })); - await waitFor(() => expect(within(gaps()).getByRole('heading').textContent).toBe('Gap notes: 2 open')); - - await user.click(within(gaps()).getByRole('button', { name: 'Mark resolved: Armor Class' })); - await waitFor(() => expect(within(gaps()).getByRole('heading').textContent).toBe('Gap notes: 1 open')); - expect(within(gaps()).getByRole('button', { name: 'Reopen: Armor Class' })).toBeTruthy(); - - // "Report a gap" on a field works the same way (the field's details hold the button). - await openTab(user, sheet, 'Skills and saves'); - const armor = within(screen.getByRole('article', { name: 'E2E Gaps' })).getByRole('region', { name: /^Armor Class:/ }); - await user.click(within(armor).getByRole('heading')); - await user.click(within(armor).getByRole('button', { name: 'Report a gap: Armor Class' })); - expect((about as HTMLSelectElement).selectedOptions[0]!.textContent).toBe('Armor Class'); - await waitFor(() => expect(document.activeElement).toBe(text)); - // "Report a gap" left Features as the remembered tab; move the memory off it so the deep link below is what selects Features. - await openTab(user, sheet, 'Play'); - - // M3 C5: the list across characters shows the open note with its character; resolved ones only on request. - await user.click(within(screen.getByRole('navigation', { name: 'Main' })).getByRole('button', { name: 'Help' })); - const all = await screen.findByRole('region', { name: 'Gap notes' }); // a section of the Help screen; its list keeps "of all characters" - const allList = await within(all).findByRole('list', { name: 'Gap notes of all characters' }); - const mine = () => within(allList).getAllByRole('listitem').filter((li: HTMLElement) => li.textContent!.startsWith('E2E Gaps')); - expect(mine().map((li: HTMLElement) => li.textContent)).toEqual([expect.stringContaining('Speed bonus should apply while unarmored only.')]); - await user.click(within(all).getByRole('checkbox', { name: 'Show resolved notes' })); - await waitFor(() => expect(mine()).toHaveLength(2)); - await user.click(within(all).getAllByRole('button', { name: 'Open E2E Gaps' })[0]!); - await screen.findByRole('article', { name: 'E2E Gaps' }); - // "Open " from the Help screen's Gap notes section opens the sheet on Features, where the notes are. - expect(within(screen.getByRole('article', { name: 'E2E Gaps' })).getByRole('tab', { name: 'Features' }).getAttribute('aria-selected')).toBe('true'); - // The reopened sheet loads its notes again; wait for them before using them. - await within(gaps()).findByText('Speed bonus should apply while unarmored only.'); - - // Deleting asks first; "Keep note" leaves it. - const quickfootNote = () => within(gaps()).getByText('Speed bonus should apply while unarmored only.').closest('li')!; - await user.click(within(quickfootNote()).getByRole('button', { name: 'Delete…' })); - await user.click(within(quickfootNote()).getByRole('button', { name: 'Keep note' })); - await user.click(within(quickfootNote()).getByRole('button', { name: 'Delete…' })); - await user.click(within(quickfootNote()).getByRole('button', { name: 'Delete note' })); - await waitFor(() => expect(within(gaps()).queryByText('Speed bonus should apply while unarmored only.')).toBeNull()); - expect(within(gaps()).getByRole('heading').textContent).toBe('Gap notes: 0 open'); - - // Notes never change the character's sheet. - expect(summaryValue(screen.getByRole('article', { name: 'E2E Gaps' }), 'Armor Class')).toBe(armorClass); - await openTab(user, screen.getByRole('article', { name: 'E2E Gaps' }), 'Skills and saves'); - expect(screen.getByRole('heading', { name: /^Armor Class:/ }).textContent).toBe(armorClassHeading); -}); - -it('opens Help from the sidebar with its h1 focused, lists a sheet gap note there, and Open lands on Features', async () => { - const user = userEvent.setup(); - const created = await client.createCharacter({ name: 'E2E Help Gaps', rulesFamily: 'srd-5.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [] }); - // A field every sheet has (the service refuses a field the sheet does not show). - await client.addGapNote(created.character.id, { kind: 'field', fieldId: 'initiative' }, 'Help screen note from the sheet.'); - render(); - await user.click(within(await screen.findByRole('navigation', { name: 'Main' })).getByRole('button', { name: 'Help' })); - const h1 = await screen.findByRole('heading', { level: 1, name: 'Help' }); - await waitFor(() => expect(document.activeElement).toBe(h1)); - const section = screen.getByRole('region', { name: 'Gap notes' }); - expect(await within(section).findByText('Help screen note from the sheet.')).toBeTruthy(); - await user.click(within(section).getAllByRole('button', { name: 'Open E2E Help Gaps' })[0]!); - const sheet = await screen.findByRole('article', { name: 'E2E Help Gaps' }); - expect(within(sheet).getByRole('tab', { name: 'Features' }).getAttribute('aria-selected')).toBe('true'); -}); - -it('keeps the older-version choice behind a disclosure on the sheet export, and picks a release once opened', async () => { - const user = userEvent.setup(); - await client.createCharacter({ name: 'E2E Older Target', rulesFamily: 'srd-5.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [] }); - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Older Target/ })); - const sheet = await screen.findByRole('article', { name: 'E2E Older Target' }); - await openMore(user, sheet, 'Export…'); - const panel = within(sheet).getByRole('region', { name: 'Export' }); - // D103: only the previous minor is offered, so a build with no such release (the DevHost of an unreleased minor - // may have none) shows a plain hint and no choice at all. - await waitFor(() => expect(within(panel).queryByText(/^This TomeStack has no older version to save for\.$|^Opening this in an older TomeStack\?/)).not.toBeNull()); - if (within(panel).queryByText('This TomeStack has no older version to save for.')) { - expect(panel.querySelector('details')).toBeNull(); - expect(within(panel).queryByRole('group', { name: 'Which version will open this file?' })).toBeNull(); - return; - } - const release = within(panel).getAllByText(/^\d+\.\d+\.\d+$/, { selector: 'label' })[0]!.textContent!; - expect(panel.querySelector('details')!.open).toBe(false); - await chooseOlderTarget(user, panel, release); - expect((within(panel).getByRole('radio', { name: release }) as HTMLInputElement).checked).toBe(true); -}); - -it('prints a sheet with its license notices, and gap notes only when ticked', async () => { - // M3 C4: the printable backup. The print dialog is the browser's; here window.print is a spy. - const print = vi.spyOn(window, 'print').mockImplementation(() => {}); - const user = userEvent.setup(); - render(); - await createCharacter(user, { name: 'E2E Print', family: 'srd-5.1', scores: {}, species: /^Fixture Quickfoot/ }); - await user.click(await screen.findByRole('button', { name: 'Create and save' })); - const sheet = await screen.findByRole('article', { name: 'E2E Print' }); - - await openTab(user, sheet, 'Features'); - const gaps = within(sheet).getByRole('region', { name: /^Gap notes/ }); - const form = within(gaps).getByRole('form', { name: 'New gap note' }); - await user.selectOptions(within(form).getByRole('combobox', { name: /^About/ }), 'Armor Class'); - await user.type(within(form).getByRole('textbox', { name: /^What was missing or wrong/ }), 'Private note for the print test.'); - await user.click(within(form).getByRole('button', { name: 'Save note' })); - await within(gaps).findByText('Private note for the print test.'); - await openTab(user, sheet, 'Journal'); - const journal = within(sheet).getByRole('form', { name: 'New session note' }); - await user.type(within(journal).getByRole('textbox', { name: 'Note' }), 'Private session note for the print test.'); - await user.click(within(journal).getByRole('button', { name: 'Save session note' })); - await within(sheet).findByText('Private session note for the print test.'); - const detailsForm = within(sheet).getByRole('form', { name: 'Details' }); - await user.type(within(detailsForm).getByRole('textbox', { name: 'Backstory' }), 'Private backstory for the print test.'); - await user.click(within(detailsForm).getByRole('button', { name: 'Save details' })); - await expectStatus(/Details saved/); - - await openMore(user, sheet, 'Print…'); - const preview = await within(sheet).findByRole('region', { name: 'Print preview' }); - await waitFor(() => expect(document.activeElement).toBe(within(preview).getByRole('heading', { name: 'Print character' }))); // focus moves to the preview on open - expect(within(preview).getByRole('heading', { name: 'E2E Print' })).toBeTruthy(); - expect(within(preview).getByRole('table', { name: 'Abilities' })).toBeTruthy(); - expect(within(preview).getByText(/^Fixture Quickfoot/)).toBeTruthy(); - // The license notices of the sources used (the fixture sources here), and the version it was printed from. - await waitFor(() => expect(preview.querySelectorAll('.print-notice').length).toBeGreaterThan(0)); - await waitFor(() => expect(preview.textContent).toMatch(/Printed from TomeStack \d+\.\d+\.\d+/)); - // Gap notes are private: left out until ticked. No path ever appears. - expect(preview.textContent).not.toContain('Private note for the print test.'); - expect(preview.textContent).not.toMatch(/[A-Za-z]:\\|\/Users\/|\\Users\\/); - await user.click(within(preview).getByRole('checkbox', { name: /^Include gap notes/ })); - expect(await within(preview).findByText(/Private note for the print test\./)).toBeTruthy(); - // Session notes are private too: absent until their own box is ticked. - expect(preview.textContent).not.toContain('Private session note for the print test.'); - await user.click(within(preview).getByRole('checkbox', { name: 'Include session notes (private)' })); - expect(await within(preview).findByText(/Private session note for the print test\./)).toBeTruthy(); - // Details have their own tick, unticked by default. - const includeDetails = within(preview).getByRole('checkbox', { name: /^Include details/ }); - expect(includeDetails.checked).toBe(false); - expect(preview.textContent).not.toContain('Private backstory for the print test.'); - await user.click(includeDetails); - expect(await within(preview).findByText(/Private backstory for the print test\./)).toBeTruthy(); - - await user.click(within(preview).getByRole('button', { name: 'Print…' })); - expect(print).toHaveBeenCalledTimes(1); - await user.click(within(preview).getByRole('button', { name: 'Close print preview' })); - expect(within(sheet).queryByRole('region', { name: 'Print preview' })).toBeNull(); - await waitFor(() => expect(document.activeElement).toBe(within(sheet).getByRole('button', { name: 'More' }))); - print.mockRestore(); -}); - -it('builds a spellcaster: picks spells in the builder, casts one, rolls a spell attack and a long rest restores the slot', async () => { - // D04 (M2 spellcasting) with the original fixture caster "Fixture Arcanist" (invented tables: 2 level 1 slots at level 1). - const user = userEvent.setup(); - render(); - await createCharacter(user, { name: 'E2E Sage', family: 'srd-5.2.1', scores: { Intelligence: 16 }, cls: /^Fixture Arcanist/ }); - - // Int 16 (+3) at level 1: 3 cantrips, max(1, 3 + 1) = 4 prepared. Only spells on the caster's list and castable levels. - let picker = await screen.findByRole('group', { name: /^Fixture Arcanist spells \(0 of 3 cantrips, 0 of 4 prepared spells\)/ }); - expect(within(picker).queryByRole('checkbox', { name: /Fixture Mending Word/ })).toBeNull(); // another list - expect(within(picker).queryByRole('checkbox', { name: /Fixture Ember Wave/ })).toBeNull(); // level 3: no slot yet - // D30: the search hides what does not match and says how many are shown; clearing it brings everything back. - const search = within(picker).getByRole('searchbox', { name: 'Search Fixture Arcanist spells by name' }); - await user.type(search, 'frost'); - expect(within(picker).getByText(/^1 of \d+ spells shown$/)).toBeTruthy(); - expect(within(picker).queryByRole('checkbox', { name: /^Fixture Spark/ })).toBeNull(); - await user.clear(search); - await user.click(within(picker).getByRole('checkbox', { name: /^Fixture Spark/ })); - picker = await screen.findByRole('group', { name: /^Fixture Arcanist spells \(1 of 3 cantrips/ }); - // R23: a chosen spell the search hides is named in the status, and the legend's count still includes it. - const search2 = within(picker).getByRole('searchbox', { name: 'Search Fixture Arcanist spells by name' }); - await user.type(search2, 'frost'); - expect(within(picker).getByText(/^1 of \d+ spells shown, 1 chosen hidden by the search$/)).toBeTruthy(); - expect(within(picker).queryByRole('checkbox', { name: /^Fixture Spark/ })).toBeNull(); - await screen.findByRole('group', { name: /^Fixture Arcanist spells \(1 of 3 cantrips/ }); - await user.type(search2, 'zz'); - expect(within(picker).getByText(/No spells match “frostzz”/)).toBeTruthy(); - await user.clear(search2); - expect(within(picker).getByRole('checkbox', { name: /^Fixture Spark/ })).toBeTruthy(); - await user.click(within(picker).getByRole('checkbox', { name: /^Fixture Frost Ring/ })); - await screen.findByRole('group', { name: /^Fixture Arcanist spells \(1 of 3 cantrips, 1 of 4 prepared spells\)/ }); - await user.click(screen.getByRole('button', { name: 'Create and save' })); - - const sheet = await screen.findByRole('article', { name: 'E2E Sage' }); - await openTab(user, sheet, 'Spells'); - const spells = () => within(screen.getByRole('article', { name: 'E2E Sage' })).getByRole('region', { name: 'Spells and slots' }); - expect(within(spells()).getByRole('heading', { name: 'Fixture Arcanist (level 1, Intelligence): spell attack +5, save DC 13' })).toBeTruthy(); - expect(within(spells()).getByRole('heading', { name: 'Level 1 slots: 2 of 2' })).toBeTruthy(); - expect(within(sheet).getByRole('heading', { name: /^Spell attack bonus: \+5/ })).toBeTruthy(); - - // Concentration (D19) is not driven here: the fixture pack's only concentration spell (Fixture Veil) is level 2, which this - // level 1 character cannot prepare. The panel and its service rules are covered by ConcentrationPanel.test.tsx and PlayCommandTests. - // Casting spends a slot (a confirmed play change); rolling a spell spends nothing. - await user.click(within(spells()).getByRole('button', { name: 'Cast Fixture Frost Ring (spend a slot)' })); - await waitFor(() => expect(within(spells()).getByRole('heading', { name: 'Level 1 slots: 1 of 2' })).toBeTruthy()); - await user.click(within(spells()).getByRole('button', { name: 'Roll Fixture Spark attack' })); - const lastRoll = screen.getByRole('status', { name: 'Last roll' }); - await waitFor(() => expect(lastRoll.textContent).toMatch(/Fixture Spark \(spell attack\): \d+ \(1d20\)/)); - expect(lastRoll.textContent).toMatch(/Fixture Arcanist spell attack \+5/); - expect(within(spells()).getByRole('heading', { name: 'Level 1 slots: 1 of 2' })).toBeTruthy(); - - // The long rest proposes the slot back. - await openTab(user, sheet, 'Play'); - await user.click(screen.getByRole('button', { name: 'Long rest…' })); - const rest = await screen.findByRole('region', { name: 'Long rest' }); - expect(await within(rest).findByRole('checkbox', { name: /^Level 1 spell slots: 1 → 2/ })).toBeTruthy(); - await user.click(within(rest).getByRole('button', { name: 'Finish long rest' })); - await openTab(user, sheet, 'Spells'); - await waitFor(() => expect(within(spells()).getByRole('heading', { name: 'Level 1 slots: 2 of 2' })).toBeTruthy()); -}); - -it('a roll from any tab shows in the status bar', async () => { - const user = userEvent.setup(); - render(); - await createCharacter(user, { name: 'E2E Barwatch', family: 'srd-5.2.1', scores: { Intelligence: 16 }, cls: /^Fixture Arcanist/ }); - const picker = await screen.findByRole('group', { name: /^Fixture Arcanist spells \(0 of 3 cantrips, 0 of 4 prepared spells\)/ }); - await user.click(within(picker).getByRole('checkbox', { name: /^Fixture Spark/ })); - await user.click(screen.getByRole('button', { name: 'Create and save' })); - const sheet = await screen.findByRole('article', { name: 'E2E Barwatch' }); - - // Gear: a weapon, so Play has an attack to roll. - await openTab(user, sheet, 'Gear'); - const equipment = () => screen.getByRole('region', { name: 'Equipment' }); - await waitFor(() => expect(within(equipment()).getByRole('option', { name: /^Fixture Needle/ })).toBeTruthy()); - await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^Fixture Needle/ })); - await user.click(within(equipment()).getByRole('button', { name: 'Add' })); - await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip Fixture Needle' })); - - // The last roll is the one live node inside the status bar, whichever tab rolled it. - const bar = () => within(screen.getByRole('region', { name: 'Status' })); - expect(screen.getByRole('region', { name: 'Status' }).classList.contains('status-bar')).toBe(true); - const lastRoll = () => bar().getByRole('status', { name: 'Last roll' }); - - await openTab(user, sheet, 'Play'); - const actions = () => screen.getByRole('region', { name: 'Attacks and actions' }); - await user.click(await within(actions()).findByRole('button', { name: 'Roll Fixture Needle attack' })); - await waitFor(() => expect(lastRoll().textContent).toMatch(/Fixture Needle attack: \d+ \(1d20\)/)); - - await openTab(user, sheet, 'Spells'); - const spells = () => within(screen.getByRole('article', { name: 'E2E Barwatch' })).getByRole('region', { name: 'Spells and slots' }); - await user.click(within(spells()).getByRole('button', { name: 'Roll Fixture Spark attack' })); - await waitFor(() => expect(lastRoll().textContent).toMatch(/Fixture Spark \(spell attack\): \d+ \(1d20\)/)); - expect(lastRoll().textContent).not.toMatch(/Fixture Needle/); - - await openTab(user, sheet, 'Skills and saves'); - const intSave = screen.getByRole('region', { name: /^Intelligence saving throw:/ }); - await user.click(within(intSave).getByRole('heading')); - await user.click(within(intSave).getByRole('button', { name: 'Roll Intelligence saving throw' })); - await waitFor(() => expect(lastRoll().textContent).toMatch(/Intelligence saving throw \(d20 test\): \d+ \(1d20\)/)); - expect(lastRoll().textContent).not.toMatch(/Fixture Spark/); -}); - -it('the Backups screen says what a full backup holds, and needs the desktop app to write or restore one (M2.1)', async () => { - const user = userEvent.setup(); - render(); - - await user.click(await screen.findByRole('button', { name: 'Backups' })); - const panel = await screen.findByRole('region', { name: 'Backups' }); - // Earlier flows in this run created characters, homebrew drafts, a campaign and a PDF copy: the counts come from the service. - const contents = await within(panel).findByRole('list', { name: 'What the backup contains' }); - expect(contents.textContent).toMatch(/\d+ character\(s\), \d+ campaign\(s\), \d+ gap note\(s\)/); - expect(contents.textContent).toMatch(/\d+ published and [1-9]\d* draft entries/); - expect(contents.textContent).toMatch(/Not included: text read from PDFs/); - - // D77: daily copies are on by default; the setting is kept by the service (DevHost takes no copies itself). - const daily = await within(panel).findByRole('checkbox', { name: 'Keep 7 daily copies' }); - expect((daily as HTMLInputElement).checked).toBe(true); - await user.click(daily); - await waitFor(() => expect((daily as HTMLInputElement).checked).toBe(false)); - expect((await client.dailyCopies()).on).toBe(false); - await user.click(daily); // back on, for the flows after this one - await waitFor(() => expect((daily as HTMLInputElement).checked).toBe(true)); - - // DevHost has no native Save or Open dialog, so both say what they need instead of doing nothing. - await user.click(within(panel).getByRole('button', { name: 'Back up everything…' })); - expect((await screen.findByRole('alert')).textContent).toMatch(/Backing up everything needs the TomeStack desktop app/); - await user.click(within(panel).getByRole('button', { name: 'Choose a full backup…' })); - await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/Restoring a full backup needs the TomeStack desktop app/)); -}); - -const fighter = (n: number) => srd(408000 + n); - -it('adds a homebrew Fighter subclass through the studio and plays it: the Stardust Guardian path with original content (M2.2)', async () => { - const user = userEvent.setup(); - // An SRD 5.2.1 Fighter 3 with the Defense style and no subclass yet (the builder flows cover building one). - await client.createCharacter({ - name: 'E2E Warden', - rulesFamily: 'srd-5.2.1', - baseAbilities: { str: 16, dex: 14, con: 14, int: 10, wis: 12, cha: 8 }, - pins: [srd(1), srd(2)], - classes: [{ class: fighter(0), level: 3 }], - choices: [ - { source: srd(2), choiceId: 'soldier-ability-scores', selected: [srd(4)] }, - { source: fighter(0), choiceId: 'fighter-skills', selected: [fighter(800), fighter(802)] }, - { source: fighter(1), choiceId: 'fighting-style', selected: [fighter(601)] }, - ], - }); - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - - const newSource = await screen.findByRole('form', { name: 'New book or notebook' }); - await user.type(within(newSource).getByRole('textbox', { name: 'Title' }), 'E2E Warden Homebrew'); - await user.click(within(newSource).getByRole('checkbox', { name: '2024 rules' })); - await user.click(within(newSource).getByRole('button', { name: 'Create' })); - await screen.findByRole('heading', { name: 'Content in E2E Warden Homebrew' }); - - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - const rule = (name: RegExp) => within(editor()).getByRole('group', { name }); - async function publish(name: string) { - await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); - await waitFor(() => expect(appStatus().textContent).toBe(`Made ${name} available to characters.`)); - } - - // A limited-use feature: a resource, its recovery and a roll that spends it. - await user.click(screen.getByRole('button', { name: 'New feature' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Star Shield'); - await user.click(within(editor()).getByRole('button', { name: 'Add resource' })); - await user.type(within(rule(/^Rule 1: Resource/)).getByRole('textbox', { name: 'Resource name' }), 'Star charges'); - await user.click(within(editor()).getByRole('button', { name: 'Add recovery' })); - await user.click(within(editor()).getByRole('button', { name: 'Add roll or action' })); - const action = rule(/^Rule 3: Roll or action/); - await user.type(within(action).getByRole('textbox', { name: 'Roll name' }), 'Star burst'); - await user.clear(within(action).getByRole('textbox', { name: /^Dice/ })); - await user.type(within(action).getByRole('textbox', { name: /^Dice/ }), '2d6'); - await user.selectOptions(within(action).getByRole('combobox', { name: /Uses a resource/ }), 'Star charges'); - await publish('E2E Star Shield'); - - // The subclass joins the SRD Fighter's level-3 choice, with a modifier and the feature. - await user.click(screen.getByRole('button', { name: 'New subclass' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Starward Warden'); - const offered = within(editor()).getByRole('combobox', { name: 'Subclass of' }); - await waitFor(() => expect(within(offered).getByRole('option', { name: /^Fighter: Level 3: Fighter Subclass/ })).toBeTruthy()); - await user.selectOptions(offered, within(offered).getByRole('option', { name: /^Fighter: Level 3: Fighter Subclass/ })); - await user.click(within(editor()).getByRole('button', { name: 'Add modifier' })); // default: Initiative +1 - await user.click(within(editor()).getByRole('button', { name: 'Grant a feature' })); - await user.selectOptions(within(rule(/^Rule 2: Granted feature/)).getByRole('combobox', { name: 'Feature' }), 'E2E Star Shield (published)'); - await publish('E2E Starward Warden'); - - // Choose it on the sheet, next to the SRD Champion, then play. - await user.click(screen.getByRole('button', { name: /^E2E Warden/ })); - let sheet = await screen.findByRole('article', { name: 'E2E Warden' }); - await user.click(within(sheet).getByRole('button', { name: 'Choose now' })); - const subclass = await screen.findByRole('group', { name: /^Fighter: choose 1/ }); - expect(await within(subclass).findByRole('checkbox', { name: /^Champion/ })).toBeTruthy(); - await pick(user, /^Fighter: choose 1/, /^E2E Starward Warden/); - await user.click(await screen.findByRole('button', { name: 'Save choices' })); - - sheet = await screen.findByRole('article', { name: 'E2E Warden' }); - await openTab(user, sheet, 'Skills and saves'); - expect(within(sheet).getByRole('heading', { name: /^Initiative: \+3/ })).toBeTruthy(); // Dex +2, homebrew +1 - expect(within(sheet).getByRole('heading', { name: /^Attacks per Attack action: 1/ })).toBeTruthy(); // Extra Attack comes at 5 - await openTab(user, sheet, 'Play'); - const resources = () => within(screen.getByRole('article', { name: 'E2E Warden' })).getByRole('region', { name: 'Resources' }); - expect(within(resources()).getByRole('heading', { name: 'Star charges: 2 of 2' })).toBeTruthy(); - expect(within(resources()).getByRole('heading', { name: 'Second Wind: 2 of 2' })).toBeTruthy(); - expect(within(resources()).getByRole('heading', { name: 'Action Surge: 1 of 1' })).toBeTruthy(); - - // Second Wind rolls 1d10 plus the Fighter level; spending it is a separate, confirmed press. - await user.click(within(sheet).getByRole('button', { name: 'Roll Second Wind healing (1d10 + 3)' })); - const lastRoll = screen.getByRole('status', { name: 'Last roll' }); - await waitFor(() => expect(lastRoll.textContent).toMatch(/Second Wind healing bonus \+3/)); - expect(lastRoll.textContent).not.toMatch(/CLASS_LEVEL/); // the label names the roll, not its formula - await user.click(await screen.findByRole('button', { name: 'Spend 1 Second Wind (2 left)' })); - await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Second Wind: 1 of 2' })).toBeTruthy()); - await user.click(within(screen.getByRole('article', { name: 'E2E Warden' })).getByRole('button', { name: 'Roll Star burst (2d6)' })); - await user.click(await screen.findByRole('button', { name: 'Spend 1 Star charges (2 left)' })); - await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Star charges: 1 of 2' })).toBeTruthy()); - - // A short rest gives one Second Wind use back (2024); the homebrew charges wait for the long rest. - await user.click(screen.getByRole('button', { name: 'Short rest…' })); - const rest = await screen.findByRole('region', { name: 'Short rest' }); - expect(await within(rest).findByRole('checkbox', { name: /^Second Wind: 1 → 2/ })).toBeTruthy(); - expect(within(rest).queryByRole('checkbox', { name: /^Star charges/ })).toBeNull(); - await user.click(within(rest).getByRole('button', { name: 'Finish short rest' })); - await expectStatus(/Short rest finished/); - await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Second Wind: 2 of 2' })).toBeTruthy()); -}); - -it('authors a class in the studio and builds it at levels 1, 20 and 5/3 with an SRD class (M5 exit gate, ADR-010)', async () => { - // An original nonstandard class, built in the studio with no code edits: a d8, Int and Wis saves, a multiclass - // prerequisite, a skill choice, a column ("Ink"), a resource that reads it, and a caster whose multiclass share is its - // own table (two thirds). Tables are invented for testing. - const user = userEvent.setup(); - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - const newSource = await screen.findByRole('form', { name: 'New book or notebook' }); - await user.type(within(newSource).getByRole('textbox', { name: 'Title' }), 'E2E Chronicle Homebrew'); - await user.click(within(newSource).getByRole('checkbox', { name: '2024 rules' })); - await user.click(within(newSource).getByRole('button', { name: 'Create' })); - await screen.findByRole('heading', { name: 'Content in E2E Chronicle Homebrew' }); - - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - const rule = (name: RegExp) => within(editor()).getByRole('group', { name }); - await user.click(screen.getByRole('button', { name: 'New class' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Chronicler'); - - const basics = within(editor()).getByRole('region', { name: 'Class basics' }); - await user.selectOptions(within(basics).getByRole('combobox', { name: 'Hit die' }), 'd8'); - const saves = within(basics).getByRole('group', { name: /^Saving throw proficiencies/ }); - await user.click(within(saves).getByRole('checkbox', { name: 'Intelligence' })); - await user.click(within(saves).getByRole('checkbox', { name: 'Wisdom' })); - const prerequisites = within(basics).getByRole('group', { name: /^Multiclass prerequisites/ }); - await user.type(within(prerequisites).getByRole('spinbutton', { name: 'Intelligence at least' }), '13'); - const skills = within(basics).getByRole('group', { name: /^Skill choice/ }); - await user.click(within(skills).getByRole('checkbox', { name: 'History' })); - await user.click(within(skills).getByRole('checkbox', { name: 'Arcana' })); - await user.click(within(skills).getByRole('checkbox', { name: 'Investigation' })); - await user.click(within(skills).getByRole('button', { name: 'Create skill choice' })); - await waitFor(() => expect(within(skills).getByText(/Choose 2 of 3 skills/)).toBeTruthy()); - expect(within(skills).getByText(/3 new option features published, 0 reused/)).toBeTruthy(); // announced, and focus stays in the group - expect(document.activeElement).toBe(within(skills).getByText('Skill choice (starting class only)')); - // Removing the choice and creating it again reuses the three published features, never publishes duplicates (review fix). - await user.click(within(skills).getByRole('button', { name: 'Remove the skill choice' })); - await waitFor(() => expect(within(skills).getByText(/Skill choice removed/)).toBeTruthy()); - await user.click(within(skills).getByRole('checkbox', { name: 'History' })); - await user.click(within(skills).getByRole('checkbox', { name: 'Arcana' })); - await user.click(within(skills).getByRole('checkbox', { name: 'Investigation' })); - await user.click(within(skills).getByRole('button', { name: 'Create skill choice' })); - await waitFor(() => expect(within(skills).getByText(/0 new option features published, 3 reused/)).toBeTruthy()); - expect(within(skills).getByText(/Choose 2 of 3 skills/)).toBeTruthy(); - await user.click(within(within(basics).getByRole('group', { name: 'Subclass' })).getByRole('checkbox', { name: /^This class has subclasses/ })); - - await user.click(within(editor()).getByRole('button', { name: 'Add class column' })); - const column = rule(/^Rule 1: Class column/); - await user.type(within(column).getByRole('textbox', { name: 'Column name' }), 'Ink'); - await user.clear(within(column).getByRole('textbox', { name: /^Key/ })); - await user.type(within(column).getByRole('textbox', { name: /^Key/ }), 'ink'); - const values = within(column).getByRole('textbox', { name: /^Values at class levels/ }); - await user.clear(values); - await user.type(values, '2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9'); - - await user.click(within(editor()).getByRole('button', { name: 'Add resource' })); - const ink = rule(/^Rule 2: Resource/); - await user.type(within(ink).getByRole('textbox', { name: 'Resource name' }), 'Ink'); - await user.clear(within(ink).getByRole('textbox', { name: /^Uses/ })); - // D61: the formula's preview, worked out by the real service against this draft (proficiency bonus 6 at level 20). - await user.type(within(ink).getByRole('textbox', { name: /^Uses/ }), 'PB'); - expect((await within(ink).findByText(/Level 20: 6/)).textContent).toMatch(/^Level 1: 2 · .* · Level 20: 6$/); - expect(within(ink).getByRole('textbox', { name: /^Uses/ }).getAttribute('aria-describedby')).toMatch(/^rule-resource-\d+-maximum-preview$/); - await user.clear(within(ink).getByRole('textbox', { name: /^Uses/ })); - await user.type(within(ink).getByRole('textbox', { name: /^Uses/ }), 'SCALE.ink'); - expect(await within(ink).findByText(/Level 1: 2 · .* · Level 20: 9$/)).toBeTruthy(); // the draft's own column - await user.click(within(editor()).getByRole('button', { name: 'Add recovery' })); // all, on a long rest - - await user.click(within(editor()).getByRole('button', { name: 'Add spellcasting' })); - const casting = rule(/^Rule 4: Spellcasting/); - await user.type(within(casting).getByRole('textbox', { name: /^Spell list key/ }), 'e2e-chronicle'); - const slots = ['1', '2', '3', '3, 1', '3, 2', '4, 2', '4, 2, 1', '4, 3, 1', '4, 3, 2', '4, 3, 2, 1', '4, 3, 3, 1', '4, 3, 3, 2', '4, 3, 3, 2, 1', '4, 3, 3, 3, 1', '4, 3, 3, 3, 2', '4, 3, 3, 3, 2, 1', '4, 3, 3, 3, 2, 1', '4, 3, 3, 3, 3, 1', '4, 3, 3, 3, 3, 2', '4, 3, 3, 3, 3, 2, 1']; - await user.type(within(casting).getByRole('textbox', { name: /^Spell slots/ }), slots.join('{Enter}')); - await user.selectOptions(within(casting).getByRole('combobox', { name: /^With other casters/ }), 'Its own table of caster levels'); - const share = within(casting).getByRole('textbox', { name: /^Caster levels it adds/ }); - await user.clear(share); - await user.type(share, '0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10, 11, 12, 12, 13'); - - await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); - await waitFor(() => expect(appStatus().textContent).toBe('Made E2E Chronicler available to characters.')); - - // A homebrew subclass joins the new class's subclass choice, which declares no options of its own. - await user.click(screen.getByRole('button', { name: 'New subclass' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Order of Quills'); - const offered = within(editor()).getByRole('combobox', { name: 'Subclass of' }); - await waitFor(() => expect(within(offered).getByRole('option', { name: 'E2E Chronicler: Choose a subclass' })).toBeTruthy()); - await user.selectOptions(offered, 'E2E Chronicler: Choose a subclass'); - await user.click(within(editor()).getByRole('button', { name: 'Add modifier' })); // default: Initiative +1 - await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); - await waitFor(() => expect(appStatus().textContent).toBe('Made E2E Order of Quills available to characters.')); - - // Level 1 in the builder: the class is offered like any other, with its skill choice. - await createCharacter(user, { name: 'E2E Scribe', family: 'srd-5.2.1', scores: { Intelligence: 16 }, cls: /^E2E Chronicler/ }); - await pick(user, /^Choose 2 skills/, /^E2E Chronicler: History/); - await pick(user, /^Choose 2 skills/, /^E2E Chronicler: Arcana/); - await user.click(await screen.findByRole('button', { name: 'Create and save' })); - let sheet = await screen.findByRole('article', { name: 'E2E Scribe' }); - await openTab(user, sheet, 'Skills and saves'); - expect(within(sheet).getByRole('heading', { name: /^History: \+5/ })).toBeTruthy(); // the chosen option grants it: Int +3, PB +2 - await openTab(user, sheet, 'Play'); - expect(within(within(sheet).getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Ink: 2 of 2' })).toBeTruthy(); - expect(within(within(sheet).getByRole('region', { name: 'Class columns' })).getByText('Ink: 2')).toBeTruthy(); - await openTab(user, sheet, 'Spells'); - expect(within(within(sheet).getByRole('region', { name: 'Spells and slots' })).getByRole('heading', { name: 'Level 1 slots: 1 of 1' })).toBeTruthy(); - - // Level 20, and Chronicler 5 with the SRD Wizard 3: the same published class, no code edits. - const options = await client.listContent('srd-5.2.1'); - const chronicler = options.find((o) => o.kind === 'class' && o.name === 'E2E Chronicler' && !o.superseded)!.reference; - const wizard = options.find((o) => o.kind === 'class' && o.name === 'Wizard' && o.compatible && !o.superseded)!.reference; - const order = options.find((o) => o.kind === 'subclass' && o.name === 'E2E Order of Quills' && !o.superseded)!.reference; - const scores = { str: 10, dex: 12, con: 14, int: 16, wis: 14, cha: 10 }; - await client.createCharacter({ - name: 'E2E Scribe 20', - rulesFamily: 'srd-5.2.1', - baseAbilities: scores, - pins: [], - classes: [{ class: chronicler, level: 20 }], - choices: [{ source: chronicler, choiceId: 'subclass', selected: [order] }], - }); - await client.createCharacter({ - name: 'E2E Scribe Wizard', - rulesFamily: 'srd-5.2.1', - baseAbilities: scores, - pins: [], - classes: [{ class: chronicler, level: 5 }, { class: wizard, level: 3 }], - choices: [], - }); - cleanup(); - render(); - - await user.click(await screen.findByRole('button', { name: /^E2E Scribe 20 / })); - sheet = await screen.findByRole('article', { name: 'E2E Scribe 20' }); - await openTab(user, sheet, 'Skills and saves'); - expect(within(sheet).getByRole('heading', { name: /^Hit point maximum: 143/ })).toBeTruthy(); // 8 + 19 × 5 + 20 × Con 2 - expect(within(sheet).getByRole('heading', { name: /^Initiative: \+2/ })).toBeTruthy(); // Dex +1, the homebrew subclass +1 - await openTab(user, sheet, 'Play'); - expect(within(within(sheet).getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Ink: 9 of 9' })).toBeTruthy(); - await openTab(user, sheet, 'Spells'); - expect(within(within(sheet).getByRole('region', { name: 'Spells and slots' })).getByRole('heading', { name: 'Level 7 slots: 1 of 1' })).toBeTruthy(); - - await user.click(screen.getByRole('button', { name: /^E2E Scribe Wizard/ })); - sheet = await screen.findByRole('article', { name: 'E2E Scribe Wizard' }); - await openTab(user, sheet, 'Spells'); - const spells = within(sheet).getByRole('region', { name: 'Spells and slots' }); - // Chronicler 5 counts 3 (its table) + Wizard 3: caster level 6 on the Multiclass Spellcaster table. - expect(within(spells).getByRole('heading', { name: 'Level 1 slots: 4 of 4' })).toBeTruthy(); - expect(within(spells).getByRole('heading', { name: 'Level 3 slots: 3 of 3' })).toBeTruthy(); - await openTab(user, sheet, 'Play'); - expect(within(within(sheet).getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Ink: 4 of 4' })).toBeTruthy(); -}); - -it('archives a character after a preview, lists it apart, and brings it back (SPEC C-08)', async () => { - const user = userEvent.setup(); - render(); - await createCharacter(user, { name: 'E2E Archivist', family: 'srd-5.1', scores: {}, species: /^Fixture Quickfoot/ }); - await user.click(await screen.findByRole('button', { name: 'Create and save' })); - const sheet = await screen.findByRole('article', { name: 'E2E Archivist' }); - const characters = screen.getByRole('navigation', { name: 'Main' }); - await openMore(user, sheet, 'Archive'); - - // Preview first: focus moves into it, and Escape (or "Keep it") changes nothing and returns focus. - await user.click(within(sheet).getByRole('button', { name: 'Archive…' })); - let confirm = await screen.findByRole('alertdialog', { name: 'Archive E2E Archivist?' }); - expect(confirm.textContent).toMatch(/Nothing is deleted/); - await waitFor(() => expect(document.activeElement).toBe(within(confirm).getByRole('button', { name: 'Archive' }))); - await user.keyboard('{Escape}'); - expect(screen.queryByRole('alertdialog')).toBeNull(); - await waitFor(() => expect(document.activeElement).toBe(within(sheet).getByRole('button', { name: 'Archive…' }))); - await user.click(within(sheet).getByRole('button', { name: 'Archive…' })); - confirm = await screen.findByRole('alertdialog', { name: 'Archive E2E Archivist?' }); - await user.click(within(confirm).getByRole('button', { name: 'Keep it' })); - expect(screen.queryByRole('alertdialog')).toBeNull(); - expect(within(characters).getByRole('button', { name: /E2E Archivist/ })).toBeTruthy(); - - // Confirmed: the character moves to the collapsed "Archived" list, and its sheet says so. - await user.click(within(sheet).getByRole('button', { name: 'Archive…' })); - confirm = await screen.findByRole('alertdialog', { name: 'Archive E2E Archivist?' }); - await user.click(within(confirm).getByRole('button', { name: 'Archive' })); - await expectStatus(/Archived E2E Archivist/); - const archivedList = await within(characters).findByRole('list', { name: 'Archived characters' }); - expect(within(archivedList).getByRole('button', { name: /E2E Archivist/ })).toBeTruthy(); - expect(archivedList.closest('details')!.open).toBe(false); - await waitFor(() => expect(within(screen.getByRole('article', { name: 'E2E Archivist' })).getByRole('heading', { name: 'Archived' })).toBeTruthy()); - // The pressed button is gone; focus lands on the control that replaced it, not on . - await waitFor(() => expect(document.activeElement).toBe(within(screen.getByRole('article', { name: 'E2E Archivist' })).getByRole('button', { name: 'Unarchive' }))); - - // Unarchive: back in the main list. - await user.click(within(screen.getByRole('article', { name: 'E2E Archivist' })).getByRole('button', { name: 'Unarchive' })); - await expectStatus(/back in the character list/); - await waitFor(() => expect(within(characters).queryByRole('list', { name: 'Archived characters' })).toBeNull()); - expect(within(characters).getByRole('button', { name: /E2E Archivist/ })).toBeTruthy(); - await waitFor(() => expect(document.activeElement).toBe(within(screen.getByRole('article', { name: 'E2E Archivist' })).getByRole('button', { name: 'Archive…' }))); -}); - -// ---- character import from a character sheet PDF: a D&D Beyond export or the fillable 2014 sheet (features/ddb-pdf-import.md S4, item 14) ---- -// The committed sheet is invented: "Testy McFixture", an original fixture Arcanist 3 / Chanter 2 whose spell "Fixture Veil" -// is on both casters' lists. The DevHost has no Open dialog, so the file input sends the bytes (ddb.readData). - -const ddbSheet = () => readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-ddb-sheet.pdf')); - -async function startDdbImport(user: ReturnType) { - await user.click(await screen.findByRole('button', { name: '+ Add a character' })); - const sheet = await screen.findByRole('radio', { name: 'From a character sheet (PDF or text)' }); - await waitFor(() => expect(sheet.disabled).toBe(false)); // needs app.info - await user.click(sheet); - await user.click(screen.getByRole('button', { name: 'Continue' })); -} - -const wotcSheet = () => readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-wotc-sheet.pdf')); - -async function readDdbSheet(user: ReturnType) { - await user.click(await screen.findByRole('button', { name: 'Choose PDF…' })); - await user.upload(screen.getByLabelText('Character sheet PDF file'), new File([ddbSheet()], 'fixture-ddb-sheet.pdf', { type: 'application/pdf' })); - expect(await screen.findByText('Fixture Arcanist 3 / Fixture Chanter 2', {}, { timeout: 30000 })).toBeTruthy(); -} - -// ---- item 16 (D16(c)): unmatched features that carry text become reference drafts ---- - -async function toDdbSummary(user: ReturnType) { - await startDdbImport(user); - await readDdbSheet(user); - await nextWhenReady(user, 'Next: rules'); - await nextWhenReady(user, 'Next: matches'); - const matches = await screen.findByRole('region', { name: 'Matches' }); - const veil = await within(matches).findByRole('combobox', { name: 'Match for Fixture Veil' }); - await user.selectOptions(veil, '1'); // the option labels are the same for both casters once a character exists, so pick by position - await nextWhenReady(user, 'Next: numbers'); - await nextWhenReady(user, 'Next: summary'); -} - -/** Every revision (drafts too) in the import-derived source, from the call the studio uses; 0 while the source does not exist yet. */ -async function importSourceRevisions(): Promise { - const source = (await client.listSources()).find((s) => s.title === 'Characters imported from sheets'); - return source ? (await client.contentBySource(source.id)).reduce((n, entry) => n + entry.revisions.length, 0) : 0; -} - -/** The Cancel path: tick Publish at the summary, then Cancel; nothing is written (no source, no draft). Unmounts when done. */ -async function cancelAtSummary(user: ReturnType) { - const sources = (await client.listSources()).map((s) => s.id).sort(); - const revisions = await importSourceRevisions(); - const { unmount } = render(); - await toDdbSummary(user); - const section = await screen.findByRole('region', { name: 'Reference drafts' }); - await user.click(within(section).getByRole('checkbox', { name: /^Make these \d+ reference drafts available to characters$/ })); - - await user.click(screen.getByRole('button', { name: 'Cancel' })); - - await expectStatus(/Import cancelled\. Nothing was saved\./); - expect((await client.listSources()).map((s) => s.id).sort()).toEqual(sources); - expect(await importSourceRevisions()).toBe(revisions); - unmount(); -} - -// One test, Cancel path first and then a fresh import: the service does not draft an entry the import-derived source holds -// already (R106), so the drafts exist only for the first import of this sheet. No earlier test may import -// fixture-ddb-sheet.pdf before this one (and none does: the main import test below runs after it). -it('Cancel writes no reference drafts; a fresh import lists them unticked and publishing makes them studio content', async () => { - const user = userEvent.setup(); - await cancelAtSummary(user); - const revisions = await importSourceRevisions(); - render(); - await toDdbSummary(user); - - const section = await screen.findByRole('region', { name: 'Reference drafts' }); - expect(section.textContent).toContain('Fixture Steady Breath'); - expect(section.textContent).toContain('An invented line of fixture description.'); - const tick = within(section).getByRole('checkbox', { name: /^Make these \d+ reference drafts available to characters$/ }); - expect(tick.checked).toBe(false); - expect(within(section).getByRole('note').textContent).toContain('Features are kept as reference content in Homebrew; the gap notes stay on the character.'); - expect((await client.listContent('srd-5.1')).some((o) => o.name === 'Fixture Steady Breath')).toBe(false); - - await user.click(tick); - expect(document.activeElement).toBe(tick); - const create = await screen.findByRole('button', { name: 'Create character' }); - await waitFor(() => expect(create.disabled).toBe(false)); - await user.click(create); - - await expectStatus(/Character created from the character sheet/); - expect((await client.listContent('srd-5.1')).some((o) => o.name === 'Fixture Steady Breath')).toBe(true); - expect(await importSourceRevisions()).toBeGreaterThan(revisions); -}); - -it('imports a D&D Beyond sheet, resolves a choice, keeps one sheet number as an override and creates the character', async () => { - const user = userEvent.setup(); - render(); - await startDdbImport(user); - await readDdbSheet(user); - - await user.click(screen.getByRole('button', { name: 'Next: rules' })); - // The 2014-style layout suggests SRD 5.1; the user could pick the other family. - expect(screen.getByRole('radio', { name: /2014 rules/ }).checked).toBe(true); - await user.click(screen.getByRole('radio', { name: "Use the character sheet's values" })); // D16h preset - await user.click(screen.getByRole('button', { name: 'Next: matches' })); - - const matches = await screen.findByRole('region', { name: 'Matches' }); - const veil = await within(matches).findByRole('combobox', { name: 'Match for Fixture Veil' }); - await user.click(within(matches).getByRole('radio', { name: 'Needs a choice' })); - expect(within(matches).getAllByRole('rowheader').map((h) => h.textContent)).toEqual(['Fixture Veil']); - // The caster names come from content.list, which can answer after the rows show (more bundled packs make it slower). - const chanter = await waitFor(() => { - const option = within(veil).getAllByRole('option').find((o) => /Fixture Chanter/.test(o.textContent ?? '')); - expect(option).toBeDefined(); - return option!; - }); - await user.selectOptions(veil, chanter); - await waitFor(() => expect(within(matches).queryAllByRole('rowheader')).toHaveLength(0)); - // Not installed (the background, a feat, two items, the features): listed, and kept as gap notes. - await user.click(within(matches).getByRole('radio', { name: 'Not found' })); - expect(within(matches).getByRole('rowheader', { name: 'Fixture Archivist' })).toBeTruthy(); - - // Next waits while the proposal for the latest choice is loading. - const nextStep = async (name: string) => { - const next = screen.getByRole('button', { name }); - await waitFor(() => expect(next.disabled).toBe(false)); - await user.click(next); - }; - await nextStep('Next: numbers'); - const armorClass = await screen.findByRole('radiogroup', { name: 'Armor Class' }); - expect(within(screen.getByRole('radiogroup', { name: 'Armor Class' })).getByRole('radio', { name: "Keep the sheet's number" }).checked).toBe(true); // pre-filled by the preset - await user.click(within(armorClass).getByRole('radio', { name: "Keep the sheet's number" })); - await nextStep('Next: summary'); - - const create = await screen.findByRole('button', { name: 'Create character' }); - await waitFor(() => expect(create.disabled).toBe(false)); - await user.click(create); - - await expectStatus(/Character created from the character sheet: 3 numbers set by hand, \d+ gap note\(s\)/); - const sheet = await screen.findByRole('article', { name: 'Testy McFixture' }); - expect(summaryValue(sheet, 'Armor Class')).toContain('(set by hand)'); - await openTab(user, sheet, 'Skills and saves'); - expect(within(sheet).getByRole('heading', { name: /^Armor Class:/ }).textContent).toContain('set by hand (calculated'); -}); - -it('imports the fillable 2014 sheet through the same entry: the layout is named, prose lands in session notes and the details fill', async () => { - const user = userEvent.setup(); - render(); - await startDdbImport(user); - await user.click(await screen.findByRole('button', { name: 'Choose PDF…' })); - await user.upload(screen.getByLabelText('Character sheet PDF file'), new File([wotcSheet()], 'fixture-wotc-sheet.pdf', { type: 'application/pdf' })); - expect(await screen.findByText('Fixture Arcanist 3', {}, { timeout: 30000 })).toBeTruthy(); - expect(screen.getByText('the fillable 2014 sheet')).toBeTruthy(); - - const nextStep = async (name: string) => { - const next = await screen.findByRole('button', { name }); - await waitFor(() => expect(next.disabled).toBe(false)); - await user.click(next); - }; - await nextStep('Next: rules'); - await nextStep('Next: matches'); - await nextStep('Next: numbers'); - await nextStep('Next: summary'); - expect(await screen.findByRole('region', { name: 'Not brought over' })).toBeTruthy(); - const create = await screen.findByRole('button', { name: 'Create character' }); - await waitFor(() => expect(create.disabled).toBe(false)); - await user.click(create); - - await expectStatus(/Character created from the character sheet: \d+ numbers? set by hand, \d+ gap note\(s\)/); - const sheet = await screen.findByRole('article', { name: 'Testy McFixture' }); - await openTab(user, sheet, 'Journal'); - expect(await within(sheet).findByText(/Testy backstory\./)).toBeTruthy(); - expect(within(within(sheet).getByRole('form', { name: 'Details' })).getByRole('textbox', { name: 'Alignment' }).value).toBe('Fixture Neutral'); -}); - -it('cancelling the D&D Beyond import at each step leaves the character list unchanged', async () => { - const user = userEvent.setup(); - const before = (await client.listCharacters()).map((c) => c.id).sort(); - render(); - const next = ['Next: rules', 'Next: matches', 'Next: numbers', 'Next: summary']; - - for (let step = 1; step <= 5; step++) { - await startDdbImport(user); - await readDdbSheet(user); - for (const label of next.slice(0, step - 1)) { - const button = await screen.findByRole('button', { name: label }); - await waitFor(() => expect(button.disabled).toBe(false)); - await user.click(button); - } - await screen.findByRole('heading', { name: ['Choose the sheet', 'Rules and campaign', 'Matches', 'Numbers', 'Create'][step - 1] }); - await user.click(screen.getByRole('button', { name: 'Cancel' })); - await waitFor(() => expect(screen.queryByRole('button', { name: 'Choose PDF…' })).toBeNull()); - await waitFor(() => expect(screen.queryByRole('heading', { name: 'Create' })).toBeNull()); - await expectStatus(/Import cancelled\. Nothing was saved\./); - } - - expect((await client.listCharacters()).map((c) => c.id).sort()).toEqual(before); -}); - -// ---- item 19a (D37): character import from pasted or file text ---- -// The text is invented. "Barbarian 1" is an installed SRD class with no choice to answer at level 1. - -const fixtureText = [ - '# Testy Texter', - 'Class: Barbarian 1', - 'STR 16 DEX 14 CON 14 INT 8 WIS 9 CHA 10', - 'Gold: 12', - 'Languages: Common, Fixturish', - 'Some line the reader cannot place', -].join('\n'); - -it('imports a character from pasted text: the unreadable line is listed and kept as a session note, and a too-large file is refused by size', async () => { - const user = userEvent.setup(); - render(); - await startDdbImport(user); - - await user.click(await screen.findByRole('button', { name: 'Import a character from text…' })); - const box = await screen.findByRole('textbox', { name: 'Character text' }); - await waitFor(() => expect(document.activeElement).toBe(box)); - - // A file over the limit is refused by its size alone, before any of it is read. - const big = new File(['x'], 'big-fixture.txt', { type: 'text/plain' }); - Object.defineProperty(big, 'size', { value: 300_000 }); - await user.upload(screen.getByLabelText('Character text file'), big); - expect((await screen.findByRole('alert')).textContent).toContain('300,000'); - expect(box.value).toBe(''); - - await user.click(box); - await user.paste(fixtureText); - await user.click(screen.getByRole('button', { name: 'Read the text' })); - expect(await screen.findByText('pasted or file text')).toBeTruthy(); - - await nextWhenReady(user, 'Next: rules'); - await nextWhenReady(user, 'Next: matches'); - await nextWhenReady(user, 'Next: numbers'); - await nextWhenReady(user, 'Next: summary'); - const notRead = await screen.findByRole('region', { name: 'Lines not read' }); - expect(notRead.textContent).toContain('Some line the reader cannot place'); - const tick = within(notRead).getByRole('checkbox', { name: 'Keep the lines that were not read as session notes' }); - expect(tick.checked).toBe(true); - - const create = await screen.findByRole('button', { name: 'Create character' }); - await waitFor(() => expect(create.disabled).toBe(false)); - await user.click(create); - - await expectStatus(/Character created from the character sheet/); - const sheet = await screen.findByRole('article', { name: 'Testy Texter' }); - await openTab(user, sheet, 'Journal'); - expect(await within(sheet).findByText(/Some line the reader cannot place/)).toBeTruthy(); -}); - -// ---- item 19b (D37, ADR-013): a PDF with no form fields is read as text through the same entry ---- -// The committed sheet is a generated text-only PDF (no form): "Testy Printout", an invented Fixture Arcanist 3. - -const textSheet = () => readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-text-sheet.pdf')); - -it('imports a PDF that has no form fields: its page text is read, the layout says so, and the character is created', async () => { - const user = userEvent.setup(); - render(); - await startDdbImport(user); - await user.click(await screen.findByRole('button', { name: 'Choose PDF…' })); - await user.upload(screen.getByLabelText('Character sheet PDF file'), new File([textSheet()], 'fixture-text-sheet.pdf', { type: 'application/pdf' })); - expect(await screen.findByText('Fixture Arcanist 3', {}, { timeout: 30000 })).toBeTruthy(); - expect(screen.getByText('text from the PDF')).toBeTruthy(); - - await nextWhenReady(user, 'Next: rules'); - await nextWhenReady(user, 'Next: matches'); - await nextWhenReady(user, 'Next: numbers'); - await nextWhenReady(user, 'Next: summary'); - const create = await screen.findByRole('button', { name: 'Create character' }); - await waitFor(() => expect(create.disabled).toBe(false)); - await user.click(create); - - await expectStatus(/Character created from the character sheet/); - expect(await screen.findByRole('article', { name: 'Testy Printout' })).toBeTruthy(); -}); - -// ---- item 15 (D35): a class the sheet names that TomeStack does not have, offered as a homebrew class ---- -// The generated sheet names the invented "Fixture Tinkerer" 3 with hit dice 3d8; no installed content has it. - -const tinkererSheet = () => readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-tinkerer-sheet.pdf')); - -async function readTinkererSheet(user: ReturnType) { - await user.click(await screen.findByRole('button', { name: 'Choose PDF…' })); - await user.upload(screen.getByLabelText('Character sheet PDF file'), new File([tinkererSheet()], 'fixture-tinkerer-sheet.pdf', { type: 'application/pdf' })); - expect(await screen.findByText('Fixture Tinkerer 3', {}, { timeout: 30000 })).toBeTruthy(); -} - -async function nextWhenReady(user: ReturnType, name: string) { - const next = await screen.findByRole('button', { name }); - await waitFor(() => expect(next.disabled).toBe(false)); - await user.click(next); -} - -it('creates a draft homebrew class from an uninstalled class, leaves Publish it unticked and the character gets nothing from it', async () => { - const user = userEvent.setup(); - const before = new Set((await client.listCharacters()).map((c) => c.id)); - render(); - await startDdbImport(user); - await readTinkererSheet(user); - await nextWhenReady(user, 'Next: rules'); - await nextWhenReady(user, 'Next: matches'); - - const matches = await screen.findByRole('region', { name: 'Matches' }); - const box = await within(matches).findByRole('checkbox', { name: /Create a homebrew class Fixture Tinkerer/ }); - expect(box.getAttribute('aria-disabled')).toBeNull(); - await user.click(box); - await waitFor(() => expect(within(matches).getByRole('checkbox', { name: /Create a homebrew class/ }).checked).toBe(true)); - await waitFor(() => expect(within(matches).getByText(/A homebrew class is created for it/)).toBeTruthy()); - - await nextWhenReady(user, 'Next: numbers'); - await nextWhenReady(user, 'Next: summary'); - const stub = await screen.findByRole('region', { name: 'Homebrew class to create' }); - for (const text of ['Fixture Tinkerer', 'd8', 'Strength', 'Characters imported from sheets']) expect(stub.textContent).toContain(text); - expect(within(stub).getByRole('checkbox', { name: 'Make it available to characters' }).checked).toBe(false); - expect(within(stub).getByRole('note').textContent).toBe('The class is a draft: the character gets nothing from it until you make it available to characters in Homebrew and accept the update on the character.'); - - const create = await screen.findByRole('button', { name: 'Create character' }); - await waitFor(() => expect(create.disabled).toBe(false)); - await user.click(create); - - await expectStatus(/Character created from the character sheet/); - await screen.findByRole('article', { name: 'Testy Tinker' }); - const created = (await client.listCharacters()).find((c) => !before.has(c.id) && c.name === 'Testy Tinker')!; - const view = await client.getCharacter(created.id); - expect(view.sheet.diagnostics.map((d) => d.code)).toContain('content.unpublished'); - const source = (await client.listSources()).find((s) => s.title === 'Characters imported from sheets')!; - expect(source.importDerived).toBe(true); - expect(source.redistributable).toBe(false); -}); - -it('cancelling after choosing to create a homebrew class writes nothing: no character, no source', async () => { - const user = userEvent.setup(); - const characters = (await client.listCharacters()).map((c) => c.id).sort(); - const sources = (await client.listSources()).map((s) => s.id).sort(); - render(); - await startDdbImport(user); - await readTinkererSheet(user); - await nextWhenReady(user, 'Next: rules'); - await nextWhenReady(user, 'Next: matches'); - const matches = await screen.findByRole('region', { name: 'Matches' }); - await user.click(await within(matches).findByRole('checkbox', { name: /Create a homebrew class Fixture Tinkerer/ })); - await waitFor(() => expect(within(matches).getByRole('checkbox', { name: /Create a homebrew class/ }).checked).toBe(true)); - await nextWhenReady(user, 'Next: numbers'); - await nextWhenReady(user, 'Next: summary'); - await screen.findByRole('region', { name: 'Homebrew class to create' }); - - await user.click(screen.getByRole('button', { name: 'Cancel' })); - - await expectStatus(/Import cancelled\. Nothing was saved\./); - expect((await client.listCharacters()).map((c) => c.id).sort()).toEqual(characters); - expect((await client.listSources()).map((s) => s.id).sort()).toEqual(sources); - // No draft check here: no client call lists drafts without a content id, and listContent shows published content only. - // DdbStubClassTests (cancel at every step) counts sources, revisions, characters and notes. -}); - -it('keeps the theme picked in Settings when the app is rendered again (ADR-015)', async () => { - const user = userEvent.setup(); - const { unmount } = render(); - await user.click(await screen.findByRole('button', { name: 'Settings' })); - await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('heading', { level: 1, name: 'Settings' }))); - await user.click(screen.getByRole('radio', { name: 'Violet' })); - expect(document.documentElement.dataset.theme).toBe('violet'); - await user.click(screen.getByRole('radio', { name: 'Dark' })); - expect(document.documentElement.dataset.appearance).toBe('dark'); - await user.selectOptions(screen.getByRole('combobox', { name: 'Text size' }), '125'); - expect(document.documentElement.dataset.textSize).toBe('125'); - unmount(); - // so the final check proves the mount effect re-applied the saved preferences - delete document.documentElement.dataset.theme; - delete document.documentElement.dataset.appearance; - delete document.documentElement.dataset.textSize; - render(); - await screen.findByRole('button', { name: 'Settings' }); - expect(document.documentElement.dataset.theme).toBe('violet'); - expect(document.documentElement.dataset.appearance).toBe('dark'); - expect(document.documentElement.dataset.textSize).toBe('125'); -}); - -it('keeps the Custom accent and its hue when the app is rendered again, and a preset replaces it (D40)', async () => { - const user = userEvent.setup(); - const { unmount } = render(); - await user.click(await screen.findByRole('button', { name: 'Settings' })); - await user.click(screen.getByRole('radio', { name: 'Custom accent' })); - const slider = screen.getByRole('slider', { name: 'Accent hue' }); - fireEvent.change(slider, { target: { value: '120' } }); - expect(slider.getAttribute('aria-valuetext')).toBe('Lime, 120 degrees'); - expect(document.documentElement.dataset.theme).toBe('custom'); - unmount(); - delete document.documentElement.dataset.theme; - render(); - await screen.findByRole('button', { name: 'Settings' }); - expect(document.documentElement.dataset.theme).toBe('custom'); - await user.click(screen.getByRole('button', { name: 'Settings' })); - expect(screen.getByRole('slider', { name: 'Accent hue' }).value).toBe('120'); - await user.click(screen.getByRole('radio', { name: 'Tide' })); - expect(screen.queryByRole('slider')).toBeNull(); - expect(document.documentElement.dataset.theme).toBe('tide'); -}); - -it('hides and shows the sidebar from the header and by Ctrl+B, moves focus out of a hidden sidebar, and remembers the state (ADR-015)', async () => { - const user = userEvent.setup(); - const { unmount } = render(); - const toggle = await screen.findByRole('button', { name: 'Hide sidebar' }); - expect(toggle.getAttribute('aria-expanded')).toBe('true'); - expect(screen.getByRole('navigation', { name: 'Main' })).toBeTruthy(); - - await user.click(toggle); - expect(screen.getByRole('button', { name: 'Show sidebar' }).getAttribute('aria-expanded')).toBe('false'); - expect(screen.queryByRole('navigation', { name: 'Main' })).toBeNull(); - - await user.keyboard('{Control>}b{/Control}'); - expect(screen.getByRole('navigation', { name: 'Main' })).toBeTruthy(); - - // Another keyboard layout: Ctrl + the physical B key reports a different character, so the shortcut follows `code`. - fireEvent.keyDown(document, { key: 'и', code: 'KeyB', ctrlKey: true }); - expect(screen.queryByRole('navigation', { name: 'Main' })).toBeNull(); - fireEvent.keyDown(document, { key: 'и', code: 'KeyB', ctrlKey: true }); - expect(screen.getByRole('navigation', { name: 'Main' })).toBeTruthy(); - - // Owner (2026-10-12): the header toggle is the only close control; the sidebar has none of its own. - expect(screen.queryByRole('button', { name: 'Close sidebar' })).toBeNull(); - expect(within(screen.getByRole('navigation', { name: 'Main' })).getByRole('list', { name: 'Characters' })).toBeTruthy(); - - // Focus inside the sidebar, then hide it by the shortcut: focus must land on the toggle, not on . - screen.getByRole('button', { name: '+ Add a character' }).focus(); - await user.keyboard('{Control>}b{/Control}'); - await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Show sidebar' }))); - - unmount(); - render(); - expect(await screen.findByRole('button', { name: 'Show sidebar' })).toBeTruthy(); - expect(screen.queryByRole('navigation', { name: 'Main' })).toBeNull(); - await user.click(screen.getByRole('button', { name: 'Show sidebar' })); - expect(localStorage.getItem('tomestack.sidebar')).toBeNull(); - - // A focused checkbox or radio must not block the shortcut (WCAG 2.1.1); a text field keeps Ctrl+B. - await user.click(screen.getByRole('button', { name: 'Settings' })); - for (const control of [screen.getByRole('checkbox', { name: 'Animate dice' }), screen.getByRole('radio', { name: 'Violet' })]) { - control.focus(); - await user.keyboard('{Control>}b{/Control}'); - expect(screen.queryByRole('navigation', { name: 'Main' })).toBeNull(); - await user.keyboard('{Control>}b{/Control}'); - expect(screen.getByRole('navigation', { name: 'Main' })).toBeTruthy(); - } - await startNewCharacter(user); - const name = await screen.findByRole('textbox', { name: /^Name/ }); - name.focus(); - await user.keyboard('{Control>}b{/Control}'); - expect(screen.getByRole('navigation', { name: 'Main' })).toBeTruthy(); // ignored in a text field -}); - -it('opens the Characters home screen with a card per character and opens one from it (D25)', async () => { - const user = userEvent.setup(); - render(); - const home = await screen.findByRole('region', { name: 'Your characters' }); // the start screen - expect(within(home).getByRole('heading', { level: 1, name: 'Your characters' })).toBeTruthy(); - const cards = await within(home).findAllByRole('listitem'); // earlier tests created characters - expect(cards.length).toBeGreaterThan(0); - expect(within(home).getByRole('list', { name: 'Characters' })).toBeTruthy(); - const first = cards[0]!; - const name = within(first).getByRole('button', { name: /^Open / }).textContent!.replace(/^Open /, ''); - expect(first.textContent).toMatch(/Level \d+/); - await user.click(within(first).getByRole('button', { name: `Open ${name}` })); - expect(await screen.findByRole('article', { name })).toBeTruthy(); - await goHome(user); - const back = await screen.findByRole('region', { name: 'Your characters' }); - await waitFor(() => expect(document.activeElement).toBe(within(back).getByRole('heading', { level: 1, name: 'Your characters' }))); -}); - -it('creates a character with the standard array (D32)', async () => { - const user = userEvent.setup(); - render(); - await createCharacter(user, { name: 'E2E Array', family: 'srd-5.2.1', cls: /^Barbarian/ }); - await user.click(await screen.findByRole('button', { name: 'Create and save' })); - const sheet = await screen.findByRole('article', { name: 'E2E Array' }); - await openTab(user, sheet, 'Skills and saves'); - expect(within(sheet).getByRole('heading', { name: /^Strength score: 15/ })).toBeTruthy(); - expect(within(sheet).getByRole('heading', { name: /^Charisma score: 8/ })).toBeTruthy(); -}); - -it('rolls ability scores through the dice engine and assigns them (D32)', async () => { - const user = userEvent.setup(); - render(); - await startNewCharacter(user); - await user.type(await screen.findByRole('textbox', { name: 'Name' }), 'E2E Rolled'); - await user.click(screen.getByRole('radio', { name: /2024 rules/ })); - await user.click(screen.getByRole('button', { name: 'Next: class' })); - await user.click(await screen.findByRole('radio', { name: /^Barbarian/ })); - await user.click(screen.getByRole('button', { name: 'Next: ability scores' })); - await user.click(screen.getByRole('radio', { name: 'Roll' })); - await user.click(screen.getByRole('button', { name: 'Roll six scores (4d6, drop the lowest)' })); - const sets = await screen.findByRole('list', { name: 'Rolled sets' }); - const lines = within(sets).getAllByRole('listitem').map((li) => li.textContent!); - expect(lines).toHaveLength(6); - // Each line's total is the sum of the three kept dice (the fourth is dropped). - const totals: number[] = []; - for (const line of lines) { - const m = /^Roll \d: (\d+) \((\d), (\d), (\d), dropped (\d)\)$/.exec(line); - expect(m, line).not.toBeNull(); - const [total, a, b, c, dropped] = m!.slice(1).map(Number) as [number, number, number, number, number]; - expect(total).toBe(a + b + c); - expect(dropped).toBeLessThanOrEqual(Math.min(a, b, c)); - totals.push(total); - } - const group = screen.getByRole('group', { name: 'Assign the rolled scores' }); - const assigned = new Map(); - for (const label of ['Strength', 'Dexterity', 'Constitution', 'Intelligence', 'Wisdom', 'Charisma'] as const) { - const select = within(group).getByRole('combobox', { name: label }); - const free = within(select).getAllByRole('option').find((o) => !(o as HTMLOptionElement).disabled && o.textContent !== 'Choose')!; - await user.selectOptions(select, (free as HTMLOptionElement).value); - assigned.set(label, Number((free as HTMLOptionElement).value)); - } - expect(screen.getByText('Assigned: 6 of 6')).toBeTruthy(); - expect([...assigned.values()].sort((x, y) => x - y)).toEqual([...totals].sort((x, y) => x - y)); // every rolled total used once - await user.click(screen.getByRole('button', { name: 'Next: species' })); - await user.click(screen.getByRole('button', { name: 'Next: background' })); - await user.click(screen.getByRole('button', { name: 'Next: gear' })); - await user.click(screen.getByRole('button', { name: /^Skip: I'll add gear myself/ })); - await user.click(screen.getByRole('button', { name: 'Next: choices' })); - await user.click(await screen.findByRole('button', { name: 'Create and save' })); - const sheet = await screen.findByRole('article', { name: 'E2E Rolled' }); - await openTab(user, sheet, 'Skills and saves'); - // The sheet's base scores are the assigned rolled totals (increases come from content the draft does not pin). - for (const [label, value] of assigned) expect(within(sheet).getByRole('heading', { name: new RegExp(`^${label} score: ${value}\\b`) })).toBeTruthy(); -}); - -it('shows the Bloodied chip and switches an auto toggle on at half hit points, and Undo takes both away (item 20, D38)', async () => { - const user = userEvent.setup(); - // Setup through the client: a homebrew feat (content schema v10) whose toggle switches itself while bloodied, and a character with 20 hit points. - const source = await client.createHomebrewSource('E2E Grit Book', ['srd-5.2.1']); - const draft = await client.saveDraft({ - contentId: crypto.randomUUID(), - revisionId: '00000000-0000-0000-0000-000000000000', - kind: 'feat', - name: 'E2E Grit', - rulesFamilies: ['srd-5.2.1'], - provenance: { sourceId: source.id }, - status: 'draft', - effects: [ - { type: 'toggle', id: 'grit-toggle', toggleId: 'grit', label: 'E2E grit', autoWhen: 'bloodied' }, - { type: 'modifier', id: 'grit-ac', operation: 'bonus', target: 'armorClass', value: '2', timing: 'whileActive', toggle: 'grit' }, - ], - }); - const feat = (await client.publish(draft)).published; - const created = await client.createCharacter({ name: 'E2E Grit Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [feat] }); - await client.saveCharacter({ ...created.character, overrides: [{ field: 'hitPoints', value: 20 }] }); - - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Grit Hero/ })); - const sheet = await screen.findByRole('article', { name: 'E2E Grit Hero' }); - await openTab(user, sheet, 'Play'); - const summary = () => within(sheet).getByRole('region', { name: 'Status' }); - const effects = () => within(screen.getByRole('region', { name: 'Attacks and actions' })).getByRole('group', { name: /Active effects/ }); - const armorClass = summaryValue(sheet, 'Armor Class'); - expect(within(summary()).queryByText('Bloodied')).toBeNull(); - expect(effects().textContent).toMatch(/E2E grit.*On while bloodied \(off now\)/); - expect(within(effects()).queryByRole('checkbox')).toBeNull(); // no switch: the sheet decides - - // Damage to exactly half (10 of 20): the chip, the toggle and its +2 Armor Class. - const hpPanel = () => screen.getByRole('region', { name: /^Hit points:/ }); - await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '10'); - await user.click(within(hpPanel()).getByRole('button', { name: 'Take damage' })); - await waitFor(() => expect(within(summary()).getByText('Bloodied')).toBeTruthy()); - expect(effects().textContent).toMatch(/On while bloodied \(on now\)/); - expect(Number(summaryValue(sheet, 'Armor Class'))).toBe(Number(armorClass) + 2); - - // Undo puts the hit points back exactly; the chip, the toggle and the bonus go with them. - await user.click(await screen.findByRole('button', { name: 'Undo last change: damage 10' })); - await waitFor(() => expect(within(summary()).queryByText('Bloodied')).toBeNull()); - expect(effects().textContent).toMatch(/On while bloodied \(off now\)/); - expect(summaryValue(sheet, 'Armor Class')).toBe(armorClass); -}); - -it('lists a toggle and a resource with an activation under their group, and switching the toggle keeps focus on it (item 22, R157)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Reflex Book', ['srd-5.2.1']); - const draft = await client.saveDraft({ - contentId: crypto.randomUUID(), - revisionId: '00000000-0000-0000-0000-000000000000', - kind: 'feat', - name: 'E2E Reflex', - rulesFamilies: ['srd-5.2.1'], - provenance: { sourceId: source.id }, - status: 'draft', - effects: [ - { type: 'toggle', id: 'guard-toggle', toggleId: 'guard', label: 'E2E guard', activation: 'reaction' }, - { type: 'modifier', id: 'guard-ac', operation: 'bonus', target: 'armorClass', value: '2', timing: 'whileActive', toggle: 'guard' }, - { type: 'toggle', id: 'calm-toggle', toggleId: 'calm', label: 'E2E calm' }, - { type: 'resource', id: 'surge-resource', resourceId: 'surge', label: 'E2E surge', maximum: '2', activation: 'bonusAction' }, - ], - }); - const feat = (await client.publish(draft)).published; - await client.createCharacter({ name: 'E2E Reflex Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [feat] }); - - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Reflex Hero/ })); - const sheet = await screen.findByRole('article', { name: 'E2E Reflex Hero' }); - await openTab(user, sheet, 'Play'); - const actions = () => screen.getByRole('region', { name: 'Attacks and actions' }); - const armorClass = summaryValue(sheet, 'Armor Class'); - - expect(within(within(actions()).getByRole('group', { name: /Active effects/ })).getByRole('checkbox', { name: /E2E calm/ })).toBeTruthy(); // no activation: stays - expect(within(within(actions()).getByRole('group', { name: /Active effects/ })).queryByRole('checkbox', { name: /E2E guard/ })).toBeNull(); - const resources = within(sheet).getByRole('region', { name: 'Resources' }); - expect(within(within(resources).getByRole('region', { name: 'Bonus actions' })).getByRole('heading', { name: /^E2E surge: 2 of 2/ })).toBeTruthy(); - - await user.click(within(within(actions()).getByRole('region', { name: 'Reactions' })).getByRole('checkbox', { name: /E2E guard/ })); - await waitFor(() => expect(Number(summaryValue(sheet, 'Armor Class'))).toBe(Number(armorClass) + 2)); - const guard = within(within(actions()).getByRole('region', { name: 'Reactions' })).getByRole('checkbox', { name: /E2E guard/ }) as HTMLInputElement; - expect(guard.checked).toBe(true); - expect(document.activeElement).toBe(guard); -}); - -it('carries two copies of a charged wand that needs attunement: attuning applies it, charges are separate, and a long rest returns them by the rolled total (item 25)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Wand Book', ['srd-5.2.1']); - const draft = await client.saveDraft({ - contentId: crypto.randomUUID(), - revisionId: '00000000-0000-0000-0000-000000000000', - kind: 'item', - name: 'E2E Wand', - rulesFamilies: ['srd-5.2.1'], - provenance: { sourceId: source.id }, - status: 'draft', - effects: [ - { type: 'modifier', id: 'wand-ac', operation: 'bonus', target: 'armorClass', value: '2' }, - { type: 'item', id: 'wand-use', requiresAttunement: true, charges: { max: 3, recovery: { period: 'longRest', regain: '1d3' } } }, - ], - }); - await client.publish(draft); - await client.createCharacter({ name: 'E2E Wand Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [] }); - - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Wand Hero/ })); - const hero = await screen.findByRole('article', { name: 'E2E Wand Hero' }); - await openTab(user, hero, 'Gear'); - const equipment = () => screen.getByRole('region', { name: 'Equipment' }); - const armorClass = () => Number(/^(\d+)/.exec(summaryValue(hero, 'Armor Class'))![1]); - const before = armorClass(); - - // Two copies: an item with charges is offered again once it is carried. - for (const copies of [1, 2]) { - await waitFor(() => expect(within(equipment()).getByRole('option', { name: /^E2E Wand/ })).toBeTruthy()); - await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^E2E Wand/ })); - await user.click(within(equipment()).getByRole('button', { name: 'Add' })); - await waitFor(() => expect(within(equipment()).getAllByRole('checkbox', { name: /^Equip E2E Wand/ })).toHaveLength(copies)); - } - expect(within(equipment()).getAllByText('3 of 3 charges left')).toHaveLength(2); // carried: charges show on Inventory too - - // Equipped but not attuned: nothing applies, and the sheet says so. Attuning applies it once. - await user.click(within(equipment()).getByRole('checkbox', { name: 'Equip E2E Wand (copy 1 of 2)' })); - await within(equipment()).findByText('E2E Wand (copy 1 of 2) is not attuned, so its effects do not apply.'); - expect(armorClass()).toBe(before); - await user.click(within(equipment()).getByRole('checkbox', { name: 'Attuned: E2E Wand (copy 1 of 2)' })); - await waitFor(() => expect(armorClass()).toBe(before + 2)); - - // Separate counts; focus stays on the button that was pressed. - const spend = () => within(equipment()).getByRole('button', { name: 'Spend a charge: E2E Wand (copy 1 of 2)' }); - await user.click(spend()); - await user.click(spend()); - await waitFor(() => expect(within(equipment()).getByText('1 of 3 charges left')).toBeTruthy()); - expect(within(equipment()).getByText('3 of 3 charges left')).toBeTruthy(); - expect(document.activeElement).toBe(spend()); - - // A long rest asks for the 1d3, takes the total as rolled at the table, and returns that many (capped at the two spent). - await user.click(screen.getByRole('button', { name: 'Long rest…' })); - const rest = await screen.findByRole('region', { name: 'Long rest' }); - await user.type(await within(rest).findByLabelText('E2E Wand: 1d3 rolled at the table (total)'), '2'); - await user.click(within(rest).getByRole('button', { name: 'Add the 1d3 total: E2E Wand' })); - expect(await within(rest).findByRole('checkbox', { name: /^E2E Wand charges: 1 → 3/ })).toBeTruthy(); - const finish = within(rest).getByRole('button', { name: 'Finish long rest' }); - await waitFor(() => expect(finish.getAttribute('aria-disabled')).toBe('false')); - await user.click(finish); - - await waitFor(() => expect(screen.queryByRole('region', { name: 'Long rest' })).toBeNull()); - await openTab(user, hero, 'Gear'); - await waitFor(() => expect(within(equipment()).getAllByText('3 of 3 charges left')).toHaveLength(2)); -}); - -it('adds a companion on Play, damages it, undoes that exactly, and rolls its attack (item 23, D39)', async () => { - const user = userEvent.setup(); - await client.createCharacter({ name: 'E2E Handler', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [] }); - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Handler/ })); - const hero = await screen.findByRole('article', { name: 'E2E Handler' }); - await openTab(user, hero, 'Play'); - - const companions = () => screen.getByRole('region', { name: 'Companions' }); - await user.click(within(companions()).getByRole('button', { name: 'Add a companion' })); - await user.type(within(companions()).getByRole('textbox', { name: 'Name' }), 'Testy Hound'); - await user.clear(within(companions()).getByRole('spinbutton', { name: 'Hit point maximum' })); - await user.type(within(companions()).getByRole('spinbutton', { name: 'Hit point maximum' }), '20'); - await user.click(within(companions()).getByRole('button', { name: 'Add an attack line' })); - await user.type(within(companions()).getByRole('textbox', { name: 'Attack 1 name' }), 'Testy Bite'); - await user.clear(within(companions()).getByRole('spinbutton', { name: 'Attack 1 to hit bonus' })); - await user.type(within(companions()).getByRole('spinbutton', { name: 'Attack 1 to hit bonus' }), '4'); - await user.type(within(companions()).getByRole('textbox', { name: 'Attack 1 damage (optional)' }), '1d6+2'); - await user.click(within(companions()).getByRole('button', { name: 'Save companion' })); - await expectStatus(/^Added Testy Hound\.$/); - - // Damage goes through the play command; the card shows it and Undo puts the hit points back exactly. - const dog = () => screen.getByRole('region', { name: 'Testy Hound' }); - await user.type(within(dog()).getByRole('spinbutton', { name: 'Amount' }), '8'); - await user.click(within(dog()).getByRole('button', { name: /^Take damage/ })); - await waitFor(() => expect(within(dog()).getByText('Hit points: 12 of 20')).toBeTruthy()); - expect(document.activeElement).toBe(within(dog()).getByRole('button', { name: /^Take damage/ })); - await user.click(await screen.findByRole('button', { name: 'Undo last change: companion damage 8' })); - await waitFor(() => expect(within(dog()).getByText('Hit points: 20 of 20')).toBeTruthy()); - - // Set temporary hit points, then damage takes them first. - await user.type(within(dog()).getByRole('spinbutton', { name: 'Amount' }), '5'); - await user.click(within(dog()).getByRole('button', { name: /^Set temporary hit points/ })); - await waitFor(() => expect(within(dog()).getByText('Hit points: 20 of 20, 5 temporary')).toBeTruthy()); - await user.type(within(dog()).getByRole('spinbutton', { name: 'Amount' }), '7'); - await user.click(within(dog()).getByRole('button', { name: /^Take damage/ })); - await waitFor(() => expect(within(dog()).getByText('Hit points: 18 of 20')).toBeTruthy()); - - // Its attack rolls through the dice engine and shows in Last roll like an attack of your own. - await user.click(within(dog()).getByRole('button', { name: /^Roll Testy Bite attack/ })); - const lastRoll = screen.getByRole('status', { name: 'Last roll' }); - await waitFor(() => expect(lastRoll.textContent).toMatch(/Testy Hound: Testy Bite attack: \d+ \(1d20\)/)); - expect(lastRoll.textContent).toMatch(/Testy Bite to hit \+4/); - await user.click(within(dog()).getByRole('button', { name: /^Roll Testy Bite damage/ })); - await waitFor(() => expect(lastRoll.textContent).toMatch(/Testy Hound: Testy Bite damage: \d+ \(1d6\+2\)/)); -}); - -it('previews a Fighter 3 at level 5 from the level-up step: Extra Attack shows and nothing is saved (D82)', async () => { - const user = userEvent.setup(); - const created = await client.createCharacter({ - name: 'E2E Previewer', - rulesFamily: 'srd-5.2.1', - baseAbilities: { str: 16, dex: 14, con: 14, int: 10, wis: 12, cha: 8 }, - pins: [srd(1), srd(2)], - classes: [{ class: fighter(0), level: 3 }], - choices: [{ source: srd(2), choiceId: 'soldier-ability-scores', selected: [srd(4)] }], - }); - const before = (await client.getCharacter(created.character.id)).character; - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Previewer/ })); - await user.click(within(await screen.findByRole('article', { name: 'E2E Previewer' })).getByRole('button', { name: 'Level up' })); - - const form = await screen.findByRole('form', { name: 'Preview at level' }); - const level = within(form).getByRole('spinbutton', { name: 'Level to preview' }); - await user.clear(level); - await user.type(level, '5'); - await user.click(within(form).getByRole('button', { name: 'Preview' })); - const preview = await screen.findByRole('region', { name: 'Preview at level 5' }); - expect(within(preview).getByText('Extra Attack')).toBeTruthy(); - await user.click(within(preview).getByRole('button', { name: 'Close preview' })); - expect(screen.queryByRole('region', { name: 'Preview at level 5' })).toBeNull(); - - await user.click(screen.getByRole('button', { name: 'Cancel' })); - await expectStatus(/Draft discarded/); - const after = (await client.getCharacter(created.character.id)).character; - expect(after.level).toBe(3); - expect(after).toEqual(before); // the store received no write -}); - -it('levels a Cleric into Wizard: what each class gives, the prerequisite warning that never blocks, and the new class on the sheet (D99)', async () => { - const user = userEvent.setup(); - const listed = await client.listContent('srd-5.2.1'); - const named = (kind: string, name: RegExp) => listed.find((o) => o.compatible && !o.superseded && o.kind === kind && name.test(o.name))!.reference; // the list holds both families - const wizard = named('class', /^Wizard/); - const created = await client.createCharacter({ - name: 'E2E Multiclasser', - rulesFamily: 'srd-5.2.1', - baseAbilities: { str: 10, dex: 12, con: 14, int: 8, wis: 15, cha: 10 }, - pins: [named('species', /^Dwarf/), named('background', /^Soldier/)], - classes: [{ class: named('class', /^Cleric/), level: 1 }], - }); - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Multiclasser/ })); - await user.click(within(await screen.findByRole('article', { name: 'E2E Multiclasser' })).getByRole('button', { name: 'Level up' })); - - // The character's own class says what it gives at its next level; the new class waits behind "Another class…". - expect(await screen.findByRole('radio', { name: /^Cleric 2 — what you get: / })).toBeTruthy(); - await user.click(await screen.findByRole('radio', { name: 'Another class…' })); - const select = await screen.findByRole('combobox', { name: 'Class to start' }); - await user.selectOptions(select, await within(select).findByRole('option', { name: 'Wizard' })); - expect(await screen.findByText('Wizard — needs Intelligence 13 (you have 8). You can still take it.')).toBeTruthy(); - - const next = screen.getByRole('button', { name: 'Next: choices' }); - expect(next.getAttribute('aria-disabled')).toBeNull(); // advice, never a block - await user.click(next); - await user.click(await screen.findByRole('button', { name: 'Save level-up' })); - - const sheet = await screen.findByRole('article', { name: 'E2E Multiclasser' }); - expect(within(sheet).getByText('Level 2')).toBeTruthy(); - const saved = (await client.getCharacter(created.character.id)).character; - expect(saved.classes.map((c) => [c.class.contentId, c.level])).toContainEqual([wizard.contentId, 1]); -}); - -it('tries the sample from the chooser, plays it and removes it (D95)', async () => { - const user = userEvent.setup(); - // The DevHost is shared, so Home is not empty here (the welcome card is covered by HomePanel's tests): the sample is reached - // through the chooser, which offers it while no sample exists. A leftover sample from a failed run is removed first. - for (const c of await client.listCharacters()) { - if (c.origin !== 'sample') continue; - try { - await client.deleteSample(c.id); - } catch (error) { - // Archiving it would hide "Try the sample" in the chooser, so the test cannot go on either way. - if (error instanceof TomeStackError && error.code === 'character.sample-has-snapshots') { - throw new Error('A leftover sample with snapshots is in the DevHost data; remove it by hand.', { cause: error }); - } - throw error; - } - } - - render(); - await user.click(await screen.findByRole('button', { name: '+ Add a character' })); - const choice = await screen.findByRole('radio', { name: /^Try the sample/ }); - await user.click(choice); - await user.click(screen.getByRole('button', { name: 'Continue' })); - - const sheet = await screen.findByRole('article', { name: 'Wren Ashdown' }); - expect(within(sheet).getByRole('tab', { name: 'Play' }).getAttribute('aria-selected')).toBe('true'); - await waitFor(() => expect(summaryValue(sheet, 'Armor Class')).toMatch(/^16/)); - expect(within(sheet).getByText('This is a sample character.')).toBeTruthy(); - - // Remove sample asks first: focus goes to Keep, Keep puts it back on Remove sample and leaves the character alone. - await user.click(within(sheet).getByRole('button', { name: 'Remove sample' })); - const dialog = await within(sheet).findByRole('alertdialog', { name: 'Remove Wren Ashdown?' }); - expect(within(dialog).getByText('Remove Wren Ashdown? This cannot be undone.')).toBeTruthy(); - await waitFor(() => expect(document.activeElement).toBe(within(dialog).getByRole('button', { name: 'Keep' }))); - await user.click(within(dialog).getByRole('button', { name: 'Keep' })); - expect(within(sheet).queryByRole('alertdialog')).toBeNull(); - expect(document.activeElement).toBe(within(sheet).getByRole('button', { name: 'Remove sample' })); - - await user.click(within(sheet).getByRole('button', { name: 'Remove sample' })); - await user.click(within(await within(sheet).findByRole('alertdialog')).getByRole('button', { name: 'Remove' })); - - // Back home, the sample is gone from the sidebar and from the service. - await waitFor(() => expect(screen.queryByRole('article', { name: 'Wren Ashdown' })).toBeNull()); - await waitFor(() => expect(screen.queryByRole('button', { name: /^Wren Ashdown/ })).toBeNull()); - expect((await client.listCharacters()).some((c) => c.origin === 'sample')).toBe(false); -}); - -it('builds a 2014 Cleric with its kit: seven steps, option a gives AC 16 with the shield, Mace on Play, the kit on Gear (Wave 3, D97)', async () => { - const user = userEvent.setup(); - render(); - let preview = ''; - await createCharacter(user, { - name: 'E2E Kitted', - family: 'srd-5.1', - scores: { Dexterity: 10 }, // scale mail 14 + 0 Dex + shield 2 - cls: /^Cleric/, - kit: true, - beforeChoices: async () => { - // The Gear step shows the live Armor Class for the kit as chosen (option a for every pick). - await waitFor(() => expect(screen.getByText(/^AC with this gear: 16/)).toBeTruthy()); - preview = screen.getByText(/^AC with this gear:/).textContent ?? ''; - }, - }); - expect(preview).toMatch(/16/); - await user.click(await screen.findByRole('button', { name: 'Create and save' })); - - const sheet = await screen.findByRole('article', { name: 'E2E Kitted' }); - await waitFor(() => expect(summaryValue(sheet, 'Armor Class')).toMatch(/^16/)); - await openTab(user, sheet, 'Play'); - expect(within(sheet).getAllByText(/Mace/).length).toBeGreaterThan(0); - await openTab(user, sheet, 'Gear'); - const equipment = screen.getByRole('region', { name: 'Equipment' }); - for (const item of [/Mace/, /Scale mail/, /Shield/]) expect(within(equipment).getAllByText(item).length).toBeGreaterThan(0); -}, 180_000); - -it('a 2024 class taking gold has coins and no kit items (Wave 3, D97)', async () => { - const user = userEvent.setup(); - render(); - await createCharacter(user, { - name: 'E2E Goldtaker', - family: 'srd-5.2.1', - cls: /^Barbarian/, - background: /^Soldier/, - kit: true, - beforeChoices: async () => { - // Option b of the Barbarian's kit is gold only, and so is the Soldier's. - const classKit = await screen.findByRole('region', { name: /^From your class/ }); - await user.click(within(classKit).getByRole('radio', { name: /Instead: 75 gp/ })); - const backgroundKit = screen.getByRole('region', { name: /^From your background/ }); - await user.click(within(backgroundKit).getByRole('radio', { name: /Instead: 50 gp/ })); - }, - }); - await user.click(await screen.findByRole('button', { name: 'Create and save' })); - - const sheet = await screen.findByRole('article', { name: 'E2E Goldtaker' }); - await openTab(user, sheet, 'Gear'); - const equipment = screen.getByRole('region', { name: 'Equipment' }); - expect(within(equipment).queryAllByRole('checkbox', { name: /^Equip / })).toHaveLength(0); - const gold = await screen.findByRole('spinbutton', { name: 'Gold (gp)' }); - expect(gold.value).toBe('125'); -}, 180_000); diff --git a/src/Ui/e2e/forms-play.e2e.tsx b/src/Ui/e2e/forms-play.e2e.tsx new file mode 100644 index 00000000..c9464b1d --- /dev/null +++ b/src/Ui/e2e/forms-play.e2e.tsx @@ -0,0 +1,471 @@ +// D43 forms and MECH-X items 1 and 2 against the real DevHost: survival and threshold hits, charges, pinned rolls, hit-point rolls and replaceable choices. +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, expect, it, vi } from 'vitest'; +import { App } from '../src/App'; +import { client } from '../src/api/client'; +import type { ContentReference, ContentRevision } from '../src/api/types'; +import { expectStatus, openTab } from './helpers'; + +vi.mock('../src/api/client', async (importOriginal) => { + const { inject } = await import('vitest'); + const { createHttpTransport } = await import('../src/api/transport'); + const original = await importOriginal(); + const { endpoint, token } = inject('devHost'); + return { ...original, client: original.createClient(createHttpTransport(endpoint, { 'X-TomeStack-Token': token })) }; +}); + +afterEach(cleanup); + +// ---- D43 S7: damage responses against the real DevHost ---- + +const fixtureFolder = () => resolve(process.cwd(), '../../tests/RulesFixtures'); + +/** The content ids of the responses pack, in the order they can be published (the pool and the form come first). */ +const responseContentOrder = ['70', '74', '71', '72', '73', '75', '76', '77'].map((n) => `6f0dc000-0000-4000-8000-0000000000${n}`); + +let responsesPack: Promise | undefined; + +/** + * Installs the responses fixture pack (`tests/RulesFixtures/fixture-pack-responses.json`) as one homebrew source, because the + * DevHost seeds only its older fixture packs. A draft gets a new revision id, so the class's grants of the six features (which + * name their revision ids) are left out and the character pins the features itself, as the fixture character does. Content ids + * stay, so the features' pool and form references still resolve. Once per run. + */ +function installResponsesPack(): Promise { + responsesPack ??= publishFixturePack('fixture-pack-responses.json', 'E2E Responses Book', responseContentOrder); + return responsesPack; +} + +/** Publishes a fixture pack's revisions, in the given content order, into a new homebrew source; the class's grants are left out. */ +async function publishFixturePack(file: string, title: string, order: string[]): Promise { + const pack = JSON.parse(readFileSync(resolve(fixtureFolder(), file), 'utf8')) as { revisions: ContentRevision[] }; + const source = await client.createHomebrewSource(title, ['srd-5.2.1']); + const published: ContentReference[] = []; + for (const contentId of order) { + const revision = pack.revisions.find((r) => r.contentId === contentId)!; + // A choice's options name revision ids that a draft does not keep either, so the class's choices are left out too. + const effects = revision.kind === 'class' ? revision.effects.filter((e) => e.type !== 'grant' && e.type !== 'choice') : revision.effects; + const draft = await client.saveDraft({ ...revision, status: 'draft', effects, provenance: { ...revision.provenance, sourceId: source.id } }); + const result = await client.publish(draft); + expect(result.report.errors).toEqual([]); + published.push(result.published); + } + return published; +} + +/** A level 8 Fixture Bulwark with the fixture character's scores, the six response features and the guard form pinned. */ +async function createBulwark(name: string): Promise { + const pins = await installResponsesPack(); + const fixture = JSON.parse(readFileSync(resolve(fixtureFolder(), 'characters/pm-bulwark-l8.json'), 'utf8')) as { baseAbilities: Record }; + const created = await client.createCharacter({ + name, + rulesFamily: 'srd-5.2.1', + baseAbilities: fixture.baseAbilities as never, + pins, + classes: [{ class: pins[0]!, level: 8 }], + }); + return created.character.id; +} + +async function openBulwark(user: ReturnType, name: string): Promise { + render(); + await user.click(await screen.findByRole('button', { name: new RegExp(`^${name}`) })); + const sheet = await screen.findByRole('article', { name }); + await openTab(user, sheet, 'Play'); + return sheet; +} + +const hitPointsOf = async (id: string) => (await client.getCharacter(id)).sheet.hitPoints!; + +it('a hit that would drop the character to 0 offers survival; choosing it leaves 1 HP and Undo restores the exact state', async () => { + const user = userEvent.setup(); + const id = await createBulwark('E2E Bulwark Stand'); + const { maximum } = await hitPointsOf(id); + await client.play(id, { action: 'setHitPoints', amount: 5 }); + const before = (await client.getCharacter(id)).character.play; + await openBulwark(user, 'E2E Bulwark Stand'); + + await user.type(await screen.findByRole('spinbutton', { name: 'Amount' }), '20'); + await user.click(screen.getByRole('button', { name: 'Take damage' })); + const group = await screen.findByRole('radiogroup', { name: 'Survive at 0 hit points' }); + // The survival that needs the surge form is listed but cannot be chosen, and says why; the others are open. + const stand = within(group).getByRole('radio', { name: /^Last stand/ }); + expect(within(group).getByRole('radio', { name: /^Endure/ }).disabled).toBe(true); + expect(within(group).getByRole('radio', { name: 'None' }).checked).toBe(true); + await user.click(stand); + await screen.findByText(`Hit points after: 1 of ${maximum}`); + const apply = screen.getByRole('button', { name: 'Apply damage' }); + await waitFor(() => expect(apply.getAttribute('aria-disabled')).toBe('false')); + await user.click(apply); + await screen.findByRole('heading', { name: `Hit points: 1 of ${maximum}` }); + expect(await hitPointsOf(id)).toMatchObject({ current: 1, maximum }); + + // The service undoes the whole hit: the stored play state (hit points, the spent pool) is as it was before. + await user.click(await screen.findByRole('button', { name: /^Undo damage 20/ })); + await screen.findByRole('heading', { name: 'Hit points: 5 of ' + maximum }); + expect((await client.getCharacter(id)).character.play).toEqual(before); +}); + +it('a hit to a quarter of the maximum offers the threshold, which turns the form on', async () => { + const user = userEvent.setup(); + const id = await createBulwark('E2E Bulwark Rally'); + const { maximum } = await hitPointsOf(id); + const quarter = Math.floor(maximum / 4); + await openBulwark(user, 'E2E Bulwark Rally'); + const forms = () => screen.getByRole('radiogroup', { name: 'Forms' }); + expect(within(forms()).getByRole('radio', { name: /^Surge form/ }).getAttribute('aria-checked')).toBe('false'); + + // A hit that is not enough: the threshold is not offered. + await user.type(await screen.findByRole('spinbutton', { name: 'Amount' }), '1'); + await user.click(screen.getByRole('button', { name: 'Take damage' })); + const first = await screen.findByRole('group', { name: 'Responses' }); + expect(within(first).queryByRole('checkbox', { name: /^Rally/ })).toBeNull(); + await user.click(screen.getByRole('button', { name: 'Cancel' })); + + // A hit that leaves exactly a quarter of the maximum: the threshold is offered; choosing it turns the surge form on. + await user.type(await screen.findByRole('spinbutton', { name: 'Amount' }), String(maximum - quarter)); + await user.click(screen.getByRole('button', { name: 'Take damage' })); + const responses = await screen.findByRole('group', { name: 'Responses' }); + const rally = await within(responses).findByRole('checkbox', { name: /^Rally/ }); + await waitFor(() => expect(rally.disabled).toBe(false)); + await user.click(rally); + // The surge form raises Constitution, so the maximum after the hit is the form's, not the one the threshold was read against. + await screen.findByText(new RegExp(`^Hit points after: ${quarter} of \\d+`)); + const apply = screen.getByRole('button', { name: 'Apply damage' }); + await waitFor(() => expect(apply.getAttribute('aria-disabled')).toBe('false')); + await user.click(apply); + await waitFor(() => expect(within(forms()).getByRole('radio', { name: /^Surge form/ }).getAttribute('aria-checked')).toBe('true')); + expect((await hitPointsOf(id)).current).toBe(quarter); +}); + +it('plain damage from the summary routes through the panel', async () => { + const user = userEvent.setup(); + const id = await createBulwark('E2E Bulwark Plain'); + const { maximum } = await hitPointsOf(id); + await openBulwark(user, 'E2E Bulwark Plain'); + + // The summary's quick button opens the panel (the character has responses); with nothing chosen Apply is plain damage. + await user.click(screen.getByRole('button', { name: 'Lose 1 hit point' })); + await screen.findByRole('heading', { name: 'Take 1 untyped damage' }); + expect(await hitPointsOf(id)).toMatchObject({ current: maximum }); // nothing is written by opening it + const apply = screen.getByRole('button', { name: 'Apply damage' }); + await waitFor(() => expect(apply.getAttribute('aria-disabled')).toBe('false')); + await user.click(apply); + await screen.findByRole('heading', { name: `Hit points: ${maximum - 1} of ${maximum}` }); + expect(screen.queryByRole('button', { name: 'Apply damage' })).toBeNull(); + expect(await hitPointsOf(id)).toMatchObject({ current: maximum - 1, maximum }); +}); + +// ---- D43 S8: charging against the real DevHost ---- + +let chargingPack: Promise | undefined; + +/** The charging pack (`fixture-pack-charging.json`): the class with its two pools, then the feature that gathers and releases. Once per run. */ +function installChargingPack(): Promise { + chargingPack ??= publishFixturePack('fixture-pack-charging.json', 'E2E Charging Book', ['80', '81'].map((n) => `6f0dc000-0000-4000-8000-0000000000${n}`)); + return chargingPack; +} + +it('gather twice, release with the charge, then end the encounter with nothing left to clear', async () => { + const user = userEvent.setup(); + const pins = await installChargingPack(); + const fixture = JSON.parse(readFileSync(resolve(fixtureFolder(), 'characters/pm-charger-l5.json'), 'utf8')) as { baseAbilities: Record }; + await client.createCharacter({ name: 'E2E Charger', rulesFamily: 'srd-5.2.1', baseAbilities: fixture.baseAbilities as never, pins, classes: [{ class: pins[0]!, level: 5 }] }); + + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Charger/ })); + const sheet = await screen.findByRole('article', { name: 'E2E Charger' }); + await openTab(user, sheet, 'Play'); + const resources = () => screen.getByRole('region', { name: 'Resources' }); + const lastRoll = () => screen.getByRole('status', { name: 'Last roll' }); + expect(within(resources()).getByRole('heading', { name: 'Focus: 9 of 9' })).toBeTruthy(); + await user.click(await screen.findByRole('button', { name: 'Start encounter' })); + await screen.findByRole('button', { name: 'End encounter' }); + + // Each Gather spends 1 Focus and builds 1 Charge in one change, which Undo takes back as one. + const gather = () => screen.getByRole('button', { name: /^Use Gather/ }); + await user.click(gather()); + await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Charge: built up 1 of 4' })).toBeTruthy()); + await user.click(gather()); + await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Charge: built up 2 of 4' })).toBeTruthy()); + expect(within(resources()).getByRole('heading', { name: 'Focus: 7 of 9' })).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Undo use Gather' })).toBeTruthy(); + + // Release with 2 points rolls the base dice and 2 extra; rolling changes nothing, the record's Spend draws the charge down. + const points = await screen.findByRole('spinbutton', { name: /^Points to spend/ }); + expect(points.max).toBe('2'); + await user.clear(points); + await user.type(points, '2'); + await user.click(screen.getByRole('button', { name: /^Roll Release/ })); + await waitFor(() => expect(lastRoll().textContent).toMatch(/Release/)); + expect(lastRoll().textContent).toMatch(/2d8\s?\+\s?2d8/); + expect(within(resources()).getByRole('heading', { name: 'Charge: built up 2 of 4' })).toBeTruthy(); + await user.click(await within(lastRoll()).findByRole('button', { name: /^Spend 2 Charge/ })); + await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Charge: built up 0 of 4' })).toBeTruthy()); + + // Nothing is built up, so End encounter is one click with no clear choices. + await user.click(screen.getByRole('button', { name: 'End encounter' })); + expect(screen.queryByRole('group', { name: 'End encounter' })).toBeNull(); + await screen.findByRole('button', { name: 'Start encounter' }); +}); + +// ---- D73: the quickbar and "Usable now" against the real DevHost ---- + +const fixtureCharacterAbilities = (file: string) => (JSON.parse(readFileSync(resolve(fixtureFolder(), file), 'utf8')) as { baseAbilities: Record }).baseAbilities; + +let waveDetailsPack: Promise | undefined; + +/** The action-details pack (`fixture-pack-action-details.json`): the class with its pool, the Wisdom focus feature, then the one with the per-unit roll. Once per run. */ +function installWaveDetailsPack(): Promise { + waveDetailsPack ??= publishFixturePack('fixture-pack-action-details.json', 'E2E Wave Book', ['50', '52', '53'].map((n) => `6f0dc000-0000-4000-8000-0000000000${n}`)); + return waveDetailsPack; +} + +let modesPack: Promise | undefined; + +/** The feature-attacks pack (`fixture-pack-feature-attacks.json`): the class with the "Modes" group, then the mode feature that owns a roll only that mode allows. Once per run. */ +function installModesPack(): Promise { + modesPack ??= publishFixturePack('fixture-pack-feature-attacks.json', 'E2E Modes Book', ['40', '42'].map((n) => `6f0dc000-0000-4000-8000-0000000000${n}`)); + return modesPack; +} + +it('pins a per-unit roll, presses it with Alt+1: it rolls and spends once, Undo restores the pool, and the pin survives opening the character again (D73)', async () => { + const user = userEvent.setup(); + const pins = await installWaveDetailsPack(); + await client.createCharacter({ + name: 'E2E Quickbar Wave', + rulesFamily: 'srd-5.2.1', + baseAbilities: fixtureCharacterAbilities('characters/pm-wave-adept-l5.json') as never, + pins, + classes: [{ class: pins[0]!, level: 5 }], + }); + + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Quickbar Wave/ })); + const sheet = await screen.findByRole('article', { name: 'E2E Quickbar Wave' }); + await openTab(user, sheet, 'Play'); + const resources = () => screen.getByRole('region', { name: 'Resources' }); + const lastRoll = () => screen.getByRole('status', { name: 'Last roll' }); + const quickbar = () => screen.getByRole('region', { name: 'Quickbar' }); + const focus = async () => Number(/^Focus: (\d+) of 9$/.exec((await within(resources()).findByRole('heading', { name: /^Focus: \d+ of 9$/ })).textContent!)![1]); + expect(await focus()).toBe(9); + expect(screen.queryByRole('region', { name: 'Quickbar' })).toBeNull(); + + await user.click(await screen.findByRole('button', { name: 'Pin Tide wave to the quickbar' })); + const pinned = await within(quickbar()).findByRole('button', { name: /^Roll Tide wave/ }); + expect(pinned.getAttribute('aria-keyshortcuts')).toBe('Alt+1'); + + // Alt+1 (a button named "and spend") rolls and then makes that spend once, through the same play change, so nothing waits on a click. + await user.keyboard('{Alt>}1{/Alt}'); + await waitFor(() => expect(lastRoll().textContent).toMatch(/Tide wave/)); + const spendButton = await within(lastRoll()).findByRole('button', { name: /^Spend \d+ Focus/ }); + const spent = Number(/^Spend (\d+) Focus/.exec(spendButton.getAttribute('aria-label') ?? spendButton.textContent!)![1]); + expect(spent).toBe(2); // the roll's base cost (R13: a pinned per-unit roll spends no extra units) + await waitFor(async () => expect(await focus()).toBe(9 - spent)); + expect(within(lastRoll()).getByRole('button', { name: /^Spend \d+ Focus/ }).disabled).toBe(true); // spent once; the record cannot spend again + await waitFor(() => expect(quickbar().getAttribute('aria-busy')).toBeNull()); // `finally` clears busy after the pool renders + + // The service undoes the spend: the pool is back. + await user.click(await screen.findByRole('button', { name: /^Undo/ })); + await waitFor(async () => expect(await focus()).toBe(9)); + + // Leaving the sheet and opening the character again (a fresh mount reads the page storage): the pin is still there. + cleanup(); + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Quickbar Wave/ })); + await screen.findByRole('article', { name: 'E2E Quickbar Wave' }); + expect(await within(quickbar()).findByRole('button', { name: /^Roll Tide wave/ })).toBeTruthy(); +}); + +it('"Usable now" leaves out a mode-only roll while the mode is off and lists it again when the mode is switched on, with no reload (D73)', async () => { + const user = userEvent.setup(); + const pins = await installModesPack(); + await client.createCharacter({ + name: 'E2E Usable Modes', + rulesFamily: 'srd-5.2.1', + baseAbilities: fixtureCharacterAbilities('characters/pm-adept-l5.json') as never, + pins, + classes: [{ class: pins[0]!, level: 1 }], + }); + + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Usable Modes/ })); + const sheet = await screen.findByRole('article', { name: 'E2E Usable Modes' }); + await openTab(user, sheet, 'Play'); + const roll = () => screen.queryByRole('button', { name: /^Roll Flash step/ }); + const modes = () => within(screen.getByRole('region', { name: 'Combat' })).getByRole('radiogroup', { name: 'Modes' }); + + // Listed with its reason while the filter is off; the form is off. + await screen.findByRole('button', { name: /^Roll Flash step/ }); + const filter = screen.getByRole('checkbox', { name: 'Usable now' }); + expect(filter.checked).toBe(false); + await user.click(filter); + await waitFor(() => expect(roll()).toBeNull()); + + // Switching the mode on lists it at once. + await user.click(within(modes()).getByRole('radio', { name: /^Kindled mode/ })); + await waitFor(() => expect(within(modes()).getByRole('radio', { name: /^Kindled mode/ }).getAttribute('aria-checked')).toBe('true')); + await waitFor(() => expect(roll()).not.toBeNull()); + expect(filter.checked).toBe(true); +}); + + +it('authors a hit-point roll in the studio, uses it and undoes it (MECH-X item 1)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Rite Book', ['srd-5.2.1']); + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Rite Book/ })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Rite Book/ })); + await screen.findByRole('heading', { name: 'Content in E2E Rite Book' }); + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + const rule = (name: RegExp) => within(within(editor()).getByRole('group', { name })); + + // A roll that pays 2 hit points and has no pool at all. + await user.click(screen.getByRole('button', { name: 'New feature' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Blood Rite Feature'); + await user.click(within(editor()).getByRole('button', { name: 'Add roll or action' })); + const rite = rule(/^Rule 1: Roll or action/); + await user.type(rite.getByRole('textbox', { name: 'Roll name' }), 'E2E Blood Rite'); + const dice = rite.getByRole('textbox', { name: /^Dice/ }); + await user.clear(dice); + await user.type(dice, '1d6'); + await user.selectOptions(rite.getByRole('combobox', { name: 'Pays with' }), 'Hit points'); + await user.type(rite.getByRole('textbox', { name: /^Hit points paid/ }), '2'); + await user.click(within(editor()).getByRole('button', { name: 'Check' })); + expect((await within(editor()).findByRole('region', { name: 'Check results' })).textContent).toMatch(/No problems found/); + await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); + await expectStatus(/Made E2E Blood Rite Feature available to characters/); + + const published = (await client.contentBySource(source.id)).find((e) => e.name === 'E2E Blood Rite Feature')?.latestPublished; + expect(published).toBeTruthy(); + const created = await client.createCharacter({ + name: 'E2E Rite Hero', + rulesFamily: 'srd-5.2.1', + baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, + pins: [published!], + }); + await client.saveCharacter({ ...created.character, overrides: [{ field: 'hitPoints', value: 20 }] }); + + cleanup(); + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Rite Hero/ })); + const sheet = await screen.findByRole('article', { name: 'E2E Rite Hero' }); + await openTab(user, sheet, 'Play'); + const lastRoll = () => screen.getByRole('status', { name: 'Last roll' }); + await waitFor(() => expect(screen.getByRole('region', { name: /^Hit points: 20 of 20/ })).toBeTruthy()); + + // Rolling pays nothing; the record's "Pay 2 hit points" takes exactly two as one change. + await user.click(await screen.findByRole('button', { name: /^Roll E2E Blood Rite/ })); + await waitFor(() => expect(lastRoll().textContent).toMatch(/E2E Blood Rite/)); + expect(screen.getByRole('region', { name: /^Hit points: 20 of 20/ })).toBeTruthy(); + await user.click(await within(lastRoll()).findByRole('button', { name: /^Pay 2 hit points/ })); + await waitFor(() => expect(screen.getByRole('region', { name: /^Hit points: 18 of 20/ })).toBeTruthy()); + + // The service undoes the payment: the hit points are back. + await user.click(await screen.findByRole('button', { name: 'Undo use E2E Blood Rite' })); + await waitFor(() => expect(screen.getByRole('region', { name: /^Hit points: 20 of 20/ })).toBeTruthy()); +}); + +it('a replaceable choice offers a swap at level-up and notes one made outside it (MECH-X item 2)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Swap Book', ['srd-5.2.1']); + const id = (n: number) => `e2e5a000-0000-4000-8000-${String(n).padStart(12, '0')}`; + const draftOf = (n: number, name: string, effects: ContentRevision['effects']): ContentRevision => ({ + contentId: id(n), + revisionId: id(n + 1000), + schemaVersion: 12, + kind: 'feature', + name, + rulesFamilies: ['srd-5.2.1'], + provenance: { sourceId: source.id }, + status: 'draft', + effects, + }); + const publishOne = async (revision: ContentRevision): Promise => { + const result = await client.publish(await client.saveDraft(revision)); + expect(result.report.errors).toEqual([]); + return result.published; + }; + + // Original options first (a draft's options name published revisions), then one feature with two replaceable choices: + // a level-up one (count 1) and a long-rest one (count 2, at most 1 swapped at once). + const upOptions = [await publishOne(draftOf(1, 'Fixture Stance One', [])), await publishOne(draftOf(2, 'Fixture Stance Two', []))]; + const restOptions: ContentReference[] = []; + for (const [n, name] of [[3, 'Fixture Drill One'], [4, 'Fixture Drill Two'], [5, 'Fixture Drill Three'], [6, 'Fixture Drill Four']] as const) { + restOptions.push(await publishOne(draftOf(n, name, []))); + } + const feature = await publishOne( + draftOf(10, 'E2E Swap Feature', [ + { type: 'choice', id: 'swap-up', choiceId: 'swap-up', count: 1, options: upOptions, replaceable: { when: 'levelUp' } }, + { type: 'choice', id: 'swap-rest', choiceId: 'swap-rest', count: 2, options: restOptions, replaceable: { when: 'longRest', max: 1 } }, + ] as ContentRevision['effects']), + ); + + // A Fighter 1 with every other choice made, and the two picks of each choice. + const srd = (n: number) => ({ contentId: `52c00000-0000-4000-8000-${String(n).padStart(12, '0')}`, revisionId: `52e00000-0000-4000-8000-${String(n).padStart(12, '0')}` }); + await client.createCharacter({ + name: 'E2E Swapper', + rulesFamily: 'srd-5.2.1', + baseAbilities: { str: 16, dex: 14, con: 14, int: 10, wis: 12, cha: 8 }, + pins: [srd(1), srd(2), feature], + classes: [{ class: srd(408000), level: 1 }], + choices: [ + { source: srd(2), choiceId: 'soldier-ability-scores', selected: [srd(4)] }, + { source: srd(408000), choiceId: 'fighter-skills', selected: [srd(408800), srd(408802)] }, + { source: srd(408001), choiceId: 'fighting-style', selected: [srd(408601)] }, + { source: feature, choiceId: 'swap-up', selected: [upOptions[0]!] }, + { source: feature, choiceId: 'swap-rest', selected: [restOptions[0]!, restOptions[1]!] }, + ], + }); + const pickIn = async (legend: RegExp, option: RegExp) => { + const group = await screen.findByRole('group', { name: legend }); + await user.click(await within(group).findByRole('checkbox', { name: option })); + }; + + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Swapper/ })); + let sheet = await screen.findByRole('article', { name: 'E2E Swapper' }); + + // Level up: the Choices step offers the swap; replacing the one pick is inside the window, so there is no notice. + await user.click(within(sheet).getByRole('button', { name: 'Level up' })); + await user.click(await screen.findByRole('radio', { name: /^Fighter 2\b/ })); + await user.click(screen.getByRole('button', { name: 'Next: choices' })); + const upGroup = await screen.findByRole('group', { name: /^E2E Swap Feature: choose 1/ }); + expect(within(upGroup).getByText('You may replace one pick now.')).toBeTruthy(); + await pickIn(/^E2E Swap Feature: choose 1/, /^Fixture Stance One/); // untick the old pick + await pickIn(/^E2E Swap Feature: choose 1/, /^Fixture Stance Two/); + await user.click(await screen.findByRole('button', { name: 'Save level-up' })); + + sheet = await screen.findByRole('article', { name: 'E2E Swapper' }); + const changed = within(sheet).getByRole('region', { name: 'What changed at level 2' }); + expect(within(changed).getByText('Replaced 1 pick: E2E Swap Feature')).toBeTruthy(); + expect(screen.queryByText(/outside its window|more than the/)).toBeNull(); + + // Long rest: the preview and the after-rest panel name the long-rest choice; swapping both picks exceeds the one it allows. + await openTab(user, sheet, 'Play'); + await user.click(screen.getByRole('button', { name: 'Long rest…' })); + const rest = await screen.findByRole('region', { name: 'Long rest' }); + await waitFor(() => expect(rest.textContent).toMatch(/you may replace one pick of: E2E Swap Feature/)); + // That line comes from the sheet, not the proposal; Finish does nothing until the proposal arrives. + const finish = within(rest).getByRole('button', { name: 'Finish long rest' }); + await waitFor(() => expect(finish.getAttribute('aria-disabled')).toBe('false')); + await user.click(finish); + const after = await screen.findByRole('region', { name: 'After your long rest' }, { timeout: 5000 }); + expect(after.textContent).toMatch(/You may replace one pick of: E2E Swap Feature\./); + await user.click(within(after).getByRole('button', { name: 'Make choices' })); + + const legend = /^E2E Swap Feature: choose 2/; + await pickIn(legend, /^Fixture Drill One/); + await pickIn(legend, /^Fixture Drill Two/); + await pickIn(legend, /^Fixture Drill Three/); + await pickIn(legend, /^Fixture Drill Four/); + await user.click(await screen.findByRole('button', { name: 'Save choices' })); + await expectStatus(/E2E Swap Feature: you replaced 2 picks, more than the 1 it allows at once\./); +}); diff --git a/src/Ui/e2e/forms.e2e.tsx b/src/Ui/e2e/forms.e2e.tsx index a2bfd230..6e243e29 100644 --- a/src/Ui/e2e/forms.e2e.tsx +++ b/src/Ui/e2e/forms.e2e.tsx @@ -1,12 +1,10 @@ // D43 slice 1 against the real DevHost: form groups authored in the studio, the form picker on Play, and a refused switch. -import { readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { afterEach, expect, it, vi } from 'vitest'; import { App } from '../src/App'; import { client } from '../src/api/client'; -import type { ContentReference, ContentRevision } from '../src/api/types'; +import { expectStatus, openTab } from './helpers'; vi.mock('../src/api/client', async (importOriginal) => { const { inject } = await import('vitest'); @@ -18,25 +16,6 @@ vi.mock('../src/api/client', async (importOriginal) => { afterEach(cleanup); -/** Waits until the status line says `text` (the line stays on screen, so a plain find would see the previous message). */ -async function expectStatus(text: RegExp): Promise { - await waitFor(() => expect(appStatus().textContent).toMatch(text)); - return appStatus(); -} - -/** The app's status line; on a sheet the "Last roll" is a second `role="status"` node (D96), so exclude it by name. */ -function appStatus(): HTMLElement { - const lines = screen.getAllByRole('status').filter((el) => el.getAttribute('aria-label') !== 'Last roll'); - if (lines.length !== 1) throw new Error(`Expected one status line, found ${lines.length}.`); - return lines[0]!; -} - -/** Activates one tab of a character sheet (ADR-014); inactive panels are hidden. A no-op when it is already selected. */ -async function openTab(user: ReturnType, sheet: HTMLElement, name: string): Promise { - const tab = within(sheet).getByRole('tab', { name }); - if (tab.getAttribute('aria-selected') !== 'true') await user.click(tab); -} - it('authors a form group and two forms in the studio, switches forms, refuses a switch without enough pool, undoes the switch, and the pool is back', async () => { const user = userEvent.setup(); const source = await client.createHomebrewSource('E2E Forms Book', ['srd-5.2.1']); @@ -460,454 +439,3 @@ it('a feat with automatic advantage rolls two dice on a Dex save, and turning on await user.click(cancelled); await waitFor(() => expect(diceRolled()).toBe(1)); }); - -// ---- D43 S7: damage responses against the real DevHost ---- - -const fixtureFolder = () => resolve(process.cwd(), '../../tests/RulesFixtures'); - -/** The content ids of the responses pack, in the order they can be published (the pool and the form come first). */ -const responseContentOrder = ['70', '74', '71', '72', '73', '75', '76', '77'].map((n) => `6f0dc000-0000-4000-8000-0000000000${n}`); - -let responsesPack: Promise | undefined; - -/** - * Installs the responses fixture pack (`tests/RulesFixtures/fixture-pack-responses.json`) as one homebrew source, because the - * DevHost seeds only its older fixture packs. A draft gets a new revision id, so the class's grants of the six features (which - * name their revision ids) are left out and the character pins the features itself, as the fixture character does. Content ids - * stay, so the features' pool and form references still resolve. Once per run. - */ -function installResponsesPack(): Promise { - responsesPack ??= publishFixturePack('fixture-pack-responses.json', 'E2E Responses Book', responseContentOrder); - return responsesPack; -} - -/** Publishes a fixture pack's revisions, in the given content order, into a new homebrew source; the class's grants are left out. */ -async function publishFixturePack(file: string, title: string, order: string[]): Promise { - const pack = JSON.parse(readFileSync(resolve(fixtureFolder(), file), 'utf8')) as { revisions: ContentRevision[] }; - const source = await client.createHomebrewSource(title, ['srd-5.2.1']); - const published: ContentReference[] = []; - for (const contentId of order) { - const revision = pack.revisions.find((r) => r.contentId === contentId)!; - // A choice's options name revision ids that a draft does not keep either, so the class's choices are left out too. - const effects = revision.kind === 'class' ? revision.effects.filter((e) => e.type !== 'grant' && e.type !== 'choice') : revision.effects; - const draft = await client.saveDraft({ ...revision, status: 'draft', effects, provenance: { ...revision.provenance, sourceId: source.id } }); - const result = await client.publish(draft); - expect(result.report.errors).toEqual([]); - published.push(result.published); - } - return published; -} - -/** A level 8 Fixture Bulwark with the fixture character's scores, the six response features and the guard form pinned. */ -async function createBulwark(name: string): Promise { - const pins = await installResponsesPack(); - const fixture = JSON.parse(readFileSync(resolve(fixtureFolder(), 'characters/pm-bulwark-l8.json'), 'utf8')) as { baseAbilities: Record }; - const created = await client.createCharacter({ - name, - rulesFamily: 'srd-5.2.1', - baseAbilities: fixture.baseAbilities as never, - pins, - classes: [{ class: pins[0]!, level: 8 }], - }); - return created.character.id; -} - -async function openBulwark(user: ReturnType, name: string): Promise { - render(); - await user.click(await screen.findByRole('button', { name: new RegExp(`^${name}`) })); - const sheet = await screen.findByRole('article', { name }); - await openTab(user, sheet, 'Play'); - return sheet; -} - -const hitPointsOf = async (id: string) => (await client.getCharacter(id)).sheet.hitPoints!; - -it('a hit that would drop the character to 0 offers survival; choosing it leaves 1 HP and Undo restores the exact state', async () => { - const user = userEvent.setup(); - const id = await createBulwark('E2E Bulwark Stand'); - const { maximum } = await hitPointsOf(id); - await client.play(id, { action: 'setHitPoints', amount: 5 }); - const before = (await client.getCharacter(id)).character.play; - await openBulwark(user, 'E2E Bulwark Stand'); - - await user.type(await screen.findByRole('spinbutton', { name: 'Amount' }), '20'); - await user.click(screen.getByRole('button', { name: 'Take damage' })); - const group = await screen.findByRole('radiogroup', { name: 'Survive at 0 hit points' }); - // The survival that needs the surge form is listed but cannot be chosen, and says why; the others are open. - const stand = within(group).getByRole('radio', { name: /^Last stand/ }); - expect(within(group).getByRole('radio', { name: /^Endure/ }).disabled).toBe(true); - expect(within(group).getByRole('radio', { name: 'None' }).checked).toBe(true); - await user.click(stand); - await screen.findByText(`Hit points after: 1 of ${maximum}`); - const apply = screen.getByRole('button', { name: 'Apply damage' }); - await waitFor(() => expect(apply.getAttribute('aria-disabled')).toBe('false')); - await user.click(apply); - await screen.findByRole('heading', { name: `Hit points: 1 of ${maximum}` }); - expect(await hitPointsOf(id)).toMatchObject({ current: 1, maximum }); - - // The service undoes the whole hit: the stored play state (hit points, the spent pool) is as it was before. - await user.click(await screen.findByRole('button', { name: /^Undo damage 20/ })); - await screen.findByRole('heading', { name: 'Hit points: 5 of ' + maximum }); - expect((await client.getCharacter(id)).character.play).toEqual(before); -}); - -it('a hit to a quarter of the maximum offers the threshold, which turns the form on', async () => { - const user = userEvent.setup(); - const id = await createBulwark('E2E Bulwark Rally'); - const { maximum } = await hitPointsOf(id); - const quarter = Math.floor(maximum / 4); - await openBulwark(user, 'E2E Bulwark Rally'); - const forms = () => screen.getByRole('radiogroup', { name: 'Forms' }); - expect(within(forms()).getByRole('radio', { name: /^Surge form/ }).getAttribute('aria-checked')).toBe('false'); - - // A hit that is not enough: the threshold is not offered. - await user.type(await screen.findByRole('spinbutton', { name: 'Amount' }), '1'); - await user.click(screen.getByRole('button', { name: 'Take damage' })); - const first = await screen.findByRole('group', { name: 'Responses' }); - expect(within(first).queryByRole('checkbox', { name: /^Rally/ })).toBeNull(); - await user.click(screen.getByRole('button', { name: 'Cancel' })); - - // A hit that leaves exactly a quarter of the maximum: the threshold is offered; choosing it turns the surge form on. - await user.type(await screen.findByRole('spinbutton', { name: 'Amount' }), String(maximum - quarter)); - await user.click(screen.getByRole('button', { name: 'Take damage' })); - const responses = await screen.findByRole('group', { name: 'Responses' }); - const rally = await within(responses).findByRole('checkbox', { name: /^Rally/ }); - await waitFor(() => expect(rally.disabled).toBe(false)); - await user.click(rally); - // The surge form raises Constitution, so the maximum after the hit is the form's, not the one the threshold was read against. - await screen.findByText(new RegExp(`^Hit points after: ${quarter} of \\d+`)); - const apply = screen.getByRole('button', { name: 'Apply damage' }); - await waitFor(() => expect(apply.getAttribute('aria-disabled')).toBe('false')); - await user.click(apply); - await waitFor(() => expect(within(forms()).getByRole('radio', { name: /^Surge form/ }).getAttribute('aria-checked')).toBe('true')); - expect((await hitPointsOf(id)).current).toBe(quarter); -}); - -it('plain damage from the summary routes through the panel', async () => { - const user = userEvent.setup(); - const id = await createBulwark('E2E Bulwark Plain'); - const { maximum } = await hitPointsOf(id); - await openBulwark(user, 'E2E Bulwark Plain'); - - // The summary's quick button opens the panel (the character has responses); with nothing chosen Apply is plain damage. - await user.click(screen.getByRole('button', { name: 'Lose 1 hit point' })); - await screen.findByRole('heading', { name: 'Take 1 untyped damage' }); - expect(await hitPointsOf(id)).toMatchObject({ current: maximum }); // nothing is written by opening it - const apply = screen.getByRole('button', { name: 'Apply damage' }); - await waitFor(() => expect(apply.getAttribute('aria-disabled')).toBe('false')); - await user.click(apply); - await screen.findByRole('heading', { name: `Hit points: ${maximum - 1} of ${maximum}` }); - expect(screen.queryByRole('button', { name: 'Apply damage' })).toBeNull(); - expect(await hitPointsOf(id)).toMatchObject({ current: maximum - 1, maximum }); -}); - -// ---- D43 S8: charging against the real DevHost ---- - -let chargingPack: Promise | undefined; - -/** The charging pack (`fixture-pack-charging.json`): the class with its two pools, then the feature that gathers and releases. Once per run. */ -function installChargingPack(): Promise { - chargingPack ??= publishFixturePack('fixture-pack-charging.json', 'E2E Charging Book', ['80', '81'].map((n) => `6f0dc000-0000-4000-8000-0000000000${n}`)); - return chargingPack; -} - -it('gather twice, release with the charge, then end the encounter with nothing left to clear', async () => { - const user = userEvent.setup(); - const pins = await installChargingPack(); - const fixture = JSON.parse(readFileSync(resolve(fixtureFolder(), 'characters/pm-charger-l5.json'), 'utf8')) as { baseAbilities: Record }; - await client.createCharacter({ name: 'E2E Charger', rulesFamily: 'srd-5.2.1', baseAbilities: fixture.baseAbilities as never, pins, classes: [{ class: pins[0]!, level: 5 }] }); - - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Charger/ })); - const sheet = await screen.findByRole('article', { name: 'E2E Charger' }); - await openTab(user, sheet, 'Play'); - const resources = () => screen.getByRole('region', { name: 'Resources' }); - const lastRoll = () => screen.getByRole('status', { name: 'Last roll' }); - expect(within(resources()).getByRole('heading', { name: 'Focus: 9 of 9' })).toBeTruthy(); - await user.click(await screen.findByRole('button', { name: 'Start encounter' })); - await screen.findByRole('button', { name: 'End encounter' }); - - // Each Gather spends 1 Focus and builds 1 Charge in one change, which Undo takes back as one. - const gather = () => screen.getByRole('button', { name: /^Use Gather/ }); - await user.click(gather()); - await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Charge: built up 1 of 4' })).toBeTruthy()); - await user.click(gather()); - await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Charge: built up 2 of 4' })).toBeTruthy()); - expect(within(resources()).getByRole('heading', { name: 'Focus: 7 of 9' })).toBeTruthy(); - expect(screen.getByRole('button', { name: 'Undo use Gather' })).toBeTruthy(); - - // Release with 2 points rolls the base dice and 2 extra; rolling changes nothing, the record's Spend draws the charge down. - const points = await screen.findByRole('spinbutton', { name: /^Points to spend/ }); - expect(points.max).toBe('2'); - await user.clear(points); - await user.type(points, '2'); - await user.click(screen.getByRole('button', { name: /^Roll Release/ })); - await waitFor(() => expect(lastRoll().textContent).toMatch(/Release/)); - expect(lastRoll().textContent).toMatch(/2d8\s?\+\s?2d8/); - expect(within(resources()).getByRole('heading', { name: 'Charge: built up 2 of 4' })).toBeTruthy(); - await user.click(await within(lastRoll()).findByRole('button', { name: /^Spend 2 Charge/ })); - await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Charge: built up 0 of 4' })).toBeTruthy()); - - // Nothing is built up, so End encounter is one click with no clear choices. - await user.click(screen.getByRole('button', { name: 'End encounter' })); - expect(screen.queryByRole('group', { name: 'End encounter' })).toBeNull(); - await screen.findByRole('button', { name: 'Start encounter' }); -}); - -// ---- D73: the quickbar and "Usable now" against the real DevHost ---- - -const fixtureCharacterAbilities = (file: string) => (JSON.parse(readFileSync(resolve(fixtureFolder(), file), 'utf8')) as { baseAbilities: Record }).baseAbilities; - -let waveDetailsPack: Promise | undefined; - -/** The action-details pack (`fixture-pack-action-details.json`): the class with its pool, the Wisdom focus feature, then the one with the per-unit roll. Once per run. */ -function installWaveDetailsPack(): Promise { - waveDetailsPack ??= publishFixturePack('fixture-pack-action-details.json', 'E2E Wave Book', ['50', '52', '53'].map((n) => `6f0dc000-0000-4000-8000-0000000000${n}`)); - return waveDetailsPack; -} - -let modesPack: Promise | undefined; - -/** The feature-attacks pack (`fixture-pack-feature-attacks.json`): the class with the "Modes" group, then the mode feature that owns a roll only that mode allows. Once per run. */ -function installModesPack(): Promise { - modesPack ??= publishFixturePack('fixture-pack-feature-attacks.json', 'E2E Modes Book', ['40', '42'].map((n) => `6f0dc000-0000-4000-8000-0000000000${n}`)); - return modesPack; -} - -it('pins a per-unit roll, presses it with Alt+1: it rolls and spends once, Undo restores the pool, and the pin survives opening the character again (D73)', async () => { - const user = userEvent.setup(); - const pins = await installWaveDetailsPack(); - await client.createCharacter({ - name: 'E2E Quickbar Wave', - rulesFamily: 'srd-5.2.1', - baseAbilities: fixtureCharacterAbilities('characters/pm-wave-adept-l5.json') as never, - pins, - classes: [{ class: pins[0]!, level: 5 }], - }); - - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Quickbar Wave/ })); - const sheet = await screen.findByRole('article', { name: 'E2E Quickbar Wave' }); - await openTab(user, sheet, 'Play'); - const resources = () => screen.getByRole('region', { name: 'Resources' }); - const lastRoll = () => screen.getByRole('status', { name: 'Last roll' }); - const quickbar = () => screen.getByRole('region', { name: 'Quickbar' }); - const focus = async () => Number(/^Focus: (\d+) of 9$/.exec((await within(resources()).findByRole('heading', { name: /^Focus: \d+ of 9$/ })).textContent!)![1]); - expect(await focus()).toBe(9); - expect(screen.queryByRole('region', { name: 'Quickbar' })).toBeNull(); - - await user.click(await screen.findByRole('button', { name: 'Pin Tide wave to the quickbar' })); - const pinned = await within(quickbar()).findByRole('button', { name: /^Roll Tide wave/ }); - expect(pinned.getAttribute('aria-keyshortcuts')).toBe('Alt+1'); - - // Alt+1 (a button named "and spend") rolls and then makes that spend once, through the same play change, so nothing waits on a click. - await user.keyboard('{Alt>}1{/Alt}'); - await waitFor(() => expect(lastRoll().textContent).toMatch(/Tide wave/)); - const spendButton = await within(lastRoll()).findByRole('button', { name: /^Spend \d+ Focus/ }); - const spent = Number(/^Spend (\d+) Focus/.exec(spendButton.getAttribute('aria-label') ?? spendButton.textContent!)![1]); - expect(spent).toBe(2); // the roll's base cost (R13: a pinned per-unit roll spends no extra units) - await waitFor(async () => expect(await focus()).toBe(9 - spent)); - expect(within(lastRoll()).getByRole('button', { name: /^Spend \d+ Focus/ }).disabled).toBe(true); // spent once; the record cannot spend again - await waitFor(() => expect(quickbar().getAttribute('aria-busy')).toBeNull()); // `finally` clears busy after the pool renders - - // The service undoes the spend: the pool is back. - await user.click(await screen.findByRole('button', { name: /^Undo/ })); - await waitFor(async () => expect(await focus()).toBe(9)); - - // Leaving the sheet and opening the character again (a fresh mount reads the page storage): the pin is still there. - cleanup(); - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Quickbar Wave/ })); - await screen.findByRole('article', { name: 'E2E Quickbar Wave' }); - expect(await within(quickbar()).findByRole('button', { name: /^Roll Tide wave/ })).toBeTruthy(); -}); - -it('"Usable now" leaves out a mode-only roll while the mode is off and lists it again when the mode is switched on, with no reload (D73)', async () => { - const user = userEvent.setup(); - const pins = await installModesPack(); - await client.createCharacter({ - name: 'E2E Usable Modes', - rulesFamily: 'srd-5.2.1', - baseAbilities: fixtureCharacterAbilities('characters/pm-adept-l5.json') as never, - pins, - classes: [{ class: pins[0]!, level: 1 }], - }); - - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Usable Modes/ })); - const sheet = await screen.findByRole('article', { name: 'E2E Usable Modes' }); - await openTab(user, sheet, 'Play'); - const roll = () => screen.queryByRole('button', { name: /^Roll Flash step/ }); - const modes = () => within(screen.getByRole('region', { name: 'Combat' })).getByRole('radiogroup', { name: 'Modes' }); - - // Listed with its reason while the filter is off; the form is off. - await screen.findByRole('button', { name: /^Roll Flash step/ }); - const filter = screen.getByRole('checkbox', { name: 'Usable now' }); - expect(filter.checked).toBe(false); - await user.click(filter); - await waitFor(() => expect(roll()).toBeNull()); - - // Switching the mode on lists it at once. - await user.click(within(modes()).getByRole('radio', { name: /^Kindled mode/ })); - await waitFor(() => expect(within(modes()).getByRole('radio', { name: /^Kindled mode/ }).getAttribute('aria-checked')).toBe('true')); - await waitFor(() => expect(roll()).not.toBeNull()); - expect(filter.checked).toBe(true); -}); - - -it('authors a hit-point roll in the studio, uses it and undoes it (MECH-X item 1)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Rite Book', ['srd-5.2.1']); - render(); - const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); - await waitFor(() => expect(studioButton.disabled).toBe(false)); - await user.click(studioButton); - const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); - await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Rite Book/ })).toBeTruthy()); - await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Rite Book/ })); - await screen.findByRole('heading', { name: 'Content in E2E Rite Book' }); - const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); - const rule = (name: RegExp) => within(within(editor()).getByRole('group', { name })); - - // A roll that pays 2 hit points and has no pool at all. - await user.click(screen.getByRole('button', { name: 'New feature' })); - await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Blood Rite Feature'); - await user.click(within(editor()).getByRole('button', { name: 'Add roll or action' })); - const rite = rule(/^Rule 1: Roll or action/); - await user.type(rite.getByRole('textbox', { name: 'Roll name' }), 'E2E Blood Rite'); - const dice = rite.getByRole('textbox', { name: /^Dice/ }); - await user.clear(dice); - await user.type(dice, '1d6'); - await user.selectOptions(rite.getByRole('combobox', { name: 'Pays with' }), 'Hit points'); - await user.type(rite.getByRole('textbox', { name: /^Hit points paid/ }), '2'); - await user.click(within(editor()).getByRole('button', { name: 'Check' })); - expect((await within(editor()).findByRole('region', { name: 'Check results' })).textContent).toMatch(/No problems found/); - await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); - await expectStatus(/Made E2E Blood Rite Feature available to characters/); - - const published = (await client.contentBySource(source.id)).find((e) => e.name === 'E2E Blood Rite Feature')?.latestPublished; - expect(published).toBeTruthy(); - const created = await client.createCharacter({ - name: 'E2E Rite Hero', - rulesFamily: 'srd-5.2.1', - baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, - pins: [published!], - }); - await client.saveCharacter({ ...created.character, overrides: [{ field: 'hitPoints', value: 20 }] }); - - cleanup(); - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Rite Hero/ })); - const sheet = await screen.findByRole('article', { name: 'E2E Rite Hero' }); - await openTab(user, sheet, 'Play'); - const lastRoll = () => screen.getByRole('status', { name: 'Last roll' }); - await waitFor(() => expect(screen.getByRole('region', { name: /^Hit points: 20 of 20/ })).toBeTruthy()); - - // Rolling pays nothing; the record's "Pay 2 hit points" takes exactly two as one change. - await user.click(await screen.findByRole('button', { name: /^Roll E2E Blood Rite/ })); - await waitFor(() => expect(lastRoll().textContent).toMatch(/E2E Blood Rite/)); - expect(screen.getByRole('region', { name: /^Hit points: 20 of 20/ })).toBeTruthy(); - await user.click(await within(lastRoll()).findByRole('button', { name: /^Pay 2 hit points/ })); - await waitFor(() => expect(screen.getByRole('region', { name: /^Hit points: 18 of 20/ })).toBeTruthy()); - - // The service undoes the payment: the hit points are back. - await user.click(await screen.findByRole('button', { name: 'Undo use E2E Blood Rite' })); - await waitFor(() => expect(screen.getByRole('region', { name: /^Hit points: 20 of 20/ })).toBeTruthy()); -}); - -it('a replaceable choice offers a swap at level-up and notes one made outside it (MECH-X item 2)', async () => { - const user = userEvent.setup(); - const source = await client.createHomebrewSource('E2E Swap Book', ['srd-5.2.1']); - const id = (n: number) => `e2e5a000-0000-4000-8000-${String(n).padStart(12, '0')}`; - const draftOf = (n: number, name: string, effects: ContentRevision['effects']): ContentRevision => ({ - contentId: id(n), - revisionId: id(n + 1000), - schemaVersion: 12, - kind: 'feature', - name, - rulesFamilies: ['srd-5.2.1'], - provenance: { sourceId: source.id }, - status: 'draft', - effects, - }); - const publishOne = async (revision: ContentRevision): Promise => { - const result = await client.publish(await client.saveDraft(revision)); - expect(result.report.errors).toEqual([]); - return result.published; - }; - - // Original options first (a draft's options name published revisions), then one feature with two replaceable choices: - // a level-up one (count 1) and a long-rest one (count 2, at most 1 swapped at once). - const upOptions = [await publishOne(draftOf(1, 'Fixture Stance One', [])), await publishOne(draftOf(2, 'Fixture Stance Two', []))]; - const restOptions: ContentReference[] = []; - for (const [n, name] of [[3, 'Fixture Drill One'], [4, 'Fixture Drill Two'], [5, 'Fixture Drill Three'], [6, 'Fixture Drill Four']] as const) { - restOptions.push(await publishOne(draftOf(n, name, []))); - } - const feature = await publishOne( - draftOf(10, 'E2E Swap Feature', [ - { type: 'choice', id: 'swap-up', choiceId: 'swap-up', count: 1, options: upOptions, replaceable: { when: 'levelUp' } }, - { type: 'choice', id: 'swap-rest', choiceId: 'swap-rest', count: 2, options: restOptions, replaceable: { when: 'longRest', max: 1 } }, - ] as ContentRevision['effects']), - ); - - // A Fighter 1 with every other choice made, and the two picks of each choice. - const srd = (n: number) => ({ contentId: `52c00000-0000-4000-8000-${String(n).padStart(12, '0')}`, revisionId: `52e00000-0000-4000-8000-${String(n).padStart(12, '0')}` }); - await client.createCharacter({ - name: 'E2E Swapper', - rulesFamily: 'srd-5.2.1', - baseAbilities: { str: 16, dex: 14, con: 14, int: 10, wis: 12, cha: 8 }, - pins: [srd(1), srd(2), feature], - classes: [{ class: srd(408000), level: 1 }], - choices: [ - { source: srd(2), choiceId: 'soldier-ability-scores', selected: [srd(4)] }, - { source: srd(408000), choiceId: 'fighter-skills', selected: [srd(408800), srd(408802)] }, - { source: srd(408001), choiceId: 'fighting-style', selected: [srd(408601)] }, - { source: feature, choiceId: 'swap-up', selected: [upOptions[0]!] }, - { source: feature, choiceId: 'swap-rest', selected: [restOptions[0]!, restOptions[1]!] }, - ], - }); - const pickIn = async (legend: RegExp, option: RegExp) => { - const group = await screen.findByRole('group', { name: legend }); - await user.click(await within(group).findByRole('checkbox', { name: option })); - }; - - render(); - await user.click(await screen.findByRole('button', { name: /^E2E Swapper/ })); - let sheet = await screen.findByRole('article', { name: 'E2E Swapper' }); - - // Level up: the Choices step offers the swap; replacing the one pick is inside the window, so there is no notice. - await user.click(within(sheet).getByRole('button', { name: 'Level up' })); - await user.click(await screen.findByRole('radio', { name: /^Fighter 2\b/ })); - await user.click(screen.getByRole('button', { name: 'Next: choices' })); - const upGroup = await screen.findByRole('group', { name: /^E2E Swap Feature: choose 1/ }); - expect(within(upGroup).getByText('You may replace one pick now.')).toBeTruthy(); - await pickIn(/^E2E Swap Feature: choose 1/, /^Fixture Stance One/); // untick the old pick - await pickIn(/^E2E Swap Feature: choose 1/, /^Fixture Stance Two/); - await user.click(await screen.findByRole('button', { name: 'Save level-up' })); - - sheet = await screen.findByRole('article', { name: 'E2E Swapper' }); - const changed = within(sheet).getByRole('region', { name: 'What changed at level 2' }); - expect(within(changed).getByText('Replaced 1 pick: E2E Swap Feature')).toBeTruthy(); - expect(screen.queryByText(/outside its window|more than the/)).toBeNull(); - - // Long rest: the preview and the after-rest panel name the long-rest choice; swapping both picks exceeds the one it allows. - await openTab(user, sheet, 'Play'); - await user.click(screen.getByRole('button', { name: 'Long rest…' })); - const rest = await screen.findByRole('region', { name: 'Long rest' }); - await waitFor(() => expect(rest.textContent).toMatch(/you may replace one pick of: E2E Swap Feature/)); - // That line comes from the sheet, not the proposal; Finish does nothing until the proposal arrives. - const finish = within(rest).getByRole('button', { name: 'Finish long rest' }); - await waitFor(() => expect(finish.getAttribute('aria-disabled')).toBe('false')); - await user.click(finish); - const after = await screen.findByRole('region', { name: 'After your long rest' }, { timeout: 5000 }); - expect(after.textContent).toMatch(/You may replace one pick of: E2E Swap Feature\./); - await user.click(within(after).getByRole('button', { name: 'Make choices' })); - - const legend = /^E2E Swap Feature: choose 2/; - await pickIn(legend, /^Fixture Drill One/); - await pickIn(legend, /^Fixture Drill Two/); - await pickIn(legend, /^Fixture Drill Three/); - await pickIn(legend, /^Fixture Drill Four/); - await user.click(await screen.findByRole('button', { name: 'Save choices' })); - await expectStatus(/E2E Swap Feature: you replaced 2 picks, more than the 1 it allows at once\./); -}); diff --git a/src/Ui/e2e/helpers.tsx b/src/Ui/e2e/helpers.tsx new file mode 100644 index 00000000..54d14fb1 --- /dev/null +++ b/src/Ui/e2e/helpers.tsx @@ -0,0 +1,132 @@ +// Helpers shared by the e2e files. Everything here is used by two or more of them; a helper used by one file stays in that file. +import { screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { expect } from 'vitest'; + +/** + * Group 2 navigation: a new character goes "+ Add a character" (sidebar) > "Make a new one" > Continue. The sidebar button is + * enabled before app.info loads; the chooser disables "Make a new one" until it has, so the radio is waited on. + */ +export async function startNewCharacter(user: ReturnType): Promise { + await user.click(await screen.findByRole('button', { name: '+ Add a character' })); + const make = await screen.findByRole('radio', { name: 'Make a new one' }); + await waitFor(() => expect(make.disabled).toBe(false)); + await user.click(make); + await user.click(screen.getByRole('button', { name: 'Continue' })); +} + +/** The brand button in the window title area always goes home (the sidebar's "All characters" shows only with 2+ characters). */ +export async function goHome(user: ReturnType): Promise { + await user.click(await screen.findByRole('button', { name: 'TomeStack, your characters' })); +} + +export function bytesOf(base64: string): Uint8Array { + return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); +} + +/** + * Waits until the status line says `text`. The status line stays on screen, so `findByRole('status')` would return at + * once with the previous message (lint forbids it here). + */ +export async function expectStatus(text: RegExp): Promise { + await waitFor(() => expect(appStatus().textContent).toMatch(text)); + return appStatus(); +} + +/** + * The app's status line. On a sheet the "Last roll" is a second `role="status"` node (D96), so a plain + * `getByRole('status')` finds two; this excludes it by name and expects exactly one line left. + */ +export function appStatus(): HTMLElement { + const lines = screen.getAllByRole('status').filter((el) => el.getAttribute('aria-label') !== 'Last roll'); + if (lines.length !== 1) throw new Error(`Expected one status line, found ${lines.length}.`); + return lines[0]!; +} + +/** + * Activates one tab of a character sheet (ADR-014). Inactive panels are hidden, so a query finds only the active + * tab's sections; a test must open the tab a user would open. A no-op when the tab is already selected. + */ +export async function openTab(user: ReturnType, sheet: HTMLElement, name: string): Promise { + const tab = within(sheet).getByRole('tab', { name }); + if (tab.getAttribute('aria-selected') !== 'true') await user.click(tab); +} + +/** Opens the sheet's More disclosure and chooses one item (Choices, Print…, Export…, Snapshots, Updates, Archive). */ +export async function openMore(user: ReturnType, sheet: HTMLElement, item: string): Promise { + await user.click(within(sheet).getByRole('button', { name: 'More' })); + await user.click(within(sheet).getByRole('button', { name: item })); +} + +/** One value of the sheet's status bar: the `.status-value` beside the `.status-label` named `term` (button or plain item). */ +export function summaryValue(sheet: HTMLElement, term: string): string { + const summary = within(sheet).getByRole('region', { name: 'Status' }); + const label = Array.from(summary.querySelectorAll('.status-label')).find((l) => l.textContent?.trim() === term); + if (!label) throw new Error(`No status bar item named ${term}`); + return label.parentElement!.querySelector('.status-value')!.textContent!.trim(); +} + +/** Ticks one option of the choice whose legend starts with `legend`. */ +export async function pick(user: ReturnType, legend: RegExp, option: RegExp) { + const group = await screen.findByRole('group', { name: legend }); + await user.click(await within(group).findByRole('checkbox', { name: option })); // options load after the choices +} + +/** D32: walks the seven create steps (rules, class, scores, species, background, gear, choices). `scores` uses "Enter by hand" ({} keeps the default scores); otherwise the standard array is assigned in order. */ +export async function createCharacter( + user: ReturnType, + opts: { + name: string; + family?: 'srd-5.1' | 'srd-5.2.1'; + scores?: Partial>; + species?: RegExp; + cls?: RegExp; + background?: RegExp; + /** A checkbox under "Other content" on the Background step. */ + other?: RegExp; + /** Keep the starting kits on the Gear step instead of skipping it; `beforeChoices` runs there first. */ + kit?: boolean; + beforeChoices?: () => Promise; + }, +) { + await startNewCharacter(user); + await user.type(await screen.findByRole('textbox', { name: 'Name' }), opts.name); + if (opts.family) await user.click(screen.getByRole('radio', { name: opts.family === 'srd-5.2.1' ? /2024 rules/ : /2014 rules/ })); + await user.click(screen.getByRole('button', { name: 'Next: class' })); + // The class options only appear once the listing for the chosen rules family has arrived, so this pick is never dropped. + if (opts.cls) await user.click(await screen.findByRole('radio', { name: opts.cls })); + await user.click(screen.getByRole('button', { name: 'Next: ability scores' })); + if (opts.scores) { + await user.click(screen.getByRole('radio', { name: 'Enter by hand' })); + const group = screen.getByRole('group', { name: 'Base ability scores' }); + for (const [label, value] of Object.entries(opts.scores)) { + const input = within(group).getByRole('spinbutton', { name: label }); + await user.clear(input); + await user.type(input, String(value)); + } + } else { + const group = screen.getByRole('group', { name: 'Assign the standard array' }); + for (const [label, value] of [['Strength', '15'], ['Dexterity', '14'], ['Constitution', '13'], ['Intelligence', '12'], ['Wisdom', '10'], ['Charisma', '8']] as const) + await user.selectOptions(within(group).getByRole('combobox', { name: label }), value); + } + await user.click(screen.getByRole('button', { name: 'Next: species' })); + if (opts.species) await user.click(await screen.findByRole('radio', { name: opts.species })); + await user.click(screen.getByRole('button', { name: 'Next: background' })); + if (opts.background) await user.click(await screen.findByRole('radio', { name: opts.background })); + if (opts.other) { + await user.click(screen.getByText(/^Other content \(/)); // the summary, not the legend inside it + await user.click(await screen.findByRole('checkbox', { name: opts.other })); + } + await user.click(screen.getByRole('button', { name: 'Next: gear' })); + // Gear: most walks skip it so inventories stay as the test expects; `kit` keeps the guides' defaults (option a) and `beforeChoices` runs on the step. + if (opts.kit) await opts.beforeChoices?.(); + else await user.click(screen.getByRole('button', { name: /^Skip: I'll add gear myself/ })); + await user.click(screen.getByRole('button', { name: 'Next: choices' })); +} + +export const srd = (n: number) => ({ + contentId: `52c00000-0000-4000-8000-${String(n).padStart(12, '0')}`, + revisionId: `52e00000-0000-4000-8000-${String(n).padStart(12, '0')}`, +}); + +export const fighter = (n: number) => srd(408000 + n); diff --git a/src/Ui/e2e/play.e2e.tsx b/src/Ui/e2e/play.e2e.tsx new file mode 100644 index 00000000..3e49e139 --- /dev/null +++ b/src/Ui/e2e/play.e2e.tsx @@ -0,0 +1,463 @@ +// End-to-end UI flow against the real DevHost (same CommandDispatcher as the shell). Only the transport differs from the desktop +// app: HTTP to loopback instead of the WebView2 bridge, so export takes the download fallback instead of the native Save dialog. +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, expect, it, vi } from 'vitest'; +import { App } from '../src/App'; +import { client } from '../src/api/client'; +import { appStatus, createCharacter, expectStatus, openTab, pick, summaryValue } from './helpers'; + +vi.mock('../src/api/client', async (importOriginal) => { + const { inject } = await import('vitest'); + const { createHttpTransport } = await import('../src/api/transport'); + const original = await importOriginal(); + const { endpoint, token } = inject('devHost'); + return { ...original, client: original.createClient(createHttpTransport(endpoint, { 'X-TomeStack-Token': token })) }; +}); + +vi.mock('../src/files', async (importOriginal) => ({ + ...(await importOriginal()), + downloadBase64: vi.fn(), +})); + +afterEach(() => { + cleanup(); + // One jsdom window serves the whole file: a preference or `html` attribute left by one test would leak into the next. + // The per-character tab memory stays (ids are unique per test and the deep-link test relies on it). + for (const key of Object.keys(localStorage)) if (key.startsWith('tomestack.') && !key.startsWith('tomestack.sheetTab.')) localStorage.removeItem(key); + for (const key of Object.keys(document.documentElement.dataset)) delete document.documentElement.dataset[key]; +}); + +it('equips a weapon: the attack uses finesse and proficiency, rolls, and actions are grouped', async () => { + // SPEC C-02, C-04 with the original fixtures "Fixture Duelist" (simple and martial weapons) and "Fixture Needle" (finesse). + const user = userEvent.setup(); + render(); + await createCharacter(user, { name: 'E2E Blade', scores: { Strength: 14, Dexterity: 16 }, cls: /^Fixture Duelist/ }); + await pick(user, /^Fixture Duelist: choose 2/, /^Duelist Skill: Acrobatics/); + await pick(user, /^Fixture Duelist: choose 2/, /^Duelist Skill: Insight/); + await user.click(await screen.findByRole('button', { name: 'Create and save' })); + const blade = await screen.findByRole('article', { name: 'E2E Blade' }); + + await openTab(user, blade, 'Gear'); + const equipment = () => screen.getByRole('region', { name: 'Equipment' }); + await waitFor(() => expect(within(equipment()).getByRole('option', { name: /^Fixture Needle/ })).toBeTruthy()); + await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^Fixture Needle/ })); + await user.click(within(equipment()).getByRole('button', { name: 'Add' })); + await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip Fixture Needle' })); + + // Dex +3 (finesse beats Str +2) + PB 2 = +5; damage 1d4 + 3. + await openTab(user, blade, 'Play'); + const actions = () => screen.getByRole('region', { name: 'Attacks and actions' }); + await waitFor(() => expect(within(actions()).getByText(/\+5 to hit, 1d4\+3 piercing/)).toBeTruthy()); + await user.click(within(actions()).getByRole('button', { name: 'Roll Fixture Needle attack' })); + const lastRoll = screen.getByRole('status', { name: 'Last roll' }); + await waitFor(() => expect(lastRoll.textContent).toMatch(/Fixture Needle attack: \d+ \(1d20\)/)); + expect(lastRoll.textContent).toMatch(/Fixture Needle to hit \+5/); + const reactions = within(actions()).getByRole('region', { name: 'Reactions' }); + expect(within(reactions).getByRole('button', { name: 'Roll Riposte damage (1d6)' })).toBeTruthy(); +}); + +it('adds an attack of your own on Inventory, rolls it on Play with advantage, and the roll shows in Last roll (item 18)', async () => { + const user = userEvent.setup(); + render(); + await createCharacter(user, { name: 'E2E Sling', scores: {}, cls: /^Fixture Duelist/ }); + await pick(user, /^Fixture Duelist: choose 2/, /^Duelist Skill: Acrobatics/); + await pick(user, /^Fixture Duelist: choose 2/, /^Duelist Skill: Insight/); + await user.click(await screen.findByRole('button', { name: 'Create and save' })); + const hero = await screen.findByRole('article', { name: 'E2E Sling' }); + + // Inventory: an item and an attack of your own. Neither changes a calculation. + await openTab(user, hero, 'Gear'); + const armorClass = summaryValue(hero, 'Armor Class'); + const items = () => screen.getByRole('region', { name: 'Your own items' }); + await user.click(within(items()).getByRole('button', { name: 'Add an item of your own' })); + await user.type(within(items()).getByRole('textbox', { name: 'Name' }), 'Testy Rope'); + await user.click(within(items()).getByRole('button', { name: 'Save item' })); + await expectStatus(/^Added Testy Rope\.$/); + await waitFor(() => expect(document.activeElement).toBe(within(items()).getByRole('button', { name: 'Edit Testy Rope' }))); // focus can land a tick after the status text + + const own = () => screen.getByRole('region', { name: 'Your own attacks' }); + await user.click(within(own()).getByRole('button', { name: 'Add an attack of your own' })); + await user.type(within(own()).getByRole('textbox', { name: 'Name' }), 'Testy Sling'); + await user.clear(within(own()).getByRole('spinbutton', { name: 'To hit bonus' })); + await user.type(within(own()).getByRole('spinbutton', { name: 'To hit bonus' }), '5'); + // The dice engine's own message for bad damage, linked to the field; nothing is saved. + const damage = within(own()).getByRole('textbox', { name: 'Damage (optional)' }); + await user.type(damage, '5'); + await user.click(within(own()).getByRole('button', { name: 'Save attack' })); + await waitFor(() => expect(damage.getAttribute('aria-invalid')).toBe('true')); + expect(document.getElementById(damage.getAttribute('aria-describedby')!.split(' ').at(-1)!)?.textContent).toMatch(/dice/i); + await user.clear(damage); + await user.type(damage, '1d6+2'); + await user.selectOptions(within(own()).getByRole('combobox', { name: 'Damage type (optional)' }), 'Bludgeoning'); + await user.click(within(own()).getByRole('button', { name: 'Save attack' })); + await expectStatus(/^Added Testy Sling\.$/); + expect(summaryValue(hero, 'Armor Class')).toBe(armorClass); + + // Play: the attack is listed (the panel shows for a character with only custom attacks) and rolled with advantage. + await openTab(user, hero, 'Play'); + const actions = () => screen.getByRole('region', { name: 'Attacks and actions' }); + expect(within(actions()).getAllByRole('button', { name: 'Roll Testy Sling attack' })).toHaveLength(1); + await user.click(screen.getByRole('radio', { name: 'Advantage' })); + await user.click(within(actions()).getByRole('button', { name: 'Roll Testy Sling attack' })); + const lastRoll = screen.getByRole('status', { name: 'Last roll' }); + await waitFor(() => expect(lastRoll.textContent).toMatch(/Testy Sling attack: \d+ \(1d20, advantage\)/)); + expect(lastRoll.textContent).toMatch(/Testy Sling to hit \+5/); + await user.click(within(actions()).getByRole('button', { name: 'Roll Testy Sling damage' })); + await waitFor(() => expect(lastRoll.textContent).toMatch(/Testy Sling damage \(bludgeoning\): \d+ \(1d6\+2\)/)); +}); + +it('switches a toggled effect on and off, spends a chosen amount, and a long rest proposes the toggle off', async () => { + // M3 B2 (content v6) with the original fixture feat "Fixture Radiant Stance": a stance (+2 AC, spends 1 radiance) and a + // variable-cost surge. PB 2 at level 1, so 2 radiance. + const user = userEvent.setup(); + render(); + await createCharacter(user, { name: 'E2E Stance', scores: {}, cls: /^Fixture Duelist/, other: /^Fixture Radiant Stance/ }); + await pick(user, /^Fixture Duelist: choose 2/, /^Duelist Skill: Acrobatics/); + await pick(user, /^Fixture Duelist: choose 2/, /^Duelist Skill: Insight/); + await user.click(await screen.findByRole('button', { name: 'Create and save' })); + const stance = await screen.findByRole('article', { name: 'E2E Stance' }); + + const armorClass = () => Number(/^(\d+)/.exec(summaryValue(stance, 'Armor Class'))![1]); + const before = armorClass(); + const actions = () => screen.getByRole('region', { name: 'Attacks and actions' }); + await user.click(within(actions()).getByRole('checkbox', { name: /^Radiant stance/ })); + await waitFor(() => expect(armorClass()).toBe(before + 2)); + const resources = () => screen.getByRole('region', { name: 'Resources' }); + expect(within(resources()).getByRole('heading', { name: 'Radiance: 1 of 2' })).toBeTruthy(); + + // The surge spends a chosen amount (1 to the cost or what is left): here only 1 is left. + await user.click(within(actions()).getByRole('button', { name: 'Roll Radiant surge (1d6)' })); + const lastRoll = screen.getByRole('status', { name: 'Last roll' }); + await user.type(await within(lastRoll).findByRole('spinbutton', { name: 'Radiance to spend (1 to 1)' }), '1'); + await user.click(within(lastRoll).getByRole('button', { name: /^Spend 1 Radiance/ })); + await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Radiance: 0 of 2' })).toBeTruthy()); + + // The long rest proposes switching it off (and restores radiance). + await user.click(screen.getByRole('button', { name: 'Long rest…' })); + const rest = await screen.findByRole('region', { name: 'Long rest' }); + expect(await within(rest).findByRole('checkbox', { name: /^Radiant stance: 1 → 0/ })).toBeTruthy(); + await user.click(within(rest).getByRole('button', { name: 'Finish long rest' })); + await waitFor(() => expect(armorClass()).toBe(before)); + expect(within(actions()).getByRole('checkbox', { name: /^Radiant stance/ }).checked).toBe(false); +}); + +it('records a gap note on a field and a feature, resolves one, and deletes one after confirming', async () => { + // M3 B3: session feedback, stored locally and never changing the character. + const user = userEvent.setup(); + render(); + await createCharacter(user, { name: 'E2E Gaps', family: 'srd-5.1', scores: {}, species: /^Fixture Quickfoot/ }); + await user.click(await screen.findByRole('button', { name: 'Create and save' })); + const sheet = await screen.findByRole('article', { name: 'E2E Gaps' }); + const armorClass = summaryValue(sheet, 'Armor Class'); + await openTab(user, sheet, 'Skills and saves'); + const armorClassHeading = screen.getByRole('heading', { name: /^Armor Class:/ }).textContent; + + await openTab(user, sheet, 'Features'); // gap notes end the Features tab + const gaps = () => screen.getByRole('region', { name: /^Gap notes/ }); + expect(await within(gaps()).findByText('No gap notes yet.')).toBeTruthy(); + const form = within(gaps()).getByRole('form', { name: 'New gap note' }); + const about = within(form).getByRole('combobox', { name: /^About/ }); + const text = within(form).getByRole('textbox', { name: /^What was missing or wrong/ }); + + await user.selectOptions(about, within(about).getByRole('option', { name: 'Armor Class' })); + await user.type(text, 'The table grants a cover bonus here.'); + await user.click(within(form).getByRole('button', { name: 'Save note' })); + await waitFor(() => expect(appStatus().textContent).toBe('Gap note saved for Armor Class.')); + expect(within(gaps()).getByText('The table grants a cover bonus here.')).toBeTruthy(); + + // M3 C5: "Report a gap" on a feature pre-fills the picker and moves focus to the note's text. + await openTab(user, sheet, 'Features'); + const features = within(screen.getByRole('article', { name: 'E2E Gaps' })).getByRole('region', { name: 'Features' }); + await user.click(within(features).getByRole('button', { name: 'Report a gap: Fixture Quickfoot' })); + expect((about as HTMLSelectElement).selectedOptions[0]!.textContent).toBe('Fixture Quickfoot'); + await waitFor(() => expect(document.activeElement).toBe(text)); + expect(within(sheet).getByRole('tab', { name: 'Features' }).getAttribute('aria-selected')).toBe('true'); + await user.type(text, 'Speed bonus should apply while unarmored only.'); + await user.click(within(form).getByRole('button', { name: 'Save note' })); + await waitFor(() => expect(within(gaps()).getByRole('heading').textContent).toBe('Gap notes: 2 open')); + + await user.click(within(gaps()).getByRole('button', { name: 'Mark resolved: Armor Class' })); + await waitFor(() => expect(within(gaps()).getByRole('heading').textContent).toBe('Gap notes: 1 open')); + expect(within(gaps()).getByRole('button', { name: 'Reopen: Armor Class' })).toBeTruthy(); + + // "Report a gap" on a field works the same way (the field's details hold the button). + await openTab(user, sheet, 'Skills and saves'); + const armor = within(screen.getByRole('article', { name: 'E2E Gaps' })).getByRole('region', { name: /^Armor Class:/ }); + await user.click(within(armor).getByRole('heading')); + await user.click(within(armor).getByRole('button', { name: 'Report a gap: Armor Class' })); + expect((about as HTMLSelectElement).selectedOptions[0]!.textContent).toBe('Armor Class'); + await waitFor(() => expect(document.activeElement).toBe(text)); + // "Report a gap" left Features as the remembered tab; move the memory off it so the deep link below is what selects Features. + await openTab(user, sheet, 'Play'); + + // M3 C5: the list across characters shows the open note with its character; resolved ones only on request. + await user.click(within(screen.getByRole('navigation', { name: 'Main' })).getByRole('button', { name: 'Help' })); + const all = await screen.findByRole('region', { name: 'Gap notes' }); // a section of the Help screen; its list keeps "of all characters" + const allList = await within(all).findByRole('list', { name: 'Gap notes of all characters' }); + const mine = () => within(allList).getAllByRole('listitem').filter((li: HTMLElement) => li.textContent!.startsWith('E2E Gaps')); + expect(mine().map((li: HTMLElement) => li.textContent)).toEqual([expect.stringContaining('Speed bonus should apply while unarmored only.')]); + await user.click(within(all).getByRole('checkbox', { name: 'Show resolved notes' })); + await waitFor(() => expect(mine()).toHaveLength(2)); + await user.click(within(all).getAllByRole('button', { name: 'Open E2E Gaps' })[0]!); + await screen.findByRole('article', { name: 'E2E Gaps' }); + // "Open " from the Help screen's Gap notes section opens the sheet on Features, where the notes are. + expect(within(screen.getByRole('article', { name: 'E2E Gaps' })).getByRole('tab', { name: 'Features' }).getAttribute('aria-selected')).toBe('true'); + // The reopened sheet loads its notes again; wait for them before using them. + await within(gaps()).findByText('Speed bonus should apply while unarmored only.'); + + // Deleting asks first; "Keep note" leaves it. + const quickfootNote = () => within(gaps()).getByText('Speed bonus should apply while unarmored only.').closest('li')!; + await user.click(within(quickfootNote()).getByRole('button', { name: 'Delete…' })); + await user.click(within(quickfootNote()).getByRole('button', { name: 'Keep note' })); + await user.click(within(quickfootNote()).getByRole('button', { name: 'Delete…' })); + await user.click(within(quickfootNote()).getByRole('button', { name: 'Delete note' })); + await waitFor(() => expect(within(gaps()).queryByText('Speed bonus should apply while unarmored only.')).toBeNull()); + expect(within(gaps()).getByRole('heading').textContent).toBe('Gap notes: 0 open'); + + // Notes never change the character's sheet. + expect(summaryValue(screen.getByRole('article', { name: 'E2E Gaps' }), 'Armor Class')).toBe(armorClass); + await openTab(user, screen.getByRole('article', { name: 'E2E Gaps' }), 'Skills and saves'); + expect(screen.getByRole('heading', { name: /^Armor Class:/ }).textContent).toBe(armorClassHeading); +}); + +it('a roll from any tab shows in the status bar', async () => { + const user = userEvent.setup(); + render(); + await createCharacter(user, { name: 'E2E Barwatch', family: 'srd-5.2.1', scores: { Intelligence: 16 }, cls: /^Fixture Arcanist/ }); + const picker = await screen.findByRole('group', { name: /^Fixture Arcanist spells \(0 of 3 cantrips, 0 of 4 prepared spells\)/ }); + await user.click(within(picker).getByRole('checkbox', { name: /^Fixture Spark/ })); + await user.click(screen.getByRole('button', { name: 'Create and save' })); + const sheet = await screen.findByRole('article', { name: 'E2E Barwatch' }); + + // Gear: a weapon, so Play has an attack to roll. + await openTab(user, sheet, 'Gear'); + const equipment = () => screen.getByRole('region', { name: 'Equipment' }); + await waitFor(() => expect(within(equipment()).getByRole('option', { name: /^Fixture Needle/ })).toBeTruthy()); + await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^Fixture Needle/ })); + await user.click(within(equipment()).getByRole('button', { name: 'Add' })); + await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip Fixture Needle' })); + + // The last roll is the one live node inside the status bar, whichever tab rolled it. + const bar = () => within(screen.getByRole('region', { name: 'Status' })); + expect(screen.getByRole('region', { name: 'Status' }).classList.contains('status-bar')).toBe(true); + const lastRoll = () => bar().getByRole('status', { name: 'Last roll' }); + + await openTab(user, sheet, 'Play'); + const actions = () => screen.getByRole('region', { name: 'Attacks and actions' }); + await user.click(await within(actions()).findByRole('button', { name: 'Roll Fixture Needle attack' })); + await waitFor(() => expect(lastRoll().textContent).toMatch(/Fixture Needle attack: \d+ \(1d20\)/)); + + await openTab(user, sheet, 'Spells'); + const spells = () => within(screen.getByRole('article', { name: 'E2E Barwatch' })).getByRole('region', { name: 'Spells and slots' }); + await user.click(within(spells()).getByRole('button', { name: 'Roll Fixture Spark attack' })); + await waitFor(() => expect(lastRoll().textContent).toMatch(/Fixture Spark \(spell attack\): \d+ \(1d20\)/)); + expect(lastRoll().textContent).not.toMatch(/Fixture Needle/); + + await openTab(user, sheet, 'Skills and saves'); + const intSave = screen.getByRole('region', { name: /^Intelligence saving throw:/ }); + await user.click(within(intSave).getByRole('heading')); + await user.click(within(intSave).getByRole('button', { name: 'Roll Intelligence saving throw' })); + await waitFor(() => expect(lastRoll().textContent).toMatch(/Intelligence saving throw \(d20 test\): \d+ \(1d20\)/)); + expect(lastRoll().textContent).not.toMatch(/Fixture Spark/); +}); + +it('shows the Bloodied chip and switches an auto toggle on at half hit points, and Undo takes both away (item 20, D38)', async () => { + const user = userEvent.setup(); + // Setup through the client: a homebrew feat (content schema v10) whose toggle switches itself while bloodied, and a character with 20 hit points. + const source = await client.createHomebrewSource('E2E Grit Book', ['srd-5.2.1']); + const draft = await client.saveDraft({ + contentId: crypto.randomUUID(), + revisionId: '00000000-0000-0000-0000-000000000000', + kind: 'feat', + name: 'E2E Grit', + rulesFamilies: ['srd-5.2.1'], + provenance: { sourceId: source.id }, + status: 'draft', + effects: [ + { type: 'toggle', id: 'grit-toggle', toggleId: 'grit', label: 'E2E grit', autoWhen: 'bloodied' }, + { type: 'modifier', id: 'grit-ac', operation: 'bonus', target: 'armorClass', value: '2', timing: 'whileActive', toggle: 'grit' }, + ], + }); + const feat = (await client.publish(draft)).published; + const created = await client.createCharacter({ name: 'E2E Grit Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [feat] }); + await client.saveCharacter({ ...created.character, overrides: [{ field: 'hitPoints', value: 20 }] }); + + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Grit Hero/ })); + const sheet = await screen.findByRole('article', { name: 'E2E Grit Hero' }); + await openTab(user, sheet, 'Play'); + const summary = () => within(sheet).getByRole('region', { name: 'Status' }); + const effects = () => within(screen.getByRole('region', { name: 'Attacks and actions' })).getByRole('group', { name: /Active effects/ }); + const armorClass = summaryValue(sheet, 'Armor Class'); + expect(within(summary()).queryByText('Bloodied')).toBeNull(); + expect(effects().textContent).toMatch(/E2E grit.*On while bloodied \(off now\)/); + expect(within(effects()).queryByRole('checkbox')).toBeNull(); // no switch: the sheet decides + + // Damage to exactly half (10 of 20): the chip, the toggle and its +2 Armor Class. + const hpPanel = () => screen.getByRole('region', { name: /^Hit points:/ }); + await user.type(within(hpPanel()).getByRole('spinbutton', { name: 'Amount' }), '10'); + await user.click(within(hpPanel()).getByRole('button', { name: 'Take damage' })); + await waitFor(() => expect(within(summary()).getByText('Bloodied')).toBeTruthy()); + expect(effects().textContent).toMatch(/On while bloodied \(on now\)/); + expect(Number(summaryValue(sheet, 'Armor Class'))).toBe(Number(armorClass) + 2); + + // Undo puts the hit points back exactly; the chip, the toggle and the bonus go with them. + await user.click(await screen.findByRole('button', { name: 'Undo last change: damage 10' })); + await waitFor(() => expect(within(summary()).queryByText('Bloodied')).toBeNull()); + expect(effects().textContent).toMatch(/On while bloodied \(off now\)/); + expect(summaryValue(sheet, 'Armor Class')).toBe(armorClass); +}); + +it('lists a toggle and a resource with an activation under their group, and switching the toggle keeps focus on it (item 22, R157)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Reflex Book', ['srd-5.2.1']); + const draft = await client.saveDraft({ + contentId: crypto.randomUUID(), + revisionId: '00000000-0000-0000-0000-000000000000', + kind: 'feat', + name: 'E2E Reflex', + rulesFamilies: ['srd-5.2.1'], + provenance: { sourceId: source.id }, + status: 'draft', + effects: [ + { type: 'toggle', id: 'guard-toggle', toggleId: 'guard', label: 'E2E guard', activation: 'reaction' }, + { type: 'modifier', id: 'guard-ac', operation: 'bonus', target: 'armorClass', value: '2', timing: 'whileActive', toggle: 'guard' }, + { type: 'toggle', id: 'calm-toggle', toggleId: 'calm', label: 'E2E calm' }, + { type: 'resource', id: 'surge-resource', resourceId: 'surge', label: 'E2E surge', maximum: '2', activation: 'bonusAction' }, + ], + }); + const feat = (await client.publish(draft)).published; + await client.createCharacter({ name: 'E2E Reflex Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [feat] }); + + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Reflex Hero/ })); + const sheet = await screen.findByRole('article', { name: 'E2E Reflex Hero' }); + await openTab(user, sheet, 'Play'); + const actions = () => screen.getByRole('region', { name: 'Attacks and actions' }); + const armorClass = summaryValue(sheet, 'Armor Class'); + + expect(within(within(actions()).getByRole('group', { name: /Active effects/ })).getByRole('checkbox', { name: /E2E calm/ })).toBeTruthy(); // no activation: stays + expect(within(within(actions()).getByRole('group', { name: /Active effects/ })).queryByRole('checkbox', { name: /E2E guard/ })).toBeNull(); + const resources = within(sheet).getByRole('region', { name: 'Resources' }); + expect(within(within(resources).getByRole('region', { name: 'Bonus actions' })).getByRole('heading', { name: /^E2E surge: 2 of 2/ })).toBeTruthy(); + + await user.click(within(within(actions()).getByRole('region', { name: 'Reactions' })).getByRole('checkbox', { name: /E2E guard/ })); + await waitFor(() => expect(Number(summaryValue(sheet, 'Armor Class'))).toBe(Number(armorClass) + 2)); + const guard = within(within(actions()).getByRole('region', { name: 'Reactions' })).getByRole('checkbox', { name: /E2E guard/ }) as HTMLInputElement; + expect(guard.checked).toBe(true); + expect(document.activeElement).toBe(guard); +}); + +it('carries two copies of a charged wand that needs attunement: attuning applies it, charges are separate, and a long rest returns them by the rolled total (item 25)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Wand Book', ['srd-5.2.1']); + const draft = await client.saveDraft({ + contentId: crypto.randomUUID(), + revisionId: '00000000-0000-0000-0000-000000000000', + kind: 'item', + name: 'E2E Wand', + rulesFamilies: ['srd-5.2.1'], + provenance: { sourceId: source.id }, + status: 'draft', + effects: [ + { type: 'modifier', id: 'wand-ac', operation: 'bonus', target: 'armorClass', value: '2' }, + { type: 'item', id: 'wand-use', requiresAttunement: true, charges: { max: 3, recovery: { period: 'longRest', regain: '1d3' } } }, + ], + }); + await client.publish(draft); + await client.createCharacter({ name: 'E2E Wand Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [] }); + + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Wand Hero/ })); + const hero = await screen.findByRole('article', { name: 'E2E Wand Hero' }); + await openTab(user, hero, 'Gear'); + const equipment = () => screen.getByRole('region', { name: 'Equipment' }); + const armorClass = () => Number(/^(\d+)/.exec(summaryValue(hero, 'Armor Class'))![1]); + const before = armorClass(); + + // Two copies: an item with charges is offered again once it is carried. + for (const copies of [1, 2]) { + await waitFor(() => expect(within(equipment()).getByRole('option', { name: /^E2E Wand/ })).toBeTruthy()); + await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^E2E Wand/ })); + await user.click(within(equipment()).getByRole('button', { name: 'Add' })); + await waitFor(() => expect(within(equipment()).getAllByRole('checkbox', { name: /^Equip E2E Wand/ })).toHaveLength(copies)); + } + expect(within(equipment()).getAllByText('3 of 3 charges left')).toHaveLength(2); // carried: charges show on Inventory too + + // Equipped but not attuned: nothing applies, and the sheet says so. Attuning applies it once. + await user.click(within(equipment()).getByRole('checkbox', { name: 'Equip E2E Wand (copy 1 of 2)' })); + await within(equipment()).findByText('E2E Wand (copy 1 of 2) is not attuned, so its effects do not apply.'); + expect(armorClass()).toBe(before); + await user.click(within(equipment()).getByRole('checkbox', { name: 'Attuned: E2E Wand (copy 1 of 2)' })); + await waitFor(() => expect(armorClass()).toBe(before + 2)); + + // Separate counts; focus stays on the button that was pressed. + const spend = () => within(equipment()).getByRole('button', { name: 'Spend a charge: E2E Wand (copy 1 of 2)' }); + await user.click(spend()); + await user.click(spend()); + await waitFor(() => expect(within(equipment()).getByText('1 of 3 charges left')).toBeTruthy()); + expect(within(equipment()).getByText('3 of 3 charges left')).toBeTruthy(); + expect(document.activeElement).toBe(spend()); + + // A long rest asks for the 1d3, takes the total as rolled at the table, and returns that many (capped at the two spent). + await user.click(screen.getByRole('button', { name: 'Long rest…' })); + const rest = await screen.findByRole('region', { name: 'Long rest' }); + await user.type(await within(rest).findByLabelText('E2E Wand: 1d3 rolled at the table (total)'), '2'); + await user.click(within(rest).getByRole('button', { name: 'Add the 1d3 total: E2E Wand' })); + expect(await within(rest).findByRole('checkbox', { name: /^E2E Wand charges: 1 → 3/ })).toBeTruthy(); + const finish = within(rest).getByRole('button', { name: 'Finish long rest' }); + await waitFor(() => expect(finish.getAttribute('aria-disabled')).toBe('false')); + await user.click(finish); + + await waitFor(() => expect(screen.queryByRole('region', { name: 'Long rest' })).toBeNull()); + await openTab(user, hero, 'Gear'); + await waitFor(() => expect(within(equipment()).getAllByText('3 of 3 charges left')).toHaveLength(2)); +}); + +it('adds a companion on Play, damages it, undoes that exactly, and rolls its attack (item 23, D39)', async () => { + const user = userEvent.setup(); + await client.createCharacter({ name: 'E2E Handler', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [] }); + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Handler/ })); + const hero = await screen.findByRole('article', { name: 'E2E Handler' }); + await openTab(user, hero, 'Play'); + + const companions = () => screen.getByRole('region', { name: 'Companions' }); + await user.click(within(companions()).getByRole('button', { name: 'Add a companion' })); + await user.type(within(companions()).getByRole('textbox', { name: 'Name' }), 'Testy Hound'); + await user.clear(within(companions()).getByRole('spinbutton', { name: 'Hit point maximum' })); + await user.type(within(companions()).getByRole('spinbutton', { name: 'Hit point maximum' }), '20'); + await user.click(within(companions()).getByRole('button', { name: 'Add an attack line' })); + await user.type(within(companions()).getByRole('textbox', { name: 'Attack 1 name' }), 'Testy Bite'); + await user.clear(within(companions()).getByRole('spinbutton', { name: 'Attack 1 to hit bonus' })); + await user.type(within(companions()).getByRole('spinbutton', { name: 'Attack 1 to hit bonus' }), '4'); + await user.type(within(companions()).getByRole('textbox', { name: 'Attack 1 damage (optional)' }), '1d6+2'); + await user.click(within(companions()).getByRole('button', { name: 'Save companion' })); + await expectStatus(/^Added Testy Hound\.$/); + + // Damage goes through the play command; the card shows it and Undo puts the hit points back exactly. + const dog = () => screen.getByRole('region', { name: 'Testy Hound' }); + await user.type(within(dog()).getByRole('spinbutton', { name: 'Amount' }), '8'); + await user.click(within(dog()).getByRole('button', { name: /^Take damage/ })); + await waitFor(() => expect(within(dog()).getByText('Hit points: 12 of 20')).toBeTruthy()); + expect(document.activeElement).toBe(within(dog()).getByRole('button', { name: /^Take damage/ })); + await user.click(await screen.findByRole('button', { name: 'Undo last change: companion damage 8' })); + await waitFor(() => expect(within(dog()).getByText('Hit points: 20 of 20')).toBeTruthy()); + + // Set temporary hit points, then damage takes them first. + await user.type(within(dog()).getByRole('spinbutton', { name: 'Amount' }), '5'); + await user.click(within(dog()).getByRole('button', { name: /^Set temporary hit points/ })); + await waitFor(() => expect(within(dog()).getByText('Hit points: 20 of 20, 5 temporary')).toBeTruthy()); + await user.type(within(dog()).getByRole('spinbutton', { name: 'Amount' }), '7'); + await user.click(within(dog()).getByRole('button', { name: /^Take damage/ })); + await waitFor(() => expect(within(dog()).getByText('Hit points: 18 of 20')).toBeTruthy()); + + // Its attack rolls through the dice engine and shows in Last roll like an attack of your own. + await user.click(within(dog()).getByRole('button', { name: /^Roll Testy Bite attack/ })); + const lastRoll = screen.getByRole('status', { name: 'Last roll' }); + await waitFor(() => expect(lastRoll.textContent).toMatch(/Testy Hound: Testy Bite attack: \d+ \(1d20\)/)); + expect(lastRoll.textContent).toMatch(/Testy Bite to hit \+4/); + await user.click(within(dog()).getByRole('button', { name: /^Roll Testy Bite damage/ })); + await waitFor(() => expect(lastRoll.textContent).toMatch(/Testy Hound: Testy Bite damage: \d+ \(1d6\+2\)/)); +}); diff --git a/src/Ui/e2e/sharing.e2e.tsx b/src/Ui/e2e/sharing.e2e.tsx new file mode 100644 index 00000000..738221a6 --- /dev/null +++ b/src/Ui/e2e/sharing.e2e.tsx @@ -0,0 +1,486 @@ +// End-to-end UI flow against the real DevHost (same CommandDispatcher as the shell). Only the transport differs from the desktop +// app: HTTP to loopback instead of the WebView2 bridge, so export takes the download fallback instead of the native Save dialog. +import { readdirSync, readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, expect, inject, it, vi } from 'vitest'; +import { zip } from './zip'; +import { App } from '../src/App'; +import { client } from '../src/api/client'; +import { downloadBase64 } from '../src/files'; +import { appStatus, bytesOf, createCharacter, expectStatus, openMore, openTab, srd, startNewCharacter } from './helpers'; + +vi.mock('../src/api/client', async (importOriginal) => { + const { inject } = await import('vitest'); + const { createHttpTransport } = await import('../src/api/transport'); + const original = await importOriginal(); + const { endpoint, token } = inject('devHost'); + return { ...original, client: original.createClient(createHttpTransport(endpoint, { 'X-TomeStack-Token': token })) }; +}); + +vi.mock('../src/files', async (importOriginal) => ({ + ...(await importOriginal()), + downloadBase64: vi.fn(), +})); + +afterEach(() => { + cleanup(); + // One jsdom window serves the whole file: a preference or `html` attribute left by one test would leak into the next. + // The per-character tab memory stays (ids are unique per test and the deep-link test relies on it). + for (const key of Object.keys(localStorage)) if (key.startsWith('tomestack.') && !key.startsWith('tomestack.sheetTab.')) localStorage.removeItem(key); + for (const key of Object.keys(document.documentElement.dataset)) delete document.documentElement.dataset[key]; +}); + +/** Add-ons live in Settings now (no sidebar entry): opens Settings and waits for the lazy Add-ons section. */ +async function openAddOns(user: ReturnType): Promise { + await user.click(await screen.findByRole('button', { name: 'Settings' })); + await screen.findByRole('heading', { name: 'Add-ons' }); +} + +/** Opens the "Opening this in an older TomeStack?" disclosure inside `scope`, then picks the radio for `release` (e.g. "0.7.0"). */ +async function chooseOlderTarget(user: ReturnType, scope: HTMLElement, release: string): Promise { + const summary = within(scope).getByText(/^Opening this in an older TomeStack\?/); + if (!summary.closest('details')!.open) await user.click(summary); + await user.click(within(scope).getByRole('radio', { name: release })); +} + +it('marks a source as shareable after confirming it is your own work, saves a source pack and imports it (M6 slice 1)', async () => { + const user = userEvent.setup(); + // Setup through the client: your own source with a published feat, and a source a PDF was attached to. + const own = await client.createHomebrewSource('E2E Own Notes', ['srd-5.1']); + const draft = await client.saveDraft({ + contentId: crypto.randomUUID(), + revisionId: '00000000-0000-0000-0000-000000000000', + kind: 'feat', + name: 'E2E Own Feat', + rulesFamilies: ['srd-5.1'], + provenance: { sourceId: own.id }, + status: 'draft', + summary: 'An original feat.', + effects: [], + }); + await client.publish(draft); + const scanned = await client.createHomebrewSource('E2E Scanned Notes', ['srd-5.1']); + await client.attachPdfData(scanned.id, 'e2e-scan.pdf', btoa('%PDF-1.4\n% e2e\n%%EOF\n')); + + render(); + await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); + const mine = await screen.findByRole('listitem', { name: 'E2E Own Notes' }); + expect(within(mine).getByText('Not shared.')).toBeTruthy(); + // A source a PDF was attached to is import-derived for good: it offers no way to share it. + const theirs = screen.getByRole('listitem', { name: 'E2E Scanned Notes' }); + expect(within(theirs).getByText(/Holds imported material \(from a PDF or a Markdown file\): never shared/)).toBeTruthy(); + expect(within(theirs).queryByRole('button', { name: 'Mark as shareable…' })).toBeNull(); + + // Marking needs the author's confirmation. + await user.click(within(mine).getByRole('button', { name: 'Mark as shareable…' })); + const confirm = await screen.findByRole('alertdialog', { name: 'Mark E2E Own Notes as shareable?' }); + const mark = within(confirm).getByRole('button', { name: 'Mark as shareable' }); + expect(mark.disabled).toBe(true); + await user.click(within(confirm).getByRole('checkbox', { name: /The source is my own work/ })); + await user.click(mark); + await expectStatus(/E2E Own Notes is marked as shareable/); + await waitFor(() => expect(within(screen.getByRole('listitem', { name: 'E2E Own Notes' })).getByText(/Marked as shareable/)).toBeTruthy()); + + // The pack offers only shareable sources; DevHost has no Save dialog, so it downloads. + const packForm = screen.getByRole('region', { name: 'Share sources as a TomeStack file' }); + expect(within(packForm).queryByRole('checkbox', { name: 'E2E Scanned Notes' })).toBeNull(); + await user.click(within(packForm).getByRole('checkbox', { name: 'E2E Own Notes' })); + await user.click(within(packForm).getByRole('button', { name: 'Preview file' })); + const preview = await within(packForm).findByRole('region', { name: 'TomeStack file preview' }); + expect(preview.textContent).toMatch(/1 source, 1 published version/); + // L5: the preflight lists what goes (and what stays), and Save waits for it. + const preflight = await within(packForm).findByRole('region', { name: 'Preflight: TomeStack file' }); + expect(preflight.textContent).toMatch(/Included: 1 item\. Left out: 1\./); + expect(preflight.textContent).toMatch(/E2E Own Feat \(E2E Own Notes\): a draft; only published content is shared/); // the draft stays here + await waitFor(() => expect(within(preview).getByRole('button', { name: 'Save file…' }).disabled).toBe(false)); + const downloads = vi.mocked(downloadBase64).mock.calls.length; + await user.click(within(preview).getByRole('button', { name: 'Save file…' })); + await waitFor(() => expect(vi.mocked(downloadBase64).mock.calls.length).toBe(downloads + 1)); + const [fileName, base64] = vi.mocked(downloadBase64).mock.calls[downloads]!; + expect(fileName).toBe('E2E-Own-Notes-source-pack.tomestack.zip'); + + // Importing it: the preview says what a source pack is; here everything is already installed. + await user.upload(screen.getByLabelText('TomeStack file'), new File([bytesOf(base64)], fileName, { type: 'application/zip' })); + const importing = await screen.findByRole('region', { name: 'Import a TomeStack file' }); + expect(within(importing).getByText(/This TomeStack file holds sources\. Its sender stated that each source is their own work/)).toBeTruthy(); + await user.click(within(importing).getByRole('button', { name: 'Apply import' })); + await expectStatus(/unchanged/); + + // L5: a shareable source with nothing published blocks the pack, in words (the export would refuse it too). + const late = await client.createHomebrewSource('E2E Late Notes', ['srd-5.1']); + await client.setShareable(late.id, true, true); + await user.click(screen.getByRole('button', { name: 'Books and PDFs' })); + const lateForm = await screen.findByRole('region', { name: 'Share sources as a TomeStack file' }); + await user.click(await within(lateForm).findByRole('checkbox', { name: 'E2E Late Notes' })); + const blocked = await within(lateForm).findByRole('region', { name: 'Preflight: TomeStack file' }); + expect(within(blocked).getByRole('alert').textContent).toMatch(/E2E Late Notes: nothing is published yet/); +}); + +it('shares a campaign as a campaign pack that names what it leaves out, and imports it over a changed copy by choice (M6 slice 2)', async () => { + const user = userEvent.setup(); + // Setup through the client: your own shareable homebrew, homebrew you did not mark, and a campaign allowing both and the SRD. + async function homebrew(title: string, shareable: boolean) { + const source = await client.createHomebrewSource(title, ['srd-5.2.1']); + if (shareable) await client.setShareable(source.id, true, true); + const draft = await client.saveDraft({ + contentId: crypto.randomUUID(), + revisionId: '00000000-0000-0000-0000-000000000000', + kind: 'feat', + name: `${title} Feat`, + rulesFamilies: ['srd-5.2.1'], + provenance: { sourceId: source.id }, + status: 'draft', + summary: 'An original feat.', + effects: [], + }); + await client.publish(draft); + return source; + } + const harbor = await homebrew('E2E Harbor Notes', true); + const secret = await homebrew('E2E Secret Notes', false); + const campaign = await client.saveCampaign({ + id: '00000000-0000-0000-0000-000000000000', + name: 'E2E Harbor Table', + rulesFamily: 'srd-5.2.1', + allowedSources: ['52500000-0000-4000-8000-000000000001', harbor.id, secret.id], + houseRules: 'Original house rule: rests take a full day.', + }); + + render(); + const campaignsButton = await screen.findByRole('button', { name: 'Campaigns' }); + await waitFor(() => expect(campaignsButton.disabled).toBe(false)); + await user.click(campaignsButton); + await user.click(await screen.findByRole('button', { name: 'Share E2E Harbor Table…' })); + const share = await screen.findByRole('region', { name: 'Share E2E Harbor Table' }); + await waitFor(() => expect(share.textContent).toMatch(/1 source carried with 1 available version; System Reference Document 5\.2\.1 named, not copied/)); + // The guard: homebrew you did not mark as your own shareable work is only named. + const leftOut = within(share).getByRole('region', { name: 'Left out of the TomeStack file' }); + expect(leftOut.textContent).toMatch(/E2E Secret Notes .*not marked as shareable/); + + // DevHost has no Save dialog, so it downloads. + // L5: the preflight names the same source in words, and Save waits for it. + const campaignCheck = await within(share).findByRole('region', { name: 'Preflight: TomeStack file' }); + expect(campaignCheck.textContent).toMatch(/E2E Secret Notes.*not marked as your own shareable work/); + await waitFor(() => expect(within(share).getByRole('button', { name: 'Save TomeStack file…' }).disabled).toBe(false)); + const downloads = vi.mocked(downloadBase64).mock.calls.length; + await user.click(within(share).getByRole('button', { name: 'Save TomeStack file…' })); + await waitFor(() => expect(vi.mocked(downloadBase64).mock.calls.length).toBe(downloads + 1)); + const [fileName, base64] = vi.mocked(downloadBase64).mock.calls[downloads]!; + expect(fileName).toBe('E2E-Harbor-Table-campaign-pack.tomestack.zip'); + + // Here the campaign changes after the pack was made; importing it asks which version to keep. + await client.saveCampaign({ ...campaign, name: 'E2E Harbor Table (local)', allowedSources: ['52500000-0000-4000-8000-000000000001', harbor.id] }); + await user.upload(screen.getByLabelText('TomeStack file'), new File([bytesOf(base64)], fileName, { type: 'application/zip' })); + const importing = await screen.findByRole('region', { name: 'Import a TomeStack file' }); + expect(within(importing).getByText(/This TomeStack file holds a campaign/)).toBeTruthy(); + const apply = within(importing).getByRole('button', { name: 'Apply import' }); + expect(apply.disabled).toBe(true); + const decision = within(importing).getByRole('group', { name: 'Campaign “E2E Harbor Table” differs from yours' }); + expect(within(decision).getByRole('rowheader', { name: 'allowedSources' })).toBeTruthy(); + await user.click(within(decision).getByRole('radio', { name: 'Use the imported version' })); + await user.click(apply); + await expectStatus(/1 replaced.*copied to backups\/pre-import-.*\.db/); + expect((await client.listCampaigns()).find((c) => c.id === campaign.id)?.name).toBe('E2E Harbor Table'); +}); + +it('installs the sample extension after granting its permissions, runs its import and export hooks, and removes it (M6 slice 3)', async () => { + const user = userEvent.setup(); + // The external sample, packed as a user would: extension.json and transforms/ from examples/extensions. + const folder = resolve(process.cwd(), '../../examples/extensions/spell-list-and-sheet-summary'); + const files: Record = { 'extension.json': readFileSync(resolve(folder, 'extension.json')) }; + for (const name of readdirSync(resolve(folder, 'transforms'))) files[`transforms/${name}`] = readFileSync(resolve(folder, 'transforms', name)); + const extension = new File([zip(files)], 'spell-list-and-sheet-summary.tomestack-ext.zip', { type: 'application/zip' }); + await client.createCharacter({ name: 'E2E Ext Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 14, con: 12, int: 10, wis: 10, cha: 10 }, pins: [] }); + + render(); + await openAddOns(user); + // DevHost has no native Open dialog, so the browser picker is used. + await user.click(await screen.findByRole('button', { name: 'Install extension…' })); + await user.upload(screen.getByLabelText('Extension file'), extension); + const review = await screen.findByRole('region', { name: 'Install Spell list and sheet summary (sample)?' }); + const install = within(review).getByRole('button', { name: 'Install with these permissions' }); + expect(install.disabled).toBe(true); // nothing is granted until it is ticked + const permissions = within(within(review).getByRole('group', { name: 'Permissions to grant' })).getAllByRole('checkbox'); + expect(permissions).toHaveLength(4); + for (const permission of permissions) await user.click(permission); + await user.click(install); + await expectStatus(/Installed Spell list and sheet summary \(sample\) with 4 permissions/); + const item = await screen.findByRole('listitem', { name: 'Spell list and sheet summary (sample)' }); + + // Import: a CSV spell list becomes drafts in a new source; nothing is written before "Create drafts". + await user.click(within(item).getByRole('button', { name: 'Import a CSV spell list as draft spells' })); + const importRun = await screen.findByRole('region', { name: 'Run Import a CSV spell list as draft spells' }); + await user.clear(within(importRun).getByRole('textbox', { name: 'New source for the drafts' })); + await user.type(within(importRun).getByRole('textbox', { name: 'New source for the drafts' }), 'E2E Imported Spells'); + await user.click(within(importRun).getByRole('button', { name: 'Choose CSV file…' })); + const csv = readFileSync(resolve(folder, 'sample-spells.csv')); + await user.upload(screen.getByLabelText('Import a CSV spell list as draft spells: file'), new File([csv], 'sample-spells.csv', { type: 'text/csv' })); + const drafts = await within(importRun).findByRole('region', { name: 'Preview of Import a CSV spell list as draft spells' }); + expect(drafts.textContent).toMatch(/3 drafts in the new source E2E Imported Spells/); + expect(drafts.textContent).toMatch(/never shared/); + expect((await client.listSources()).some((s) => s.title === 'E2E Imported Spells')).toBe(false); + await user.click(within(drafts).getByRole('button', { name: 'Create drafts' })); + await expectStatus(/Created 3 drafts in the new source E2E Imported Spells/); + const imported = (await client.listSources()).find((s) => s.title === 'E2E Imported Spells')!; + expect(imported.importDerived).toBe(true); + expect((await client.contentBySource(imported.id)).every((e) => e.latest.status === 'draft')).toBe(true); + + // Export: the sheet summary, previewed and then saved (DevHost downloads). No local path reaches it. + await user.click(within(screen.getByRole('listitem', { name: 'Spell list and sheet summary (sample)' })).getByRole('button', { name: 'Export a sheet summary as Markdown' })); + const exportRun = await screen.findByRole('region', { name: 'Run Export a sheet summary as Markdown' }); + await user.selectOptions(within(exportRun).getByRole('combobox', { name: 'Character' }), 'E2E Ext Hero'); + await user.click(within(exportRun).getByRole('button', { name: 'Preview output' })); + const output = await within(exportRun).findByRole('region', { name: 'Preview of Export a sheet summary as Markdown' }); + expect(output.textContent).toMatch(/# E2E Ext Hero/); + const downloads = vi.mocked(downloadBase64).mock.calls.length; + await user.click(within(output).getByRole('button', { name: 'Save output…' })); + await waitFor(() => expect(vi.mocked(downloadBase64).mock.calls.length).toBe(downloads + 1)); + const [fileName, base64] = vi.mocked(downloadBase64).mock.calls[downloads]!; + expect(fileName).toBe('E2E-Ext-Hero-sheet-markdown.md'); + const markdown = new TextDecoder().decode(bytesOf(base64)); + expect(markdown).toMatch(/## Sources and licenses/); + expect(markdown.toLowerCase().replaceAll('\\', '/')).not.toContain(inject('devHost').dataDir.toLowerCase().replaceAll('\\', '/')); + + // Remove: its permissions and file go; its drafts stay. + await user.click(within(screen.getByRole('listitem', { name: 'Spell list and sheet summary (sample)' })).getByRole('button', { name: 'Remove Spell list and sheet summary (sample)…' })); + await user.click(within(await screen.findByRole('alertdialog', { name: 'Remove Spell list and sheet summary (sample)?' })).getByRole('button', { name: 'Remove' })); + await expectStatus(/Removed Spell list and sheet summary \(sample\)/); + expect(await client.listExtensions()).toEqual([]); + expect(await client.contentBySource(imported.id)).toHaveLength(3); +}); + +it('exports a character for Foundry VTT and as sheet JSON after a preview, with no local path in either file (M6 slice 4)', async () => { + const user = userEvent.setup(); + const character = await client.createCharacter({ name: 'E2E VTT Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 14, con: 12, int: 10, wis: 10, cha: 10 }, pins: [] }); + render(); + await user.click(await screen.findByRole('button', { name: /^E2E VTT Hero/ })); + const sheet = await screen.findByRole('article', { name: 'E2E VTT Hero' }); + await openMore(user, sheet, 'Export…'); + const panel = within(sheet).getByRole('region', { name: 'Export for a virtual tabletop' }); + const dataDir = inject('devHost').dataDir.toLowerCase().replaceAll('\\', '/'); + + // Foundry VTT (dnd5e): the preview names the pinned release, then DevHost downloads the file. + await user.click(within(panel).getByRole('radio', { name: /Foundry VTT \(dnd5e system\)/ })); + await user.click(within(panel).getByRole('button', { name: 'Preview export' })); + const preview = await within(panel).findByRole('region', { name: 'Export preview' }); + expect(preview.textContent).toMatch(/E2E-VTT-Hero\.foundry-dnd5e\.json.*checked against Foundry VTT 14\.367 with dnd5e 6\.0\.6/); + expect(preview.textContent).toMatch(/not affiliated with Foundry Gaming LLC/); + const downloads = vi.mocked(downloadBase64).mock.calls.length; + await within(panel).findByRole('region', { name: 'Preflight: shared sheet' }); + await waitFor(() => expect(within(preview).getByRole('button', { name: 'Save export file…' }).disabled).toBe(false)); + await user.click(within(preview).getByRole('button', { name: 'Save export file…' })); + await waitFor(() => expect(vi.mocked(downloadBase64).mock.calls.length).toBe(downloads + 1)); + const [foundryName, foundry64] = vi.mocked(downloadBase64).mock.calls[downloads]!; + expect(foundryName).toBe('E2E-VTT-Hero.foundry-dnd5e.json'); + const actorText = new TextDecoder().decode(bytesOf(foundry64)); + const actor = JSON.parse(actorText) as { type: string; name: string; _stats: { systemVersion: string } }; + expect([actor.type, actor.name, actor._stats.systemVersion]).toEqual(['character', 'E2E VTT Hero', '6.0.6']); + expect(actorText.toLowerCase().replaceAll('\\\\', '/').replaceAll('\\', '/')).not.toContain(dataDir); + + // The neutral sheet JSON. + await user.click(within(panel).getByRole('radio', { name: /TomeStack sheet \(JSON\)/ })); + await user.click(within(panel).getByRole('button', { name: 'Preview export' })); + const sheetPreview = await within(panel).findByRole('region', { name: 'Export preview' }); + await waitFor(() => expect(within(sheetPreview).getByRole('button', { name: 'Save export file…' }).disabled).toBe(false)); + await user.click(within(sheetPreview).getByRole('button', { name: 'Save export file…' })); + await waitFor(() => expect(vi.mocked(downloadBase64).mock.calls.length).toBe(downloads + 2)); + const [sheetName, sheet64] = vi.mocked(downloadBase64).mock.calls[downloads + 1]!; + expect(sheetName).toBe('E2E-VTT-Hero.tomestack-sheet.json'); + const model = JSON.parse(new TextDecoder().decode(bytesOf(sheet64))) as { format: string; formatVersion: number; character: { name: string } }; + expect([model.format, model.formatVersion, model.character.name]).toEqual(['tomestack.sheet', 1, 'E2E VTT Hero']); + expect(character.character.id).toBeTruthy(); +}); + +it('follows the authoring guides: the extension guide, packed as written, installs, is granted and exports its features with every notice (M6 slice 5)', async () => { + const user = userEvent.setup(); + // docs/authoring/extension.md, its tagged blocks exactly as the guide shows them. + const guide = readFileSync(resolve(process.cwd(), '../../docs/authoring/extension.md'), 'utf8'); + const files: Record = {}; + for (const match of guide.matchAll(/```json tomestack-example:([^\r\n]+)\r?\n([\s\S]*?)\r?\n```/g)) { + const name = match[1]!.trim(); + if (name === 'extension.json' || name.startsWith('transforms/')) files[name] = new TextEncoder().encode(match[2]!); + } + expect(Object.keys(files).sort()).toEqual(['extension.json', 'transforms/features-md.json']); + // A class, so the file has feature lines and an SRD notice. + await client.createCharacter({ name: 'E2E Guide Reader', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [], classes: [{ class: srd(11), level: 1 }] }); + + render(); + await openAddOns(user); + await user.click(await screen.findByRole('button', { name: 'Install extension…' })); + await user.upload(screen.getByLabelText('Extension file'), new File([zip(files)], 'example-feature-list.tomestack-ext.zip', { type: 'application/zip' })); + // "Tick the permissions and choose Install with these permissions." + const review = await screen.findByRole('region', { name: 'Install Example feature list?' }); + for (const permission of within(within(review).getByRole('group', { name: 'Permissions to grant' })).getAllByRole('checkbox')) await user.click(permission); + await user.click(within(review).getByRole('button', { name: 'Install with these permissions' })); + await expectStatus(/Installed Example feature list with 2 permissions/); + // "Then choose the hook (Export features as Markdown), pick a character …, choose Preview output, and Save output…" + await user.click(within(await screen.findByRole('listitem', { name: 'Example feature list' })).getByRole('button', { name: 'Export features as Markdown' })); + const run = await screen.findByRole('region', { name: 'Run Export features as Markdown' }); + await user.selectOptions(within(run).getByRole('combobox', { name: 'Character' }), 'E2E Guide Reader'); + await user.click(within(run).getByRole('button', { name: 'Preview output' })); + const output = await within(run).findByRole('region', { name: 'Preview of Export features as Markdown' }); + expect(output.textContent).toMatch(/# Features of E2E Guide Reader/); + const downloads = vi.mocked(downloadBase64).mock.calls.length; + await user.click(within(output).getByRole('button', { name: 'Save output…' })); + await waitFor(() => expect(vi.mocked(downloadBase64).mock.calls.length).toBe(downloads + 1)); + const [fileName, base64] = vi.mocked(downloadBase64).mock.calls[downloads]!; + expect(fileName).toBe('E2E-Guide-Reader-features-md.md'); + const text = new TextDecoder().decode(bytesOf(base64)); + expect(text).toMatch(/^- .+ \([a-z]+\), from .+$/m); // at least one feature line + expect(text).toMatch(/## Sources and licenses\n- .+CC-BY-4\.0/); + await client.removeExtension((await client.listExtensions()).find((x) => x.manifest.name === 'Example feature list')!.id); +}); + +it('shows different allowed content for two campaign profiles, and records a reasoned exception', async () => { + const user = userEvent.setup(); + render(); + const campaignsButton = await screen.findByRole('button', { name: 'Campaigns' }); + await waitFor(() => expect(campaignsButton.disabled).toBe(false)); + await user.click(campaignsButton); + + async function createCampaign(name: string, sources: RegExp[]) { + await user.click(await screen.findByRole('button', { name: 'New campaign' })); + const form = screen.getByRole('form', { name: 'Campaign' }); + await user.type(within(form).getByRole('textbox', { name: 'Campaign name' }), name); + await user.click(within(form).getByRole('radio', { name: /2024 rules/ })); + for (const source of sources) await user.click(within(form).getByRole('checkbox', { name: source })); + await user.click(within(form).getByRole('button', { name: 'Save campaign' })); + await waitFor(() => expect(appStatus().textContent).toBe(`Saved the campaign ${name}.`)); + } + await createCampaign('E2E Strict', [/^System Reference Document 5\.2\.1/]); + await createCampaign('E2E Open', [/^System Reference Document 5\.2\.1/, /^TomeStack Fixtures: 2024 Family/]); + + // The campaign is chosen on the Rules step; the backgrounds it governs are on the Background step (D32), so this flow + // walks the steps by hand instead of through `createCharacter`. + await startNewCharacter(user); + await user.type(await screen.findByRole('textbox', { name: 'Name' }), 'E2E Campaigner'); + const courier = () => screen.getByRole('radio', { name: /^Fixture Courier/ }); + const courierOff = () => courier().getAttribute('aria-disabled') === 'true'; // inert, never natively disabled (2.4.3) + const soldier = () => screen.getAllByRole('radio', { name: /^Soldier/ }).find((r) => r.getAttribute('aria-disabled') !== 'true'); + const toBackground = async () => { + await user.click(screen.getByRole('button', { name: 'Next: class' })); + await user.click(screen.getByRole('button', { name: 'Next: ability scores' })); + await user.click(screen.getByRole('radio', { name: 'Enter by hand' })); // the default method needs all six scores assigned + for (const next of ['Next: species', 'Next: background']) await user.click(screen.getByRole('button', { name: next })); + }; + const toRules = async () => { + for (let i = 0; i < 4; i++) await user.click(screen.getByRole('button', { name: 'Back' })); + }; + + // Profile 1: SRD only. The fixture background is listed but not allowed; the SRD one is. + // The Campaign picker appears once the campaign list arrives, which can be after the name is typed. + await user.selectOptions(await screen.findByRole('combobox', { name: 'Campaign' }), 'E2E Strict (2024 rules)'); + await toBackground(); + await waitFor(() => expect(courierOff()).toBe(true)); + expect(courier().closest('label')!.textContent).toMatch(/not allowed in this campaign/); + expect(soldier()).toBeTruthy(); + + // Profile 2: SRD and the 2024 fixtures. The same background is allowed. + await toRules(); + await user.selectOptions(screen.getByRole('combobox', { name: 'Campaign' }), 'E2E Open (2024 rules)'); + await toBackground(); + await waitFor(() => expect(courierOff()).toBe(false)); + + // Back to profile 1, with a deliberate exception: a reason is required before outside content can be picked. + await toRules(); + await user.selectOptions(screen.getByRole('combobox', { name: 'Campaign' }), 'E2E Strict (2024 rules)'); + await toBackground(); + await waitFor(() => expect(courierOff()).toBe(true)); + const sources = screen.getByRole('group', { name: 'Campaign sources' }); + await user.click(within(sources).getByRole('checkbox', { name: 'Use content from outside the campaign' })); + expect(courierOff()).toBe(true); // no reason yet + await user.type(within(sources).getByRole('textbox', { name: /^Reason/ }), 'DM approved'); + await waitFor(() => expect(courierOff()).toBe(false)); + await user.click(courier()); + await user.click(screen.getByRole('button', { name: 'Next: gear' })); + await user.click(screen.getByRole('button', { name: 'Next: choices' })); + await user.click(await screen.findByRole('button', { name: 'Create and save' })); + + const sheet = await screen.findByRole('article', { name: 'E2E Campaigner' }); + expect(within(sheet).getByText('Campaign: E2E Strict', { selector: '.tag' })).toBeTruthy(); + const notes = within(sheet).getByRole('region', { name: 'Campaign: E2E Strict' }); + expect(notes.textContent).toMatch(/Fixture Courier.*used by exception: DM approved/); +}); + +it('keeps the older-version choice behind a disclosure on the sheet export, and picks a release once opened', async () => { + const user = userEvent.setup(); + await client.createCharacter({ name: 'E2E Older Target', rulesFamily: 'srd-5.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [] }); + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Older Target/ })); + const sheet = await screen.findByRole('article', { name: 'E2E Older Target' }); + await openMore(user, sheet, 'Export…'); + const panel = within(sheet).getByRole('region', { name: 'Export' }); + // D103: only the previous minor is offered, so a build with no such release (the DevHost of an unreleased minor + // may have none) shows a plain hint and no choice at all. + await waitFor(() => expect(within(panel).queryByText(/^This TomeStack has no older version to save for\.$|^Opening this in an older TomeStack\?/)).not.toBeNull()); + if (within(panel).queryByText('This TomeStack has no older version to save for.')) { + expect(panel.querySelector('details')).toBeNull(); + expect(within(panel).queryByRole('group', { name: 'Which version will open this file?' })).toBeNull(); + return; + } + const release = within(panel).getAllByText(/^\d+\.\d+\.\d+$/, { selector: 'label' })[0]!.textContent!; + expect(panel.querySelector('details')!.open).toBe(false); + await chooseOlderTarget(user, panel, release); + expect((within(panel).getByRole('radio', { name: release }) as HTMLInputElement).checked).toBe(true); +}); + +it('prints a sheet with its license notices, and gap notes only when ticked', async () => { + // M3 C4: the printable backup. The print dialog is the browser's; here window.print is a spy. + const print = vi.spyOn(window, 'print').mockImplementation(() => {}); + const user = userEvent.setup(); + render(); + await createCharacter(user, { name: 'E2E Print', family: 'srd-5.1', scores: {}, species: /^Fixture Quickfoot/ }); + await user.click(await screen.findByRole('button', { name: 'Create and save' })); + const sheet = await screen.findByRole('article', { name: 'E2E Print' }); + + await openTab(user, sheet, 'Features'); + const gaps = within(sheet).getByRole('region', { name: /^Gap notes/ }); + const form = within(gaps).getByRole('form', { name: 'New gap note' }); + await user.selectOptions(within(form).getByRole('combobox', { name: /^About/ }), 'Armor Class'); + await user.type(within(form).getByRole('textbox', { name: /^What was missing or wrong/ }), 'Private note for the print test.'); + await user.click(within(form).getByRole('button', { name: 'Save note' })); + await within(gaps).findByText('Private note for the print test.'); + await openTab(user, sheet, 'Journal'); + const journal = within(sheet).getByRole('form', { name: 'New session note' }); + await user.type(within(journal).getByRole('textbox', { name: 'Note' }), 'Private session note for the print test.'); + await user.click(within(journal).getByRole('button', { name: 'Save session note' })); + await within(sheet).findByText('Private session note for the print test.'); + const detailsForm = within(sheet).getByRole('form', { name: 'Details' }); + await user.type(within(detailsForm).getByRole('textbox', { name: 'Backstory' }), 'Private backstory for the print test.'); + await user.click(within(detailsForm).getByRole('button', { name: 'Save details' })); + await expectStatus(/Details saved/); + + await openMore(user, sheet, 'Print…'); + const preview = await within(sheet).findByRole('region', { name: 'Print preview' }); + await waitFor(() => expect(document.activeElement).toBe(within(preview).getByRole('heading', { name: 'Print character' }))); // focus moves to the preview on open + expect(within(preview).getByRole('heading', { name: 'E2E Print' })).toBeTruthy(); + expect(within(preview).getByRole('table', { name: 'Abilities' })).toBeTruthy(); + expect(within(preview).getByText(/^Fixture Quickfoot/)).toBeTruthy(); + // The license notices of the sources used (the fixture sources here), and the version it was printed from. + await waitFor(() => expect(preview.querySelectorAll('.print-notice').length).toBeGreaterThan(0)); + await waitFor(() => expect(preview.textContent).toMatch(/Printed from TomeStack \d+\.\d+\.\d+/)); + // Gap notes are private: left out until ticked. No path ever appears. + expect(preview.textContent).not.toContain('Private note for the print test.'); + expect(preview.textContent).not.toMatch(/[A-Za-z]:\\|\/Users\/|\\Users\\/); + await user.click(within(preview).getByRole('checkbox', { name: /^Include gap notes/ })); + expect(await within(preview).findByText(/Private note for the print test\./)).toBeTruthy(); + // Session notes are private too: absent until their own box is ticked. + expect(preview.textContent).not.toContain('Private session note for the print test.'); + await user.click(within(preview).getByRole('checkbox', { name: 'Include session notes (private)' })); + expect(await within(preview).findByText(/Private session note for the print test\./)).toBeTruthy(); + // Details have their own tick, unticked by default. + const includeDetails = within(preview).getByRole('checkbox', { name: /^Include details/ }); + expect(includeDetails.checked).toBe(false); + expect(preview.textContent).not.toContain('Private backstory for the print test.'); + await user.click(includeDetails); + expect(await within(preview).findByText(/Private backstory for the print test\./)).toBeTruthy(); + + await user.click(within(preview).getByRole('button', { name: 'Print…' })); + expect(print).toHaveBeenCalledTimes(1); + await user.click(within(preview).getByRole('button', { name: 'Close print preview' })); + expect(within(sheet).queryByRole('region', { name: 'Print preview' })).toBeNull(); + await waitFor(() => expect(document.activeElement).toBe(within(sheet).getByRole('button', { name: 'More' }))); + print.mockRestore(); +}); diff --git a/src/Ui/e2e/sources-import.e2e.tsx b/src/Ui/e2e/sources-import.e2e.tsx new file mode 100644 index 00000000..abe8cab0 --- /dev/null +++ b/src/Ui/e2e/sources-import.e2e.tsx @@ -0,0 +1,487 @@ +// End-to-end UI flow against the real DevHost (same CommandDispatcher as the shell). Only the transport differs from the desktop +// app: HTTP to loopback instead of the WebView2 bridge, so export takes the download fallback instead of the native Save dialog. +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, expect, it, vi } from 'vitest'; +import { App } from '../src/App'; +import { client } from '../src/api/client'; +import { appStatus, createCharacter, expectStatus, goHome, openTab } from './helpers'; + +vi.mock('../src/api/client', async (importOriginal) => { + const { inject } = await import('vitest'); + const { createHttpTransport } = await import('../src/api/transport'); + const original = await importOriginal(); + const { endpoint, token } = inject('devHost'); + return { ...original, client: original.createClient(createHttpTransport(endpoint, { 'X-TomeStack-Token': token })) }; +}); + +vi.mock('../src/files', async (importOriginal) => ({ + ...(await importOriginal()), + downloadBase64: vi.fn(), +})); + +afterEach(() => { + cleanup(); + // One jsdom window serves the whole file: a preference or `html` attribute left by one test would leak into the next. + // The per-character tab memory stays (ids are unique per test and the deep-link test relies on it). + for (const key of Object.keys(localStorage)) if (key.startsWith('tomestack.') && !key.startsWith('tomestack.sheetTab.')) localStorage.removeItem(key); + for (const key of Object.keys(document.documentElement.dataset)) delete document.documentElement.dataset[key]; +}); + +/** + * A row of the review panel's Entries found list. After a filter or kind change the panel says "No entries match." until the + * new `import.candidates` reply arrives, so the list itself may not exist yet: the whole lookup is retried, never read once. + */ +const candidateButton = (panel: () => HTMLElement, name: string) => + waitFor(() => within(within(panel()).getByRole('list', { name: 'Entries found' })).getByRole('button', { name }), { timeout: 10000 }); + +it('attaches a PDF to a source, offers the cited page on a feature, and removes it after a warning', async () => { + const user = userEvent.setup(); + // Setup through the client: a homebrew source, a published feat citing page 7, and a character using it. + const source = await client.createHomebrewSource('E2E Book', ['srd-5.1']); + const draft = await client.saveDraft({ + contentId: crypto.randomUUID(), + revisionId: '00000000-0000-0000-0000-000000000000', + kind: 'feat', + name: 'E2E Cited Feat', + rulesFamilies: ['srd-5.1'], + provenance: { sourceId: source.id, page: { start: 7 } }, + status: 'draft', + summary: 'A feat that cites page 7.', + effects: [], + }); + const feat = (await client.publish(draft)).published; + await client.createCharacter({ name: 'E2E Reader', rulesFamily: 'srd-5.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [feat] }); + + render(); + await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); + const book = await screen.findByRole('listitem', { name: 'E2E Book' }); + expect(within(book).getByText('No PDF attached.')).toBeTruthy(); + + // DevHost has no native Open dialog, so the browser file picker sends the bytes (a managed copy). + await user.click(within(book).getByRole('button', { name: 'Attach PDF…' })); + const pdf = new File([new TextEncoder().encode('%PDF-1.4\n% e2e\n%%EOF\n')], 'e2e-book.pdf', { type: 'application/pdf' }); + await user.upload(screen.getByLabelText('PDF file'), pdf); + // The upload hashes and copies the file, then reloads every source (e2e/timeouts.setup.ts allows for that). + await waitFor(() => expect(within(screen.getByRole('listitem', { name: 'E2E Book' })).getByText(/PDF: e2e-book\.pdf .*copy in TomeStack.*available/)).toBeTruthy()); + + // SPEC I-03: pages 3-4 become a draft reference entry (nothing is extracted; it stays inactive until published). + const pages = within(screen.getByRole('listitem', { name: 'E2E Book' })).getByRole('group', { name: 'Import pages of E2E Book as reference' }); + await user.type(within(pages).getByRole('spinbutton', { name: 'First page' }), '3'); + await user.type(within(pages).getByRole('spinbutton', { name: 'Last page (optional)' }), '4'); + await user.type(within(pages).getByRole('textbox', { name: 'Title (optional)' }), 'E2E Chapter'); + await user.click(within(pages).getByRole('button', { name: 'Import pages' })); + await expectStatus(/Draft reference entry "E2E Chapter" created/); + const drafts = await client.contentBySource(source.id); + expect(drafts.find((e) => e.name === 'E2E Chapter')?.revisions[0]).toMatchObject({ status: 'draft', provenance: { page: { start: 3, end: 4 } } }); + + // The feature offers its cited page; opening needs the desktop app's viewer, which DevHost does not have. + await user.click(screen.getByRole('button', { name: /^E2E Reader/ })); + // The button appears once the sheet has fetched the source's attachment (e2e/timeouts.setup.ts allows for that). + await openTab(user, await screen.findByRole('article', { name: 'E2E Reader' }), 'Features'); + const open = await screen.findByRole('button', { name: 'Open E2E Cited Feat, p. 7' }); + await user.click(open); + expect((await screen.findByRole('alert')).textContent).toMatch(/needs the TomeStack desktop app/); + + // Removing says what breaks, and keeps the content. + await user.click(screen.getByRole('button', { name: 'Books and PDFs' })); + await user.click(within(await screen.findByRole('listitem', { name: 'E2E Book' })).getByRole('button', { name: 'Remove PDF…' })); + const confirm = await screen.findByRole('alertdialog', { name: 'Remove e2e-book.pdf?' }); + // The draft reference entry cites pages in it too. + expect(confirm.textContent).toMatch(/2 entries cite pages in it \(E2E Chapter, E2E Cited Feat\)/); + await user.click(within(confirm).getByRole('button', { name: 'Remove PDF' })); + await waitFor(() => expect(within(screen.getByRole('listitem', { name: 'E2E Book' })).getByText('No PDF attached.')).toBeTruthy()); + await user.click(screen.getByRole('button', { name: /^E2E Reader/ })); + await screen.findByRole('article', { name: 'E2E Reader' }); + await openTab(user, screen.getByRole('article', { name: 'E2E Reader' }), 'Features'); + expect(screen.queryByRole('button', { name: 'Open E2E Cited Feat, p. 7' })).toBeNull(); + expect(within(screen.getByRole('region', { name: 'Features' })).getByText('E2E Cited Feat')).toBeTruthy(); +}); + +// The gate runs in srd-5.1. It publishes the placeholder class's features ("Fixture Beacon" and the like), and an installed feature of +// a class-table name in the same rules family is linked instead of becoming a stub candidate. The PDF tests import fixture-import.pdf +// into srd-5.2.1 sources and expect 19 candidates, so keeping this test's content in the other family leaves them untouched wherever +// this test sits in the file. + +it('D60 gate: a Markdown class is reviewed, accepted with its confirm tick and published, then its coverage and 20-level grid open in the studio', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Gate Book', ['srd-5.1']); + const markdown = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/lab/placeholder-class.md')); + await client.startMarkdownImportData(source.id, 'placeholder-class.md', markdown.toString('base64')); + + render(); + await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); + const reader = () => within(screen.getByRole('listitem', { name: 'E2E Gate Book' })).getByRole('region', { name: 'Read the text of E2E Gate Book' }); + await screen.findByRole('listitem', { name: 'E2E Gate Book' }); + await user.click(await within(reader()).findByRole('button', { name: /^Review \d+ entr(y|ies) found$/ }, { timeout: 30000 })); + const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Gate Book' }); + await within(reader()).findByRole('region', { name: 'Entries found in E2E Gate Book' }); + await user.selectOptions(within(panel()).getByRole('combobox', { name: 'Kind' }), 'class'); + await user.click(await candidateButton(panel, 'Placeholder')); + const details = () => within(panel()).getByRole('region', { name: 'Entry: Placeholder' }); + await waitFor(() => expect(within(details()).getByRole('region', { name: 'Check before keeping' })).toBeTruthy()); + + // Keep stays held until the hit die is confirmed against the page; the proficiencies are left as reference. + await waitFor(() => expect(within(details()).getByRole('button', { name: 'Keep, with its rules' }).getAttribute('aria-disabled')).toBe('true')); + await user.click(await waitFor(() => within(details()).getByRole('checkbox', { name: /^Confirm the hit die/ }))); + await waitFor(() => expect(within(details()).getByRole('button', { name: 'Keep, with its rules' }).getAttribute('aria-disabled')).toBeNull()); + await user.click(within(details()).getByRole('button', { name: 'Keep, with its rules' })); + await waitFor(() => expect(appStatus().textContent).toMatch(/Placeholder is now a draft granting 10 features in Homebrew/)); + const drafts = await client.contentBySource(source.id); + expect(drafts).toHaveLength(11); + expect(drafts.every((e) => e.latest.status === 'draft')).toBe(true); + expect(drafts.find((e) => e.name === 'Placeholder')!.latest.effects.find((e) => e.type === 'hitDie')!.automation).toBe('automatic'); + + // Publish all drafts of the source through the studio panel. + await user.click(screen.getByRole('button', { name: 'Homebrew' })); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Gate Book/ })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Gate Book/ })); + await user.click(await screen.findByRole('button', { name: 'Make all drafts in this source available to characters…' })); + const region = screen.getByRole('region', { name: 'Make drafts of E2E Gate Book available to characters' }); + const publish = await within(region).findByRole('button', { name: 'Make 11 drafts available to characters' }); + await waitFor(() => expect(publish.getAttribute('aria-disabled')).toBeNull()); + await user.click(publish); + await within(region).findByText('Made 11 drafts available to characters.'); + expect((await client.contentBySource(source.id)).every((e) => e.latest.status === 'published')).toBe(true); + + // Coverage: the totals the fixture plants, and the features whose text sounds like a mechanic are flagged for hand play. + const coverage = await screen.findByRole('region', { name: 'Coverage' }); + const totals = '1 automatic · 0 by hand (assisted) · 14 reference · 0 not understood'; + await waitFor(() => expect(within(coverage).getAllByText(totals)).toHaveLength(2)); // the source line and the class line + const flagged = (name: string) => within(coverage).getByText(new RegExp(`^${name}:`)).closest('li')!.textContent!; + for (const name of ['Fixture Pool', 'Fixture Lull', 'Fixture Finale']) expect(flagged(name)).toContain('May need a mechanic'); + expect(flagged('Fixture Edge')).not.toContain('May need a mechanic'); + expect(coverage.textContent).not.toContain("can't calculate this"); + + // The class opens with its 20-row grid; level 20 grants the finale, and a level with no feature shows a dash. + await user.click(await screen.findByRole('button', { name: 'Edit Placeholder' })); + const progression = await screen.findByRole('region', { name: 'Class progression, scrollable' }); + const grid = within(progression).getByRole('table', { name: 'Class progression' }); + await waitFor(() => expect(within(grid).getAllByRole('row')).toHaveLength(21)); // header + 20 levels + const row = (level: number) => within(grid).getByRole('rowheader', { name: String(level) }).closest('tr')!; + expect(within(row(20)).getByRole('button', { name: 'Edit Fixture Finale' })).toBeTruthy(); + expect(within(row(1)).getByRole('button', { name: 'Edit Fixture Pool' })).toBeTruthy(); + expect(row(4).textContent).toContain('—'); +}); + +it('reads the fixture PDF, reviews its candidates, and publishes an accepted one through the studio', async () => { + // M4 D5 (SPEC I-02): the original fixture book, read by the real worker next to the DevHost. + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Grimoire', ['srd-5.2.1']); + // jsdom gives import.meta.url no file scheme; the e2e run starts in src/Ui (npm --prefix). + const book = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-import.pdf')); + await client.attachPdfData(source.id, 'fixture-import.pdf', book.toString('base64')); + + render(); + await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); + const reader = () => within(screen.getByRole('listitem', { name: 'E2E Grimoire' })).getByRole('region', { name: 'Read the text of E2E Grimoire' }); + await user.click(within(await screen.findByRole('listitem', { name: 'E2E Grimoire' })).getByRole('button', { name: 'Read the whole document' })); + // M4 stays experimental until a real third-party PDF and the SRD measurements pass (ROADMAP M4). + expect(within(reader()).getByRole('heading', { name: /Find entries in this PDF Experimental/ })).toBeTruthy(); + const reviewButton = await within(reader()).findByRole('button', { name: 'Review 19 entries found' }, { timeout: 30000 }); + // Page 6 (of 7) has no text layer: the worker tries Windows OCR where a language is installed, and finds nothing either way. + expect(within(reader()).getByText(/whole document: completed, 7 pages read, (1 by OCR, )?1 without text, 19 entries found\./)).toBeTruthy(); + + // SPEC I-03: the read text is searchable within this source. + await user.type(within(reader()).getByRole('textbox', { name: 'Search the text of E2E Grimoire' }), 'hookblade'); + await user.click(within(reader()).getByRole('button', { name: 'Search' })); + expect((await within(reader()).findByRole('list', { name: 'Search results' })).textContent).toMatch(/p\. 4.*Fixture Hookblade/); + + await user.click(reviewButton); + const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Grimoire' }); + const list = () => within(panel()).getByRole('list', { name: 'Entries found' }); + await within(reader()).findByRole('region', { name: 'Entries found in E2E Grimoire' }); + await waitFor(() => expect(within(list()).getAllByRole('listitem')).toHaveLength(19)); + const kind = within(panel()).getByRole('combobox', { name: 'Kind' }); + const detail = (name: string) => within(panel()).findByRole('region', { name: `Entry: ${name}` }); + + // A clean spell: excerpt, page, what was read; the check passes; keeping makes a draft. + await user.selectOptions(kind, 'spell'); + await waitFor(() => expect(within(list()).getAllByRole('listitem')).toHaveLength(2)); + await user.click(await candidateButton(panel, 'Fixture Ember Lance')); // a slow PDF worker may still be filling the list + const ember = await detail('Fixture Ember Lance'); + await waitFor(() => expect(document.activeElement).toBe(within(ember).getByRole('heading', { name: 'Entry: Fixture Ember Lance' }))); + expect(within(ember).getByRole('figure').textContent).toMatch(/Excerpt from p\. 2.*Fixture Ember Lance.*3d6 Fire/s); + expect(ember.querySelector('dl[aria-label="What was read"]')!.textContent).toMatch(/level2schoolevocationcastingtimeAction/); + await user.click(within(ember).getByRole('button', { name: 'Open page 2' })); + expect((await screen.findByRole('alert')).textContent).toMatch(/needs the TomeStack desktop app/); + const acceptEmber = within(ember).getByRole('button', { name: 'Keep, with its rules' }); + await waitFor(() => expect(acceptEmber.getAttribute('aria-disabled')).toBeNull()); + await user.click(acceptEmber); + await waitFor(() => expect(appStatus().textContent).toMatch(/Fixture Ember Lance is now a draft in Homebrew/)); + // It left the "to review" list with its details, so focus goes back to the list (WCAG 2.4.3). + await waitFor(() => expect(document.activeElement).toBe(within(panel()).getByRole('heading', { name: 'Entries found in E2E Grimoire' }))); + // The review says what happens next and offers the studio (item 2); the flow below still goes by the sidebar. + expect(within(panel()).getByRole('button', { name: 'Open E2E Grimoire in Homebrew' })).toBeTruthy(); + + // Ignore the other spell. + await user.click(await candidateButton(panel, 'Fixture Frost Veil')); + await user.click(within(await detail('Fixture Frost Veil')).getByRole('button', { name: 'Ignore' })); + await waitFor(() => expect(appStatus().textContent).toMatch(/Ignored Fixture Frost Veil/)); + + // An unresolved reference blocks "Keep, with its rules"; "Keep as text only" keeps the text and page only. + await user.selectOptions(kind, 'feature'); + await user.click(await candidateButton(panel, 'Fixture Stormcall')); + const stormcall = await detail('Fixture Stormcall'); + expect(within(within(stormcall).getByRole('group', { name: 'Unresolved references' })).getByRole('checkbox', { name: 'Dismiss Fixture Thunder Word' })).toBeTruthy(); + await within(stormcall).findByRole('list', { name: 'Blocks keeping' }); + expect(within(stormcall).getByRole('button', { name: 'Keep, with its rules' }).getAttribute('aria-disabled')).toBe('true'); + await user.click(within(stormcall).getByRole('button', { name: 'Keep as text only' })); + await waitFor(() => expect(appStatus().textContent).toMatch(/Fixture Stormcall is now a draft reference entry/)); + + // The feat: kept as a draft, then published in the studio, which validates it again. + await user.selectOptions(kind, 'feat'); + await user.click(await candidateButton(panel, 'Fixture Keen Watcher')); + const feat = await detail('Fixture Keen Watcher'); + const acceptFeat = within(feat).getByRole('button', { name: 'Keep, with its rules' }); + await waitFor(() => expect(acceptFeat.getAttribute('aria-disabled')).toBeNull()); + await user.click(acceptFeat); + await waitFor(() => expect(appStatus().textContent).toMatch(/Fixture Keen Watcher is now a draft/)); + + // Only drafts exist: nothing is active until it is published. + const entries = await client.contentBySource(source.id); + expect(entries.map((e) => [e.name, e.latest.status]).sort()).toEqual([ + ['Fixture Ember Lance', 'draft'], + ['Fixture Keen Watcher', 'draft'], + ['Fixture Stormcall', 'draft'], + ]); + expect(entries.find((e) => e.name === 'Fixture Keen Watcher')!.latest.effects.every((e) => e.automation === 'reference')).toBe(true); + + const studio = screen.getByRole('button', { name: 'Homebrew' }); + await user.click(studio); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Grimoire/ })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Grimoire/ })); + await user.click(await screen.findByRole('button', { name: 'Edit Fixture Keen Watcher' })); + const editor = screen.getByRole('region', { name: /^Edit Fixture Keen Watcher/ }); + await user.click(within(editor).getByRole('button', { name: 'Make available to characters' })); + await waitFor(() => expect(appStatus().textContent).toBe('Made Fixture Keen Watcher available to characters.')); + expect((await client.contentBySource(source.id)).find((e) => e.name === 'Fixture Keen Watcher')!.latest.status).toBe('published'); +}); + +it('imports a fixture class: the table is checked, the hit die and slots are confirmed, and the class is saved with its linked features (item 11, D34)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Class Book', ['srd-5.2.1']); + const book = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-import.pdf')); + await client.attachPdfData(source.id, 'fixture-import.pdf', book.toString('base64')); + + render(); + await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); + const reader = () => within(screen.getByRole('listitem', { name: 'E2E Class Book' })).getByRole('region', { name: 'Read the text of E2E Class Book' }); + await user.click(within(await screen.findByRole('listitem', { name: 'E2E Class Book' })).getByRole('button', { name: 'Read the whole document' })); + await user.click(await within(reader()).findByRole('button', { name: 'Review 19 entries found' }, { timeout: 30000 })); + const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Class Book' }); + await within(reader()).findByRole('region', { name: 'Entries found in E2E Class Book' }); + await user.selectOptions(within(panel()).getByRole('combobox', { name: 'Kind' }), 'class'); + await user.click(await candidateButton(panel, 'Fixture Lamplighter')); + const lamplighter = await within(panel()).findByRole('region', { name: 'Entry: Fixture Lamplighter' }); + + // The slot table and the linked features are on screen to check against the page. + const table = await within(lamplighter).findByRole('table', { name: 'Spell slots by class level, as read from the page' }); + expect(within(table).getAllByRole('rowheader')).toHaveLength(20); + expect(within(lamplighter).getByRole('button', { name: 'Open page 7' })).toBeTruthy(); + const linked = await within(lamplighter).findByRole('list', { name: 'Linked features' }); + await waitFor(() => expect(within(linked).getAllByRole('listitem').length).toBeGreaterThan(3)); + + // The spell list name is the detector's guess: saving the edit settles it. Keep stays held until the confirmations are ticked. + await user.click(within(lamplighter).getByRole('button', { name: 'Save edit' })); + await waitFor(() => expect(appStatus().textContent).toMatch(/Saved your edit of Fixture Lamplighter/)); + // The details are rebuilt from the saved edit, and checked again. + await waitFor(() => expect(within(panel()).getByRole('region', { name: 'Entry: Fixture Lamplighter' })).not.toBe(lamplighter)); + const again = within(panel()).getByRole('region', { name: 'Entry: Fixture Lamplighter' }); + await waitFor(() => expect(within(again).getByRole('region', { name: 'Check before keeping' }).textContent).not.toMatch(/unsure/)); + const accept = within(again).getByRole('button', { name: 'Keep, with its rules' }); + expect(accept.getAttribute('aria-disabled')).toBe('true'); + await user.click(within(again).getByRole('checkbox', { name: /^Confirm the hit die/ })); + await user.click(within(again).getByRole('checkbox', { name: 'Confirm the spell slot table' })); + await waitFor(() => expect(accept.getAttribute('aria-disabled')).toBeNull()); + await user.click(accept); + await waitFor(() => expect(appStatus().textContent).toMatch(/Fixture Lamplighter is now a draft granting \d+ features in Homebrew/)); + const granting = Number(/granting (\d+) features/.exec(appStatus().textContent ?? '')![1]); + + const entries = await client.contentBySource(source.id); + const cls = entries.find((e) => e.name === 'Fixture Lamplighter')!; + expect(entries.length).toBeGreaterThan(3); + expect(entries.every((e) => e.latest.status === 'draft')).toBe(true); + expect(cls.latest.effects.find((e) => e.type === 'hitDie')!.automation).toBe('automatic'); + // The status counts exactly the features the class draft grants. + const grants = cls.latest.effects.filter((e) => e.type === 'grant' && e.grant === 'content').length; + expect(grants).toBeGreaterThan(3); + expect(granting).toBe(grants); +}); + +it('selects a proposed effect of a fixture class and sees its lines highlighted on the stored page text (D64)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Span Book', ['srd-5.2.1']); + const book = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-import.pdf')); + await client.attachPdfData(source.id, 'fixture-import.pdf', book.toString('base64')); + + render(); + await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); + const reader = () => within(screen.getByRole('listitem', { name: 'E2E Span Book' })).getByRole('region', { name: 'Read the text of E2E Span Book' }); + await user.click(within(await screen.findByRole('listitem', { name: 'E2E Span Book' })).getByRole('button', { name: 'Read the whole document' })); + await user.click(await within(reader()).findByRole('button', { name: 'Review 19 entries found' }, { timeout: 30000 })); + const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Span Book' }); + await within(reader()).findByRole('region', { name: 'Entries found in E2E Span Book' }); + await user.selectOptions(within(panel()).getByRole('combobox', { name: 'Kind' }), 'class'); + await user.click(await candidateButton(panel, 'Fixture Lamplighter')); + const lamplighter = await within(panel()).findByRole('region', { name: 'Entry: Fixture Lamplighter' }); + + // Before a choice the whole excerpt shows, as always. + expect(lamplighter.querySelector('pre.excerpt')).not.toBeNull(); + const effects = within(lamplighter).getByRole('list', { name: /^Proposed effects/ }); + await user.click(within(effects).getByRole('button', { name: /^The hit die/ })); + const region = await within(lamplighter).findByRole('region', { name: /^The hit die/ }); + expect(within(region).getByText(/^Lines \d+–\d+$/)).toBeTruthy(); + expect(region.querySelector('mark')!.textContent!.length).toBeGreaterThan(0); + expect(lamplighter.querySelector('pre.excerpt')).toBeNull(); +}); + +it('imports a fixture Markdown class into a source with no PDF: pages only, candidates to review, and the stored page text opens in the app (D67)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Markdown Book', ['srd-5.2.1']); + const markdown = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/lab/placeholder-class.md')); + const job = await client.startMarkdownImportData(source.id, 'placeholder-class.md', markdown.toString('base64')); + expect(job.format).toBe('markdown'); + + render(); + await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); + const reader = () => within(screen.getByRole('listitem', { name: 'E2E Markdown Book' })).getByRole('region', { name: 'Read the text of E2E Markdown Book' }); + // No PDF: the Markdown import is offered, the PDF reads are not. + expect(within(await screen.findByRole('listitem', { name: 'E2E Markdown Book' })).getByRole('button', { name: 'Import a Markdown file…' })).toBeTruthy(); + expect(within(reader()).queryByRole('button', { name: 'Read the whole document' })).toBeNull(); + + const review = await within(reader()).findByRole('button', { name: /^Review \d+ entr(y|ies) found$/ }, { timeout: 30000 }); + expect(Number(/\d+/.exec(review.textContent ?? '')?.[0])).toBeGreaterThan(0); + expect(within(reader()).getByText(/^Markdown file: completed, \d+ pages? read/)).toBeTruthy(); + expect(within(reader()).queryByRole('button', { name: 'Resume' })).toBeNull(); + + // The candidates list opens and holds a row for each candidate found (awaited: the list appears with the first reply). + await user.click(review); + const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Markdown Book' }); + await within(reader()).findByRole('region', { name: 'Entries found in E2E Markdown Book' }); + const rows = await waitFor(() => within(within(panel()).getByRole('list', { name: 'Entries found' })).getAllByRole('listitem')); + expect(rows.length).toBeGreaterThan(0); + expect(within(rows[0]!).getByRole('button')).toBeTruthy(); + + // The read text is searchable, and "Open page" shows what was stored, since there is no PDF to open. + await user.type(within(reader()).getByRole('textbox', { name: 'Search the text of E2E Markdown Book' }), 'Placeholder Class'); + await user.click(within(reader()).getByRole('button', { name: 'Search' })); + const results = await within(reader()).findByRole('list', { name: 'Search results' }); + await user.click(within(results).getAllByRole('button', { name: /^Open page \d+$/ })[0]!); + const stored = await within(reader()).findByRole('region', { name: /^Stored text of page \d+ of E2E Markdown Book$/ }); + expect(stored.textContent).toContain('Placeholder Class'); + expect(await client.attachment(source.id)).toBeUndefined(); // import pages only: nothing was attached +}); + +it('accepts two fixture candidates in bulk, publishes both through the studio panel, and the builder offers them (item 9, D33)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Bulk Book', ['srd-5.2.1']); + const book = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-import.pdf')); + await client.attachPdfData(source.id, 'fixture-import.pdf', book.toString('base64')); + + render(); + await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); + const reader = () => within(screen.getByRole('listitem', { name: 'E2E Bulk Book' })).getByRole('region', { name: 'Read the text of E2E Bulk Book' }); + await user.click(within(await screen.findByRole('listitem', { name: 'E2E Bulk Book' })).getByRole('button', { name: 'Read the whole document' })); + await user.click(await within(reader()).findByRole('button', { name: 'Review 19 entries found' }, { timeout: 30000 })); + const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Bulk Book' }); + await within(reader()).findByRole('region', { name: 'Entries found in E2E Bulk Book' }); + await waitFor(() => expect(within(within(panel()).getByRole('list', { name: 'Entries found' })).getAllByRole('listitem')).toHaveLength(19)); + + // Nothing is selected yet: the bulk buttons are held with their reason. + const bulk = within(panel()).getByRole('button', { name: 'Keep selected, with their rules' }); + expect(bulk.getAttribute('aria-disabled')).toBe('true'); + await user.click(within(panel()).getByRole('checkbox', { name: 'Select Fixture Ember Lance' })); + await user.click(within(panel()).getByRole('checkbox', { name: 'Select Fixture Keen Watcher' })); + expect(within(panel()).getByText('2 selected', { selector: '[aria-live="polite"]' })).toBeTruthy(); + await user.click(bulk); + await waitFor(() => expect(appStatus().textContent).toMatch(/^Kept 2\./)); + const drafts = (await client.contentBySource(source.id)).filter((e) => e.latest.status === 'draft').map((e) => e.name).sort(); + expect(drafts).toEqual(['Fixture Ember Lance', 'Fixture Keen Watcher']); + + await user.click(screen.getByRole('button', { name: 'Homebrew' })); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Bulk Book/ })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Bulk Book/ })); + await user.click(await screen.findByRole('button', { name: 'Make all drafts in this source available to characters…' })); + const region = screen.getByRole('region', { name: 'Make drafts of E2E Bulk Book available to characters' }); + await waitFor(() => expect(document.activeElement).toBe(within(region).getByRole('heading', { name: 'Make drafts of E2E Bulk Book available to characters' }))); + const publish = await within(region).findByRole('button', { name: 'Make 2 drafts available to characters' }); + await waitFor(() => expect(publish.getAttribute('aria-disabled')).toBeNull()); + await user.click(publish); + + const result = await within(region).findByText('Made 2 drafts available to characters.'); + await waitFor(() => expect(document.activeElement).toBe(result)); // an effect moves focus to the result, so it can land after the text + expect((await client.contentBySource(source.id)).map((e) => e.latest.status)).toEqual(['published', 'published']); + // A second press would find nothing pending: the button is gone with the drafts. + await waitFor(() => expect(screen.queryByRole('button', { name: 'Make all drafts in this source available to characters…' })).toBeNull()); + expect((await client.listContent('srd-5.2.1')).some((o) => o.name === 'Fixture Ember Lance')).toBe(true); +}); + +it('adds the wizard list to a fixture spell candidate in bulk, accepts and publishes it, and the builder offers it to a wizard (item 10)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Lists Book', ['srd-5.2.1']); + const book = readFileSync(resolve(process.cwd(), '../../tests/RulesFixtures/pdf/fixture-import.pdf')); + await client.attachPdfData(source.id, 'fixture-import.pdf', book.toString('base64')); + + render(); + await user.click(await screen.findByRole('button', { name: 'Books and PDFs' })); + const reader = () => within(screen.getByRole('listitem', { name: 'E2E Lists Book' })).getByRole('region', { name: 'Read the text of E2E Lists Book' }); + await user.click(within(await screen.findByRole('listitem', { name: 'E2E Lists Book' })).getByRole('button', { name: 'Read the whole document' })); + await user.click(await within(reader()).findByRole('button', { name: 'Review 19 entries found' }, { timeout: 30000 })); + const panel = () => within(reader()).getByRole('region', { name: 'Entries found in E2E Lists Book' }); + await within(reader()).findByRole('region', { name: 'Entries found in E2E Lists Book' }); + await waitFor(() => expect(within(within(panel()).getByRole('list', { name: 'Entries found' })).getAllByRole('listitem')).toHaveLength(19)); + + // The fixture spell is level 2, which a level 1 wizard has no slot for; the reviewer lowers it to level 1 first (setup, through the API). + const [job] = await client.listImports(source.id); + const ember = (await client.candidates(job!.id, { kind: 'spell' })).items.find((c) => c.candidate.proposedName === 'Fixture Ember Lance')!; + const effects = ember.candidate.proposedEffects.map((e) => (e.type === 'spell' ? { ...e, level: 1 } : e)); + await client.editCandidate(ember.id, { effects, expected: ember.etag }); + + // Nothing is ticked: the list button is held with its reason. + const open = within(panel()).getByRole('button', { name: 'Add to a spell list…' }); + expect(open.getAttribute('aria-disabled')).toBe('true'); + await user.click(within(panel()).getByRole('checkbox', { name: 'Select Fixture Ember Lance' })); + await user.click(within(panel()).getByRole('button', { name: 'Add 1 spell to a spell list…' })); + const key = within(panel()).getByRole('combobox', { name: 'Spell list key' }); + await waitFor(() => expect(document.activeElement).toBe(key)); + await user.type(key, ' Wizard'); + expect(within(panel()).getByText('Saved as: wizard')).toBeTruthy(); + await user.click(within(panel()).getByRole('button', { name: 'Add 1 spell to this list' })); + await waitFor(() => expect(appStatus().textContent).toMatch(/^Added the spell list wizard to 1 spell/)); + const stored = (await client.candidates(job!.id, { kind: 'spell' })).items.find((c) => c.id === ember.id)!; + const lists = (stored.edited ?? stored.candidate).proposedEffects.flatMap((e) => (e.type === 'spell' ? (e.lists as string[]) : [])); + expect(lists).toContain('wizard'); + + // Keep it as a draft (the bulk button), then publish through the studio panel. + const row = within(panel()).getByRole('checkbox', { name: 'Select Fixture Ember Lance' }); + if (!row.checked) await user.click(row); + const accept = within(panel()).getByRole('button', { name: 'Keep selected, with their rules' }); + await waitFor(() => expect(accept.getAttribute('aria-disabled')).toBeNull()); + await user.click(accept); + await waitFor(() => expect(appStatus().textContent).toMatch(/^Kept 1\./)); + + await user.click(screen.getByRole('button', { name: 'Homebrew' })); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Lists Book/ })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Lists Book/ })); + await user.click(await screen.findByRole('button', { name: 'Make all drafts in this source available to characters…' })); + const region = screen.getByRole('region', { name: 'Make drafts of E2E Lists Book available to characters' }); + const publish = await within(region).findByRole('button', { name: 'Make 1 draft available to characters' }); + await waitFor(() => expect(publish.getAttribute('aria-disabled')).toBeNull()); + await user.click(publish); + await within(region).findByText('Made 1 draft available to characters.'); + + // The published spell is on the wizard list, so the builder offers it to a wizard. + const keys = await client.spellListKeys(); + expect(keys.find((k) => k.key === 'wizard')!.spells).toBeGreaterThan(0); + await goHome(user); + await createCharacter(user, { name: 'E2E Listed Wizard', family: 'srd-5.2.1', cls: /^Wizard/ }); + const picker = await screen.findByRole('group', { name: /^Spellcasting spells/ }); // the SRD wizard's rule is named "Spellcasting" + expect(within(picker).getByRole('checkbox', { name: /^Fixture Ember Lance/ })).toBeTruthy(); +}); diff --git a/src/Ui/e2e/studio-tools.e2e.tsx b/src/Ui/e2e/studio-tools.e2e.tsx new file mode 100644 index 00000000..2b5144f9 --- /dev/null +++ b/src/Ui/e2e/studio-tools.e2e.tsx @@ -0,0 +1,342 @@ +// End-to-end UI flow against the real DevHost (same CommandDispatcher as the shell). Only the transport differs from the desktop +// app: HTTP to loopback instead of the WebView2 bridge, so export takes the download fallback instead of the native Save dialog. +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, expect, it, vi } from 'vitest'; +import { App } from '../src/App'; +import { client } from '../src/api/client'; +import { fromTemplate, templates } from '../src/templates'; +import { expectStatus } from './helpers'; + +vi.mock('../src/api/client', async (importOriginal) => { + const { inject } = await import('vitest'); + const { createHttpTransport } = await import('../src/api/transport'); + const original = await importOriginal(); + const { endpoint, token } = inject('devHost'); + return { ...original, client: original.createClient(createHttpTransport(endpoint, { 'X-TomeStack-Token': token })) }; +}); + +vi.mock('../src/files', async (importOriginal) => ({ + ...(await importOriginal()), + downloadBase64: vi.fn(), +})); + +afterEach(() => { + cleanup(); + // One jsdom window serves the whole file: a preference or `html` attribute left by one test would leak into the next. + // The per-character tab memory stays (ids are unique per test and the deep-link test relies on it). + for (const key of Object.keys(localStorage)) if (key.startsWith('tomestack.') && !key.startsWith('tomestack.sheetTab.')) localStorage.removeItem(key); + for (const key of Object.keys(document.documentElement.dataset)) delete document.documentElement.dataset[key]; +}); + +it('finds a problem in a source with the debugger, shows its rule, and clears it in the editor (M5 slice 2)', async () => { + const user = userEvent.setup(); + await client.createHomebrewSource('E2E Debugger', ['srd-5.2.1']); + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Debugger/ })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Debugger/ })); + await screen.findByRole('heading', { name: 'Content in E2E Debugger' }); + + // A draft feature whose resource nothing spends or recovers. + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + await user.click(screen.getByRole('button', { name: 'New feature' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Dead Well'); + await user.click(within(editor()).getByRole('button', { name: 'Add resource' })); + await user.type(within(within(editor()).getByRole('group', { name: /^Rule 1: Resource/ })).getByRole('textbox', { name: 'Resource name' }), 'Echoes'); + await user.click(within(editor()).getByRole('button', { name: 'Save draft' })); + await expectStatus(/Saved a draft of E2E Dead Well/); + await user.click(within(editor()).getByRole('button', { name: 'Close editor' })); + + await user.click(await screen.findByRole('button', { name: 'Find problems in E2E Debugger' })); + const findings = await screen.findByRole('region', { name: 'Debugger findings for E2E Debugger' }); + expect(findings.textContent).toMatch(/Warning in E2E Dead Well: Resource 'resource-1' is never spent/); + + // "Show" opens the entry and moves focus to the rule the finding is about. + await user.click(within(findings).getByRole('button', { name: 'Show rule resource-1 of E2E Dead Well' })); + await screen.findByRole('heading', { name: 'Edit E2E Dead Well' }); + await waitFor(() => expect(document.activeElement).toBe(within(editor()).getByRole('group', { name: /^Rule 1: Resource/ }))); + + // With the entry already open, Show keeps its unsaved edits and moves focus again (review fix). + const description = within(editor()).getByRole('textbox', { name: /^Description/ }); + await user.type(description, 'Unsaved words'); + await user.click(within(screen.getByRole('region', { name: 'Debugger findings for E2E Debugger' })).getByRole('button', { name: 'Show rule resource-1 of E2E Dead Well' })); + await waitFor(() => expect(document.activeElement).toBe(within(editor()).getByRole('group', { name: /^Rule 1: Resource/ }))); + expect((within(editor()).getByRole('textbox', { name: /^Description/ }) as HTMLTextAreaElement).value).toBe('Unsaved words'); + + // A recovery fixes it; the editor's own debugger checks the unsaved revision. + await user.click(within(editor()).getByRole('button', { name: 'Add recovery' })); + await user.click(within(editor()).getByRole('button', { name: 'Find problems' })); + const own = await within(editor()).findByRole('region', { name: 'Debugger findings' }); + await waitFor(() => expect(own.textContent).toMatch(/The debugger found no problems/)); +}); + +it('tries a draft class at a chosen level on a blank character without saving anything (M5 slice 3)', async () => { + const user = userEvent.setup(); + await client.createHomebrewSource('E2E Sandbox', ['srd-5.2.1']); + const charactersBefore = (await client.listCharacters()).length; + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Sandbox/ })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Sandbox/ })); + await screen.findByRole('heading', { name: 'Content in E2E Sandbox' }); + + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + await user.click(screen.getByRole('button', { name: 'New class' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Trial Class'); + await user.selectOptions(within(editor()).getByRole('combobox', { name: 'Hit die' }), 'd10'); + + const sandbox = within(editor()).getByRole('region', { name: 'Try it' }); + await user.type(within(sandbox).getByRole('textbox', { name: /^Level in this class/ }), '3'); + await user.click(within(sandbox).getByRole('button', { name: 'Try it' })); + const results = await within(sandbox).findByRole('region', { name: 'Try it results' }); + expect(results.textContent).toMatch(/Unsaved blank character at total level 3/); + expect(results.textContent).toMatch(/Hit point maximum: 22/); // d10: 10, then 6 per level, Con +0 + expect(results.textContent).not.toMatch(/Spell save DC/); // not a caster + + // An edit hides the result until it is tried again, and nothing was saved. + await user.selectOptions(within(editor()).getByRole('combobox', { name: 'Hit die' }), 'd6'); + expect(within(sandbox).queryByRole('region', { name: 'Try it results' })).toBeNull(); + expect((await client.listCharacters()).length).toBe(charactersBefore); + expect(await client.contentBySource((await client.listSources()).find((s) => s.title === 'E2E Sandbox')!.id)).toEqual([]); +}); + +it('compares the published revision with the unsaved one by rules, text and on a character copy (M5 slice 4)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Diffs', ['srd-5.2.1']); + const draft = await client.saveDraft({ + contentId: crypto.randomUUID(), + revisionId: '00000000-0000-0000-0000-000000000000', + kind: 'feat', + name: 'E2E Diff Feat', + rulesFamilies: ['srd-5.2.1'], + provenance: { sourceId: source.id }, + status: 'draft', + summary: 'Old line', + effects: [{ type: 'modifier', id: 'quick', operation: 'bonus', target: 'initiative', value: '1' }], + }); + const published = (await client.publish(draft)).published; + const hero = await client.createCharacter({ name: 'E2E Diff Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 10, dex: 10, con: 10, int: 10, wis: 10, cha: 10 }, pins: [published] }); + + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Diffs/ })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Diffs/ })); + await user.click(await screen.findByRole('button', { name: 'Edit E2E Diff Feat' })); + + const editor = () => screen.getByRole('region', { name: /^Edit / }); + const description = within(editor()).getByRole('textbox', { name: /^Description/ }); + await user.clear(description); + await user.type(description, 'New line'); + const value = within(within(editor()).getByRole('group', { name: /^Rule 1: Modifier/ })).getByRole('textbox', { name: /^Value/ }); + await user.clear(value); + await user.type(value, '3'); + + const panel = within(editor()).getByRole('region', { name: 'Compare versions' }); + await user.click(await within(panel).findByRole('checkbox', { name: 'E2E Diff Hero' })); // the character list loads after the panel opens + await user.click(within(panel).getByRole('button', { name: 'Compare' })); + const results = await within(panel).findByRole('region', { name: 'Comparison results' }); + expect(within(results).getByRole('table', { name: 'Rule changes' }).textContent).toMatch(/quick.*changed/); + expect(results.textContent).toMatch(/removed: Old line/); + expect(results.textContent).toMatch(/added: New line/); + const run = within(results).getByRole('table', { name: 'Calculated values that change for E2E Diff Hero' }); + expect(run.textContent).toMatch(/Initiative\s*1\s*3/); + + // Nothing was applied: the character still uses the published revision. + expect((await client.getCharacter(hero.character.id)).sheet.fields.find((f) => f.field === 'initiative')?.value).toBe(1); + + // A new entry has nothing stored to compare with until its first save; then the saved draft is "From" (review fix). + await user.click(within(editor()).getByRole('button', { name: 'Close editor' })); + await user.click(screen.getByRole('button', { name: 'New feat' })); + const fresh = () => screen.getByRole('region', { name: /^New / }); + expect(within(fresh()).queryByRole('region', { name: 'Compare versions' })).toBeNull(); + await user.type(within(fresh()).getByRole('textbox', { name: 'Name' }), 'E2E Fresh Feat'); + await user.click(within(fresh()).getByRole('button', { name: 'Save draft' })); + await expectStatus(/Saved a draft of E2E Fresh Feat/); + const freshPanel = await within(fresh()).findByRole('region', { name: 'Compare versions' }); + await user.click(within(freshPanel).getByRole('button', { name: 'Compare' })); + expect((await within(freshPanel).findByRole('region', { name: 'Comparison results' })).textContent).toMatch(/The rules are the same/); +}); + +it('shows an entry\'s relationships as a keyboard tree and jumps from a node to its rule (M5 slice 5)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Trees', ['srd-5.2.1']); + const draft = await client.saveDraft({ + contentId: crypto.randomUUID(), + revisionId: '00000000-0000-0000-0000-000000000000', + kind: 'feature', + name: 'E2E Tree Feature', + rulesFamilies: ['srd-5.2.1'], + provenance: { sourceId: source.id }, + status: 'draft', + effects: [ + { type: 'resource', id: 'embers', resourceId: 'embers', label: 'Embers', maximum: 'PB' }, + { type: 'roll', id: 'flare', rollId: 'flare', label: 'Flare', dice: '1d6', resourceId: 'embers', timing: 'onRoll', automation: 'assisted' }, + { type: 'recovery', id: 'rekindle', resourceId: 'embers', on: 'longRest', amount: 'all', timing: 'onLongRest' }, + ], + }); + await client.publish(draft); + + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Trees/ })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Trees/ })); + await user.click(await screen.findByRole('button', { name: 'Edit E2E Tree Feature' })); + const editor = () => screen.getByRole('region', { name: /^Edit / }); + + await user.click(within(editor()).getByRole('button', { name: 'Show relationships' })); + const tree = await within(editor()).findByRole('tree', { name: 'Relationships of E2E Tree Feature' }); + const root = within(tree).getAllByRole('treeitem')[0]!; + expect(root.getAttribute('aria-level')).toBe('1'); + expect(root.getAttribute('aria-expanded')).toBe('true'); + expect(root.tabIndex).toBe(0); + + // Keyboard only, from the button: Tab enters the tree at its one tab stop (the root). + await user.tab(); + expect(document.activeElement).toBe(root); + await user.keyboard('{ArrowDown}'); + const resource = within(tree).getByRole('treeitem', { name: 'Resource: Embers (uses PB)' }); // named by its own label only + expect(document.activeElement).toBe(resource); + expect([resource.getAttribute('aria-level'), resource.getAttribute('aria-posinset'), resource.getAttribute('aria-setsize')]).toEqual(['2', '1', '1']); + expect(resource.getAttribute('aria-expanded')).toBe('false'); + // Space opens and closes; Right opens, then goes to the first child. + await user.keyboard(' '); + expect(resource.getAttribute('aria-expanded')).toBe('true'); + await user.keyboard(' '); + expect(resource.getAttribute('aria-expanded')).toBe('false'); + await user.keyboard('{ArrowRight}'); + expect(resource.getAttribute('aria-expanded')).toBe('true'); + await user.keyboard('{ArrowRight}'); + const roll = within(resource).getByRole('treeitem', { name: 'Roll: Flare (1d6), spends it' }); + expect((document.activeElement as HTMLElement).id).toBe(roll.id); + expect([roll.getAttribute('aria-level'), roll.getAttribute('aria-posinset'), roll.getAttribute('aria-setsize')]).toEqual(['3', '1', '2']); + // End goes to the last visible item (the recovery), Home to the root, Up and Down between items. + await user.keyboard('{End}'); + expect(document.activeElement).toBe(within(resource).getByRole('treeitem', { name: 'Recovery on a long rest: all' })); + await user.keyboard('{Home}'); + expect(document.activeElement).toBe(root); + await user.keyboard('{ArrowDown}{ArrowDown}'); + expect((document.activeElement as HTMLElement).id).toBe(roll.id); + await user.keyboard('{ArrowUp}'); + expect(document.activeElement).toBe(resource); + await user.keyboard('{ArrowDown}'); + // Enter shows the rule in the editor; Left from a child goes back to its parent. + await user.keyboard('{Enter}'); + await waitFor(() => expect(document.activeElement).toBe(within(editor()).getByRole('group', { name: /^Rule 2: Roll or action/ }))); + await user.click(within(tree).getByRole('treeitem', { name: 'Roll: Flare (1d6), spends it' })); + await user.keyboard('{ArrowLeft}'); + expect(document.activeElement).toBe(resource); +}); + +it('starts homebrew from a template as an unsaved draft, publishes a stance, and a skeleton waits for its slots (M5 slice 6)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Templates', ['srd-5.2.1']); + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Templates/ })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Templates/ })); + await screen.findByRole('heading', { name: 'Content in E2E Templates' }); + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + + // The stance: a toggle that spends a use, and a bonus only while it is on. Nothing is stored until it is saved. + await user.selectOptions(screen.getByRole('combobox', { name: 'Start from a template' }), 'A stance you switch on and off'); + await user.click(screen.getByRole('button', { name: 'Use template' })); + expect(await client.contentBySource(source.id)).toEqual([]); + expect(within(editor()).getByRole('group', { name: /^Rule 3: Toggle/ })).toBeTruthy(); + expect((within(within(editor()).getByRole('group', { name: /^Rule 4: Modifier/ })).getByRole('combobox', { name: 'Applies' }) as HTMLSelectElement).value).toBe('stance'); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Stance'); + await user.click(within(editor()).getByRole('button', { name: 'Check' })); + expect((await within(editor()).findByRole('region', { name: 'Check results' })).textContent).toMatch(/No problems found/); + await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); + await expectStatus(/Made E2E Stance available to characters/); + + // The class skeleton: its hit die, saves and subclass choice are set; its improvement slots block publishing until filled. + await user.selectOptions(screen.getByRole('combobox', { name: 'Start from a template' }), 'A class skeleton'); + await user.click(screen.getByRole('button', { name: 'Use template' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Skeleton Class'); + expect((within(editor()).getByRole('combobox', { name: 'Hit die' }) as HTMLSelectElement).value).toBe('8'); + await user.click(within(editor()).getByRole('button', { name: 'Check' })); + const results = await within(editor()).findByRole('region', { name: 'Check results' }); + expect(results.textContent).toMatch(/improvement-4' grants content but names none/); + await user.click(within(editor()).getByRole('button', { name: 'Save draft' })); + await expectStatus(/Saved a draft of E2E Skeleton Class/); + expect((await client.contentBySource(source.id)).find((e) => e.name === 'E2E Skeleton Class')?.latest.status).toBe('draft'); + + // Every template passes the server's checks; only the skeletons' empty slots are errors (review fix). + for (const t of templates) { + const draft = { ...fromTemplate(t.id, source.id, ['srd-5.2.1'], crypto.randomUUID()), name: `E2E ${t.label}`, revisionId: crypto.randomUUID() }; + expect(draft.summary).toBeUndefined(); // a template never writes the description shown on the sheet + const report = await client.validateRevision(draft); + expect(report.errors.filter((e) => e.code !== 'validate.grant-content-missing')).toEqual([]); + expect(report.errors.length > 0).toBe(t.id === 'subclass-skeleton' || t.id === 'class-skeleton'); + } + + // Removing the stance's toggle turns its bonus back to always on, so nothing names a missing toggle (review fix). + await user.selectOptions(screen.getByRole('combobox', { name: 'Start from a template' }), 'A stance you switch on and off'); + await user.click(screen.getByRole('button', { name: 'Use template' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Loose Stance'); + await user.click(within(within(editor()).getByRole('group', { name: /^Rule 3: Toggle/ })).getByRole('button', { name: 'Remove rule 3' })); + // D43 S4: the source's other entries (E2E Stance above) offer their toggles, so the choice stays, and it reads "Always". + expect((within(editor()).getByRole('combobox', { name: 'Applies' }) as HTMLSelectElement).value).toBe(''); + await user.click(within(editor()).getByRole('button', { name: 'Check' })); + await waitFor(() => expect(within(editor()).getByRole('region', { name: 'Check results' }).textContent).toMatch(/No problems found/)); +}); + +it('shows design feedback only once it is switched on, as hints that do not block (M5 slice 7)', async () => { + const user = userEvent.setup(); + await client.createHomebrewSource('E2E Feedback', ['srd-5.2.1']); + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Feedback/ })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Feedback/ })); + await screen.findByRole('heading', { name: 'Content in E2E Feedback' }); + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + + // Off by default: the editor has no feedback section. + const toggle = screen.getByRole('checkbox', { name: 'Show design feedback' }); + expect((toggle as HTMLInputElement).checked).toBe(false); + await user.click(screen.getByRole('button', { name: 'New class' })); + expect(within(editor()).queryByRole('region', { name: 'Design feedback' })).toBeNull(); + + try { + await user.click(toggle); + expect(localStorage.getItem('tomestack.designFeedback')).toBe('on'); + const section = within(editor()).getByRole('region', { name: 'Design feedback' }); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Hinted Class'); + await user.click(within(section).getByRole('button', { name: 'Get design hints' })); + const hints = await within(section).findByRole('region', { name: 'Design hints' }); + expect(hints.textContent).toMatch(/Class level\(s\) .* give no feature or choice, although every bundled SRD class gives one there/); + + // The choice is remembered for next time (this machine only): a fresh studio starts with it on. + cleanup(); + render(); + const again = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(again.disabled).toBe(false)); + await user.click(again); + expect((await screen.findByRole('checkbox', { name: 'Show design feedback' })).checked).toBe(true); + + // Off again: the choice is forgotten. + await user.click(screen.getByRole('checkbox', { name: 'Show design feedback' })); + expect(localStorage.getItem('tomestack.designFeedback')).toBeNull(); + } finally { + localStorage.removeItem('tomestack.designFeedback'); // later flows start from the default, off + } +}); diff --git a/src/Ui/e2e/studio.e2e.tsx b/src/Ui/e2e/studio.e2e.tsx new file mode 100644 index 00000000..35953a5f --- /dev/null +++ b/src/Ui/e2e/studio.e2e.tsx @@ -0,0 +1,733 @@ +// End-to-end UI flow against the real DevHost (same CommandDispatcher as the shell). Only the transport differs from the desktop +// app: HTTP to loopback instead of the WebView2 bridge, so export takes the download fallback instead of the native Save dialog. +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, expect, it, vi } from 'vitest'; +import { App } from '../src/App'; +import { client } from '../src/api/client'; +import { appStatus, createCharacter, expectStatus, fighter, goHome, openMore, openTab, pick, srd, summaryValue } from './helpers'; + +vi.mock('../src/api/client', async (importOriginal) => { + const { inject } = await import('vitest'); + const { createHttpTransport } = await import('../src/api/transport'); + const original = await importOriginal(); + const { endpoint, token } = inject('devHost'); + return { ...original, client: original.createClient(createHttpTransport(endpoint, { 'X-TomeStack-Token': token })) }; +}); + +vi.mock('../src/files', async (importOriginal) => ({ + ...(await importOriginal()), + downloadBase64: vi.fn(), +})); + +afterEach(() => { + cleanup(); + // One jsdom window serves the whole file: a preference or `html` attribute left by one test would leak into the next. + // The per-character tab memory stays (ids are unique per test and the deep-link test relies on it). + for (const key of Object.keys(localStorage)) if (key.startsWith('tomestack.') && !key.startsWith('tomestack.sheetTab.')) localStorage.removeItem(key); + for (const key of Object.keys(document.documentElement.dataset)) delete document.documentElement.dataset[key]; +}); + +/** Opens the studio on the named homebrew source (item 12 flows). */ +async function openStudioOn(user: ReturnType, title: string) { + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: new RegExp(`^${title}`) })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: new RegExp(`^${title}`) })); + await screen.findByRole('heading', { name: `Content in ${title}` }); +} + +const newestOf = async (sourceId: string, name: string) => (await client.contentBySource(sourceId)).find((e) => e.name === name)?.latest; + +it('authors a homebrew subclass in the studio, plays it, and reviews an update', async () => { + const user = userEvent.setup(); + // Setup through the client: an SRD 5.2.1 Barbarian 3 without a subclass (the builder test covers building one). + await client.createCharacter({ + name: 'E2E Storm', + rulesFamily: 'srd-5.2.1', + baseAbilities: { str: 15, dex: 13, con: 14, int: 8, wis: 12, cha: 10 }, + pins: [srd(1), srd(2)], + classes: [{ class: srd(11), level: 3 }], + choices: [ + { source: srd(2), choiceId: 'soldier-ability-scores', selected: [srd(4)] }, + { source: srd(11), choiceId: 'barbarian-skills', selected: [srd(21), srd(22)] }, + { source: srd(25), choiceId: 'primal-knowledge-skill', selected: [srd(17)] }, + ], + }); + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + + // A homebrew source for 2024 rules. + const newSource = await screen.findByRole('form', { name: 'New book or notebook' }); + await user.type(within(newSource).getByRole('textbox', { name: 'Title' }), 'E2E Homebrew'); + await user.click(within(newSource).getByRole('checkbox', { name: '2024 rules' })); + await user.click(within(newSource).getByRole('button', { name: 'Create' })); + await screen.findByRole('heading', { name: 'Content in E2E Homebrew' }); + + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + const rule = (name: RegExp) => within(editor()).getByRole('group', { name }); + async function publish(name: string) { + await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); + await waitFor(() => expect(appStatus().textContent).toBe(`Made ${name} available to characters.`)); + } + + // Feature 1: a class resource, its long-rest recovery, and a limited-use action that spends it. + await user.click(screen.getByRole('button', { name: 'New feature' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Storm Ward'); + await user.click(within(editor()).getByRole('button', { name: 'Add resource' })); + await user.type(within(rule(/^Rule 1: Resource/)).getByRole('textbox', { name: 'Resource name' }), 'Storm charges'); + await user.click(within(editor()).getByRole('button', { name: 'Add recovery' })); + await user.click(within(editor()).getByRole('button', { name: 'Add roll or action' })); + const action = rule(/^Rule 3: Roll or action/); + await user.type(within(action).getByRole('textbox', { name: 'Roll name' }), 'Storm bolt'); + await user.clear(within(action).getByRole('textbox', { name: /^Dice/ })); + await user.type(within(action).getByRole('textbox', { name: /^Dice/ }), '1d8 + 2'); + await user.selectOptions(within(action).getByRole('combobox', { name: /Uses a resource/ }), 'Storm charges'); + await publish('E2E Storm Ward'); + + // Feature 2: reference-only text. + await user.click(screen.getByRole('button', { name: 'New feature' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Sky Lore'); + await user.type(within(editor()).getByRole('textbox', { name: /^Description/ }), 'You can read tomorrow’s weather.'); + await publish('E2E Sky Lore'); + + // The subclass: offered in the SRD Barbarian's subclass choice, a modifier, and both features at level 3. + await user.click(screen.getByRole('button', { name: 'New subclass' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'Path of the E2E Storm'); + const offered = within(editor()).getByRole('combobox', { name: 'Subclass of' }); + await waitFor(() => expect(within(offered).getByRole('option', { name: /^Barbarian: Level 3: Barbarian Subclass/ })).toBeTruthy()); + await user.selectOptions(offered, within(offered).getByRole('option', { name: /^Barbarian: Level 3: Barbarian Subclass/ })); + await user.click(within(editor()).getByRole('button', { name: 'Add modifier' })); // default: Initiative +1 + await user.click(within(editor()).getByRole('button', { name: 'Grant a feature' })); + await user.selectOptions(within(rule(/^Rule 2: Granted feature/)).getByRole('combobox', { name: 'Feature' }), 'E2E Storm Ward (published)'); + await user.click(within(editor()).getByRole('button', { name: 'Grant a feature' })); + await user.selectOptions(within(rule(/^Rule 3: Granted feature/)).getByRole('combobox', { name: 'Feature' }), 'E2E Sky Lore (published)'); + await user.click(within(editor()).getByRole('button', { name: 'Check' })); + expect(await within(editor()).findByText('No problems found. It can be made available to characters.')).toBeTruthy(); + await publish('Path of the E2E Storm'); + + // Play it: the homebrew subclass is an option of the SRD choice. + await user.click(screen.getByRole('button', { name: /^E2E Storm/ })); + let sheet = await screen.findByRole('article', { name: 'E2E Storm' }); + await user.click(within(sheet).getByRole('button', { name: 'Choose now' })); + await pick(user, /^Barbarian: choose 1/, /^Path of the E2E Storm/); + await user.click(await screen.findByRole('button', { name: 'Save choices' })); + sheet = await screen.findByRole('article', { name: 'E2E Storm' }); + await openTab(user, sheet, 'Skills and saves'); + expect(within(sheet).getByRole('heading', { name: /^Initiative: \+2/ })).toBeTruthy(); // Dex +1, homebrew +1 + await openTab(user, sheet, 'Play'); + const resources = within(sheet).getByRole('region', { name: 'Resources' }); + expect(within(resources).getByRole('heading', { name: 'Storm charges: 2 of 2' })).toBeTruthy(); + await openTab(user, sheet, 'Features'); + expect(within(within(sheet).getByRole('region', { name: 'Features' })).getByText('E2E Sky Lore').closest('li')!.textContent).toMatch(/Text only/); + await openTab(user, sheet, 'Play'); + await user.click(within(sheet).getByRole('button', { name: 'Roll Storm bolt (1d8 + 2)' })); + await user.click(await screen.findByRole('button', { name: 'Spend 1 Storm charges (2 left)' })); + await waitFor(() => expect(within(screen.getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Storm charges: 1 of 2' })).toBeTruthy()); + + // Republish with +3 initiative: the character keeps +2 until the reviewed update is applied. + await user.click(screen.getByRole('button', { name: 'Homebrew' })); + // The studio opens on the first source, and the other e2e file creates its own source in the same DevHost: pick ours. + const ownSource = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await user.selectOptions(ownSource, within(ownSource).getByRole('option', { name: /^E2E Homebrew/ })); + await user.click(await screen.findByRole('button', { name: 'Edit Path of the E2E Storm' })); + const modifier = rule(/^Rule 1: Modifier/); + await user.clear(within(modifier).getByRole('textbox', { name: /^Value/ })); + await user.type(within(modifier).getByRole('textbox', { name: /^Value/ }), '3'); + await publish('Path of the E2E Storm'); + expect(await screen.findByRole('button', { name: 'Review update for E2E Storm' })).toBeTruthy(); + + // M3 C7: the sheet offers the new revision too, and nothing changes until the reviewed update is applied. + await user.click(screen.getByRole('button', { name: /^E2E Storm/ })); + sheet = await screen.findByRole('article', { name: 'E2E Storm' }); + await openTab(user, sheet, 'Skills and saves'); + expect(within(sheet).getByRole('heading', { name: /^Initiative: \+2/ })).toBeTruthy(); + await openMore(user, sheet, 'Updates'); + const updates = await within(sheet).findByRole('region', { name: 'Updates available' }); + // The setup pins the M1 SRD Barbarian revision, so the newer bundled revision is offered as well. + expect(within(updates).getByRole('button', { name: 'Review update: Barbarian' }).closest('li')!.textContent).toMatch(/bundled/); + expect(within(updates).getByRole('button', { name: 'Review update: Path of the E2E Storm' }).closest('li')!.textContent).toMatch(/your source/); + await user.click(within(updates).getByRole('button', { name: 'Review update: Path of the E2E Storm' })); + const review = await within(updates).findByRole('region', { name: 'Update E2E Storm: Path of the E2E Storm' }); + const values = await within(review).findByRole('table', { name: 'Calculated values that change' }); + expect(values.textContent).toMatch(/Initiative24/); + await user.click(within(review).getByRole('button', { name: 'Apply update' })); + await waitFor(() => expect(appStatus().textContent).toMatch(/Updated E2E Storm: Path of the E2E Storm/)); + await waitFor(() => expect(summaryValue(screen.getByRole('article', { name: 'E2E Storm' }), 'Initiative')).toBe('+4')); + const remaining = () => within(within(screen.getByRole('article', { name: 'E2E Storm' })).getByRole('region', { name: 'Updates available' })); + await waitFor(() => expect(remaining().queryByRole('button', { name: 'Review update: Path of the E2E Storm' })).toBeNull()); + expect(remaining().getByRole('button', { name: 'Review update: Barbarian' })).toBeTruthy(); // still only offered + + // Import Lab (D62 L1): the studio's Coverage view for this source counts what the engine does with the rules just authored. + await user.click(screen.getByRole('button', { name: 'Homebrew' })); + const coverageSource = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await user.selectOptions(coverageSource, within(coverageSource).getByRole('option', { name: /^E2E Homebrew/ })); + const coverage = await screen.findByRole('region', { name: 'Coverage' }); + const totals = await within(coverage).findByText(/^\d+ automatic · \d+ by hand \(assisted\) · \d+ reference · \d+ not understood$/); + expect(totals.textContent).toMatch(/ · 0 not understood$/); + expect(within(coverage).getByText(/E2E Sky Lore/).closest('li')!.textContent).toContain('1 reference'); + expect(within(coverage).getByText(/E2E Storm Ward/).closest('li')!.textContent).toMatch(/^E2E Storm Ward: 2 automatic · 1 by hand \(assisted\) · 0 reference/); // resource and recovery; the roll that spends it is assisted + expect(coverage.querySelector('[role="status"], [role="alert"], [aria-live], output')).toBeNull(); // no live region of its own + + // Import Lab (D62 L2): a class of this source opens with its 20-row progression grid once a draft is saved. + await user.click(screen.getByRole('button', { name: 'New class' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Warden'); + expect(within(editor()).getByText('Save a draft of this class to see its progression.')).toBeTruthy(); + await user.click(within(editor()).getByRole('button', { name: 'Save draft' })); + const progression = await within(editor()).findByRole('region', { name: 'Class progression, scrollable' }); + await waitFor(() => expect(within(within(progression).getByRole('table', { name: 'Class progression' })).getAllByRole('row')).toHaveLength(21)); // header + 20 levels + expect(within(editor()).getByText('Draft: not yet published')).toBeTruthy(); +}); + +it('authors a +1 weapon in the studio, equips it and rolls it, and "Why?" names the weapon bonus (MECH-X item 0)', async () => { + const user = userEvent.setup(); + await client.createCharacter({ name: 'E2E Plus Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 14, dex: 12, con: 12, int: 10, wis: 10, cha: 10 }, pins: [] }); + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + + const newSource = await screen.findByRole('form', { name: 'New book or notebook' }); + await user.type(within(newSource).getByRole('textbox', { name: 'Title' }), 'E2E Plus Book'); + await user.click(within(newSource).getByRole('checkbox', { name: '2024 rules' })); + await user.click(within(newSource).getByRole('button', { name: 'Create' })); + await screen.findByRole('heading', { name: 'Content in E2E Plus Book' }); + + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + await user.click(screen.getByRole('button', { name: 'New item' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Plus Blade'); + await user.click(within(editor()).getByRole('button', { name: 'Add weapon' })); + const weapon = within(within(editor()).getByRole('group', { name: /^Rule 1: Weapon/ })); + await user.type(weapon.getByRole('textbox', { name: /^Weapon key/ }), 'blade'); + await user.clear(weapon.getByRole('textbox', { name: /^Damage \(/ })); + await user.type(weapon.getByRole('textbox', { name: /^Damage \(/ }), '1d6'); + await user.clear(weapon.getByRole('textbox', { name: /^Damage type/ })); + await user.type(weapon.getByRole('textbox', { name: /^Damage type/ }), 'slashing'); + await user.type(weapon.getByRole('textbox', { name: /^Bonus/ }), '1'); + await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); + await waitFor(() => expect(appStatus().textContent).toBe('Made E2E Plus Blade available to characters.')); + + // Carry and equip it; both rolls name the weapon bonus under "Why?". + await user.click(screen.getByRole('button', { name: /^E2E Plus Hero/ })); + const hero = await screen.findByRole('article', { name: 'E2E Plus Hero' }); + await openTab(user, hero, 'Gear'); + const equipment = () => screen.getByRole('region', { name: 'Equipment' }); + await waitFor(() => expect(within(equipment()).getByRole('option', { name: /^E2E Plus Blade/ })).toBeTruthy()); + await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^E2E Plus Blade/ })); + await user.click(within(equipment()).getByRole('button', { name: 'Add' })); + await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip E2E Plus Blade' })); + + await openTab(user, hero, 'Play'); + const actions = () => screen.getByRole('region', { name: 'Attacks and actions' }); + const whyList = async () => { + const why = within(screen.getByRole('region', { name: 'Status' })).getByText('Why?').closest('details')!; + if (!why.open) await user.click(within(why).getByText('Why?')); + return within(why).getByRole('list', { name: 'Why this roll came out this way' }).textContent ?? ''; + }; + await waitFor(() => expect(within(actions()).getByRole('button', { name: 'Roll E2E Plus Blade attack' })).toBeTruthy()); + await user.click(within(actions()).getByRole('button', { name: 'Roll E2E Plus Blade attack' })); + await waitFor(() => expect(screen.getByRole('status', { name: 'Last roll' }).textContent).toMatch(/E2E Plus Blade attack: \d+ \(1d20\)/)); + expect(await whyList()).toMatch(/\+1 to hit \(weapon\)/); + await user.click(within(actions()).getByRole('button', { name: /^Roll E2E Plus Blade damage/ })); + await waitFor(() => expect(screen.getByRole('status', { name: 'Last roll' }).textContent).toMatch(/E2E Plus Blade damage \(slashing\): \d+/)); + expect(await whyList()).toMatch(/\+1 damage \(weapon\)/); +}); + +it('item mods: a published mod attached to one copy changes only that copy\'s attack (MECH-X item 3)', async () => { + const user = userEvent.setup(); + await client.createCharacter({ name: 'E2E Mod Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 14, dex: 12, con: 12, int: 10, wis: 10, cha: 10 }, pins: [] }); + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + + const newSource = await screen.findByRole('form', { name: 'New book or notebook' }); + await user.type(within(newSource).getByRole('textbox', { name: 'Title' }), 'E2E Mod Book'); + await user.click(within(newSource).getByRole('checkbox', { name: '2024 rules' })); + await user.click(within(newSource).getByRole('button', { name: 'Create' })); + await screen.findByRole('heading', { name: 'Content in E2E Mod Book' }); + + // The host: a plain blade. The mod: item content with an item mod effect (applies to a weapon, +2). + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + await user.click(screen.getByRole('button', { name: 'New item' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Mod Blade'); + await user.click(within(editor()).getByRole('button', { name: 'Add weapon' })); + const weapon = within(within(editor()).getByRole('group', { name: /^Rule 1: Weapon/ })); + await user.type(weapon.getByRole('textbox', { name: /^Weapon key/ }), 'modblade'); + await user.clear(weapon.getByRole('textbox', { name: /^Damage \(/ })); + await user.type(weapon.getByRole('textbox', { name: /^Damage \(/ }), '1d6'); + await user.clear(weapon.getByRole('textbox', { name: /^Damage type/ })); + await user.type(weapon.getByRole('textbox', { name: /^Damage type/ }), 'slashing'); + await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); + await waitFor(() => expect(appStatus().textContent).toBe('Made E2E Mod Blade available to characters.')); + + await user.click(screen.getByRole('button', { name: 'New item' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Keen Rune'); + await user.click(within(editor()).getByRole('button', { name: 'Add mod' })); + const mod = within(within(editor()).getByRole('group', { name: /^Rule 1: Item mod/ })); + expect((mod.getByRole('combobox', { name: 'Applies to' }) as HTMLSelectElement).value).toBe('weapon'); + await user.clear(mod.getByRole('textbox', { name: /^Bonus/ })); + await user.type(mod.getByRole('textbox', { name: /^Bonus/ }), '2'); + await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); + await waitFor(() => expect(appStatus().textContent).toBe('Made E2E Keen Rune available to characters.')); + + // Carry and equip the blade, then attach the mod to a new copy: one plain copy and one modded copy. + await user.click(screen.getByRole('button', { name: /^E2E Mod Hero/ })); + const hero = await screen.findByRole('article', { name: 'E2E Mod Hero' }); + await openTab(user, hero, 'Gear'); + const equipment = () => screen.getByRole('region', { name: 'Equipment' }); + await waitFor(() => expect(within(equipment()).getByRole('option', { name: /^E2E Mod Blade/ })).toBeTruthy()); + await user.selectOptions(within(equipment()).getByRole('combobox', { name: 'Add an item' }), within(equipment()).getByRole('option', { name: /^E2E Mod Blade/ })); + await user.click(within(equipment()).getByRole('button', { name: 'Add' })); + await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip E2E Mod Blade' })); + + const attach = await within(equipment()).findByRole('combobox', { name: 'Attach a mod to E2E Mod Blade' }); + await waitFor(() => expect(within(attach).getAllByRole('option').some((o) => o.textContent?.startsWith('E2E Keen Rune'))).toBe(true)); + await user.selectOptions(attach, within(attach).getAllByRole('option').find((o) => o.textContent?.startsWith('E2E Keen Rune'))!); + await user.click(within(equipment()).getByRole('button', { name: 'Attach to a new copy of E2E Mod Blade' })); + await user.click(await within(equipment()).findByRole('checkbox', { name: 'Equip E2E Mod Blade (copy 2 of 2)' })); + await within(equipment()).findByText(/^Mods on E2E Mod Blade \(copy 2 of 2\): E2E Keen Rune/); + + // Play: two attack rows; only the modded copy carries the +2, and its trace names the mod. + await openTab(user, hero, 'Play'); + const row = async (copy: number) => { + const item = await waitFor(() => { + const found = within(screen.getByRole('region', { name: 'Attacks and actions' })).getAllByRole('listitem').find((li) => li.textContent?.includes(`E2E Mod Blade (copy ${copy} of 2): `)); + expect(found).toBeTruthy(); + return found!; + }); + return item.textContent ?? ''; + }; + const toHit = (text: string) => Number(/([+-]\d+) to hit/.exec(text)![1]); + const first = await row(1); + const second = await row(2); + expect(toHit(second)).toBe(toHit(first) + 2); + expect(second).toMatch(/E2E Keen Rune: \+2 to hit \(mod\)/); + expect(first).not.toMatch(/E2E Keen Rune/); +}); + +it('content companions: a published feature\'s companion is a card with its own pool (MECH-X item 4)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Bonded Book', ['srd-5.2.1']); + await openStudioOn(user, 'E2E Bonded Book'); + + // One feature: a pool, an attack, and a companion that lists both (the checkboxes name them by label). + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + await user.click(screen.getByRole('button', { name: 'New feature' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'Fixture Warden Bond'); + await user.click(within(editor()).getByRole('button', { name: 'Add resource' })); + const pool = within(within(editor()).getByRole('group', { name: /^Rule 1: Resource/ })); + await user.type(pool.getByRole('textbox', { name: 'Resource name' }), 'Fixture Charges'); + await user.clear(pool.getByRole('textbox', { name: /^Uses/ })); + await user.type(pool.getByRole('textbox', { name: /^Uses/ }), '3'); + await user.click(within(editor()).getByRole('button', { name: 'Add attack' })); + await user.type(within(within(editor()).getByRole('group', { name: /^Rule 2: Attack/ })).getByRole('textbox', { name: 'Attack name' }), 'Fixture Bite'); + await user.click(within(editor()).getByRole('button', { name: 'Add companion' })); + const companion = within(within(editor()).getByRole('group', { name: /^Rule 3: Companion/ })); + await user.type(companion.getByRole('textbox', { name: 'Label' }), 'Fixture Warden'); + await user.clear(companion.getByRole('textbox', { name: 'Armor Class formula' })); + await user.type(companion.getByRole('textbox', { name: 'Armor Class formula' }), '15'); + await user.clear(companion.getByRole('textbox', { name: 'Hit point maximum formula' })); + await user.type(companion.getByRole('textbox', { name: 'Hit point maximum formula' }), '20'); + await user.click(companion.getByRole('checkbox', { name: 'Fixture Bite' })); + await user.click(companion.getByRole('checkbox', { name: 'Fixture Charges' })); + await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); + await waitFor(() => expect(appStatus().textContent).toBe('Made Fixture Warden Bond available to characters.')); + + // The server stored a v12 revision with the companion and both lists. + const published = (await newestOf(source.id, 'Fixture Warden Bond'))!; + expect(published.schemaVersion).toBe(12); + expect(published.effects.find((e) => e.type === 'companion')).toMatchObject({ label: 'Fixture Warden', armorClass: '15', hitPointMaximum: '20' }); + + await client.createCharacter({ name: 'E2E Bonded Hero', rulesFamily: 'srd-5.2.1', baseAbilities: { str: 14, dex: 12, con: 12, int: 10, wis: 10, cha: 10 }, pins: [published] }); + cleanup(); + render(); + await user.click(await screen.findByRole('button', { name: /^E2E Bonded Hero/ })); + const hero = await screen.findByRole('article', { name: 'E2E Bonded Hero' }); + await openTab(user, hero, 'Play'); + + // The card shows Armor Class and hit points, calculated (no Edit or Remove), with its attack and pool inside it. + const card = () => screen.getByRole('region', { name: 'Fixture Warden' }); + await waitFor(() => expect(within(card()).getByText('Armor Class 15')).toBeTruthy()); + expect(within(card()).getByText('Hit points: 20 of 20')).toBeTruthy(); + expect(within(card()).queryByRole('button', { name: /^Edit / })).toBeNull(); + expect(within(card()).queryByRole('button', { name: /^Remove / })).toBeNull(); + expect(card().textContent).toMatch(/From Fixture Warden Bond/); + expect(within(card()).getByRole('button', { name: 'Roll Fixture Bite attack' })).toBeTruthy(); + + // "Take damage" goes through the play command and lowers the hit points. + await user.type(within(card()).getByRole('spinbutton', { name: 'Amount' }), '3'); + await user.click(within(card()).getByRole('button', { name: /^Take damage/ })); + await waitFor(() => expect(within(card()).getByText('Hit points: 17 of 20')).toBeTruthy()); + + // "Spend" on its own pool lowers the pool. + expect(within(card()).getByRole('heading', { name: /^Fixture Charges: 3 of 3/ })).toBeTruthy(); + await user.click(within(card()).getByRole('button', { name: 'Spend 1 Fixture Charges' })); + await waitFor(() => expect(within(card()).getByRole('heading', { name: /^Fixture Charges: 2 of 3/ })).toBeTruthy()); + + // The attack and the pool are drawn on the card only: not in the Actions or Resources panels. + const attackRolls = screen.queryAllByRole('button', { name: /^Roll Fixture Bite attack/ }); + expect(attackRolls).toHaveLength(1); + expect(card().contains(attackRolls[0]!)).toBe(true); + const poolHeadings = screen.queryAllByRole('heading', { name: /^Fixture Charges/ }); + expect(poolHeadings).toHaveLength(1); + expect(card().contains(poolHeadings[0]!)).toBe(true); +}); + +it('authors a species with a Strength increase and a skill in the studio, publishes it, and the builder offers it (item 12)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Folk Book', ['srd-5.1']); + await openStudioOn(user, 'E2E Folk Book'); + + await user.click(screen.getByRole('button', { name: 'New species' })); + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Folk'); + await user.type(within(editor()).getByRole('textbox', { name: 'Strength' }), '2'); + await user.click(within(editor()).getByRole('checkbox', { name: 'Athletics' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Speed (feet)' }), '25'); // items 12, 24 + await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); + await waitFor(async () => expect((await newestOf(source.id, 'E2E Folk'))?.status).toBe('published')); + // The speed is a content v10 replace modifier, so publishing it writes a v10 revision. + const published = (await newestOf(source.id, 'E2E Folk'))!; + expect(published.effects.filter((e) => e.type === 'modifier' && e.target === 'speed')).toMatchObject([{ operation: 'replace', value: '25' }]); + expect(published.schemaVersion).toBe(10); + + await goHome(user); + await createCharacter(user, { name: 'E2E Folk Child', family: 'srd-5.1', species: /^E2E Folk/ }); + expect(await screen.findByRole('heading', { name: /^Choices/ })).toBeTruthy(); +}); + +it('authors a newer-rules background with three ability increases: the option features are drafts, Publish all makes them live, and the builder offers it (item 12)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Wanderer Book', ['srd-5.2.1']); + await openStudioOn(user, 'E2E Wanderer Book'); + + await user.click(screen.getByRole('button', { name: 'New background' })); + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Wanderer'); + for (const name of ['Strength', 'Dexterity', 'Constitution']) await user.click(within(editor()).getByRole('checkbox', { name })); + await user.click(within(editor()).getByRole('button', { name: 'Save draft' })); + await waitFor(async () => expect((await newestOf(source.id, 'E2E Wanderer'))?.status).toBe('draft')); + const entries = await client.contentBySource(source.id); + expect(entries.filter((e) => e.kind === 'feature' && e.name.startsWith('E2E Wanderer Ability Scores'))).toHaveLength(7); + + // R61: Publish is not held; a linked note says the entry points at drafts and that Publish all publishes them together. + const publish = await within(editor()).findByRole('button', { name: 'Make available to characters' }); + await waitFor(() => expect(publish.getAttribute('aria-disabled')).toBeNull()); + const note = document.getElementById('editor-pins'); + expect(note?.textContent).toBe('Points at 7 drafts not yet available to characters. Making all drafts available makes them available together and re-points this entry.'); + expect((publish.getAttribute('aria-describedby') ?? '').split(' ')).toContain('editor-pins'); + await user.click(await screen.findByRole('button', { name: 'Make all drafts in this source available to characters…' })); + const region = screen.getByRole('region', { name: 'Make drafts of E2E Wanderer Book available to characters' }); + const publishAll = await within(region).findByRole('button', { name: 'Make 8 drafts available to characters' }); + await waitFor(() => expect(publishAll.getAttribute('aria-disabled')).toBeNull()); + await user.click(publishAll); + await within(region).findByText('Made 8 drafts available to characters.'); + expect((await newestOf(source.id, 'E2E Wanderer'))?.status).toBe('published'); + // The open editor showed the superseded draft: it closes with a status instead of saving over the published version. + await waitFor(() => expect(screen.queryByRole('region', { name: /^New |^Edit / })).toBeNull()); + + await goHome(user); + await createCharacter(user, { name: 'E2E Wanderer Child', family: 'srd-5.2.1', background: /^E2E Wanderer/ }); + expect(await screen.findByRole('heading', { name: /^Choices/ })).toBeTruthy(); +}); + +it('authors a cantrip on a new spell list in the studio, publishes it, and the list shows in the spell list keys (item 12)', async () => { + const user = userEvent.setup(); + const source = await client.createHomebrewSource('E2E Spark Book', ['srd-5.2.1']); + await openStudioOn(user, 'E2E Spark Book'); + + await user.click(screen.getByRole('button', { name: 'New spell' })); + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Spark'); + await user.selectOptions(within(editor()).getByRole('combobox', { name: 'Level' }), '0'); + await user.type(within(editor()).getByRole('combobox', { name: 'Add a spell list' }), 'E2E Spark List'); + expect(within(editor()).getByText('Saved as: e2e-spark-list')).toBeTruthy(); + await user.click(within(editor()).getByRole('button', { name: 'Add list' })); + await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); + await waitFor(async () => expect((await newestOf(source.id, 'E2E Spark'))?.status).toBe('published')); + + const keys = await client.spellListKeys(); + expect(keys.find((k) => k.key === 'e2e-spark-list')?.spells).toBe(1); +}); + +it('keeps a resource linked to its recovery when the resource is renamed in the studio', async () => { + const user = userEvent.setup(); + await client.createHomebrewSource('E2E Renames', ['srd-5.2.1']); + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + const sourceSelect = await screen.findByRole('combobox', { name: 'Book or notebook' }); + await waitFor(() => expect(within(sourceSelect).getByRole('option', { name: /^E2E Renames/ })).toBeTruthy()); + await user.selectOptions(sourceSelect, within(sourceSelect).getByRole('option', { name: /^E2E Renames/ })); + await screen.findByRole('heading', { name: 'Content in E2E Renames' }); + + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + await user.click(screen.getByRole('button', { name: 'New feature' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Fury'); + await user.click(within(editor()).getByRole('button', { name: 'Add resource' })); + const name = within(within(editor()).getByRole('group', { name: /^Rule 1: Resource/ })).getByRole('textbox', { name: 'Resource name' }); + await user.type(name, 'Fury'); + await user.click(within(editor()).getByRole('button', { name: 'Add recovery' })); + // Renamed after the recovery points at it: the recovery must still restore this resource. + await user.type(name, ' points'); + await user.click(within(editor()).getByRole('button', { name: 'Check' })); + + const results = await within(editor()).findByRole('region', { name: 'Check results' }); + expect(results.textContent).not.toMatch(/does not define/); +}); + +it('adds a homebrew Fighter subclass through the studio and plays it: the Stardust Guardian path with original content (M2.2)', async () => { + const user = userEvent.setup(); + // An SRD 5.2.1 Fighter 3 with the Defense style and no subclass yet (the builder flows cover building one). + await client.createCharacter({ + name: 'E2E Warden', + rulesFamily: 'srd-5.2.1', + baseAbilities: { str: 16, dex: 14, con: 14, int: 10, wis: 12, cha: 8 }, + pins: [srd(1), srd(2)], + classes: [{ class: fighter(0), level: 3 }], + choices: [ + { source: srd(2), choiceId: 'soldier-ability-scores', selected: [srd(4)] }, + { source: fighter(0), choiceId: 'fighter-skills', selected: [fighter(800), fighter(802)] }, + { source: fighter(1), choiceId: 'fighting-style', selected: [fighter(601)] }, + ], + }); + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + + const newSource = await screen.findByRole('form', { name: 'New book or notebook' }); + await user.type(within(newSource).getByRole('textbox', { name: 'Title' }), 'E2E Warden Homebrew'); + await user.click(within(newSource).getByRole('checkbox', { name: '2024 rules' })); + await user.click(within(newSource).getByRole('button', { name: 'Create' })); + await screen.findByRole('heading', { name: 'Content in E2E Warden Homebrew' }); + + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + const rule = (name: RegExp) => within(editor()).getByRole('group', { name }); + async function publish(name: string) { + await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); + await waitFor(() => expect(appStatus().textContent).toBe(`Made ${name} available to characters.`)); + } + + // A limited-use feature: a resource, its recovery and a roll that spends it. + await user.click(screen.getByRole('button', { name: 'New feature' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Star Shield'); + await user.click(within(editor()).getByRole('button', { name: 'Add resource' })); + await user.type(within(rule(/^Rule 1: Resource/)).getByRole('textbox', { name: 'Resource name' }), 'Star charges'); + await user.click(within(editor()).getByRole('button', { name: 'Add recovery' })); + await user.click(within(editor()).getByRole('button', { name: 'Add roll or action' })); + const action = rule(/^Rule 3: Roll or action/); + await user.type(within(action).getByRole('textbox', { name: 'Roll name' }), 'Star burst'); + await user.clear(within(action).getByRole('textbox', { name: /^Dice/ })); + await user.type(within(action).getByRole('textbox', { name: /^Dice/ }), '2d6'); + await user.selectOptions(within(action).getByRole('combobox', { name: /Uses a resource/ }), 'Star charges'); + await publish('E2E Star Shield'); + + // The subclass joins the SRD Fighter's level-3 choice, with a modifier and the feature. + await user.click(screen.getByRole('button', { name: 'New subclass' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Starward Warden'); + const offered = within(editor()).getByRole('combobox', { name: 'Subclass of' }); + await waitFor(() => expect(within(offered).getByRole('option', { name: /^Fighter: Level 3: Fighter Subclass/ })).toBeTruthy()); + await user.selectOptions(offered, within(offered).getByRole('option', { name: /^Fighter: Level 3: Fighter Subclass/ })); + await user.click(within(editor()).getByRole('button', { name: 'Add modifier' })); // default: Initiative +1 + await user.click(within(editor()).getByRole('button', { name: 'Grant a feature' })); + await user.selectOptions(within(rule(/^Rule 2: Granted feature/)).getByRole('combobox', { name: 'Feature' }), 'E2E Star Shield (published)'); + await publish('E2E Starward Warden'); + + // Choose it on the sheet, next to the SRD Champion, then play. + await user.click(screen.getByRole('button', { name: /^E2E Warden/ })); + let sheet = await screen.findByRole('article', { name: 'E2E Warden' }); + await user.click(within(sheet).getByRole('button', { name: 'Choose now' })); + const subclass = await screen.findByRole('group', { name: /^Fighter: choose 1/ }); + expect(await within(subclass).findByRole('checkbox', { name: /^Champion/ })).toBeTruthy(); + await pick(user, /^Fighter: choose 1/, /^E2E Starward Warden/); + await user.click(await screen.findByRole('button', { name: 'Save choices' })); + + sheet = await screen.findByRole('article', { name: 'E2E Warden' }); + await openTab(user, sheet, 'Skills and saves'); + expect(within(sheet).getByRole('heading', { name: /^Initiative: \+3/ })).toBeTruthy(); // Dex +2, homebrew +1 + expect(within(sheet).getByRole('heading', { name: /^Attacks per Attack action: 1/ })).toBeTruthy(); // Extra Attack comes at 5 + await openTab(user, sheet, 'Play'); + const resources = () => within(screen.getByRole('article', { name: 'E2E Warden' })).getByRole('region', { name: 'Resources' }); + expect(within(resources()).getByRole('heading', { name: 'Star charges: 2 of 2' })).toBeTruthy(); + expect(within(resources()).getByRole('heading', { name: 'Second Wind: 2 of 2' })).toBeTruthy(); + expect(within(resources()).getByRole('heading', { name: 'Action Surge: 1 of 1' })).toBeTruthy(); + + // Second Wind rolls 1d10 plus the Fighter level; spending it is a separate, confirmed press. + await user.click(within(sheet).getByRole('button', { name: 'Roll Second Wind healing (1d10 + 3)' })); + const lastRoll = screen.getByRole('status', { name: 'Last roll' }); + await waitFor(() => expect(lastRoll.textContent).toMatch(/Second Wind healing bonus \+3/)); + expect(lastRoll.textContent).not.toMatch(/CLASS_LEVEL/); // the label names the roll, not its formula + await user.click(await screen.findByRole('button', { name: 'Spend 1 Second Wind (2 left)' })); + await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Second Wind: 1 of 2' })).toBeTruthy()); + await user.click(within(screen.getByRole('article', { name: 'E2E Warden' })).getByRole('button', { name: 'Roll Star burst (2d6)' })); + await user.click(await screen.findByRole('button', { name: 'Spend 1 Star charges (2 left)' })); + await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Star charges: 1 of 2' })).toBeTruthy()); + + // A short rest gives one Second Wind use back (2024); the homebrew charges wait for the long rest. + await user.click(screen.getByRole('button', { name: 'Short rest…' })); + const rest = await screen.findByRole('region', { name: 'Short rest' }); + expect(await within(rest).findByRole('checkbox', { name: /^Second Wind: 1 → 2/ })).toBeTruthy(); + expect(within(rest).queryByRole('checkbox', { name: /^Star charges/ })).toBeNull(); + await user.click(within(rest).getByRole('button', { name: 'Finish short rest' })); + await expectStatus(/Short rest finished/); + await waitFor(() => expect(within(resources()).getByRole('heading', { name: 'Second Wind: 2 of 2' })).toBeTruthy()); +}); + +it('authors a class in the studio and builds it at levels 1, 20 and 5/3 with an SRD class (M5 exit gate, ADR-010)', async () => { + // An original nonstandard class, built in the studio with no code edits: a d8, Int and Wis saves, a multiclass + // prerequisite, a skill choice, a column ("Ink"), a resource that reads it, and a caster whose multiclass share is its + // own table (two thirds). Tables are invented for testing. + const user = userEvent.setup(); + render(); + const studioButton = await screen.findByRole('button', { name: 'Homebrew' }); + await waitFor(() => expect(studioButton.disabled).toBe(false)); + await user.click(studioButton); + const newSource = await screen.findByRole('form', { name: 'New book or notebook' }); + await user.type(within(newSource).getByRole('textbox', { name: 'Title' }), 'E2E Chronicle Homebrew'); + await user.click(within(newSource).getByRole('checkbox', { name: '2024 rules' })); + await user.click(within(newSource).getByRole('button', { name: 'Create' })); + await screen.findByRole('heading', { name: 'Content in E2E Chronicle Homebrew' }); + + const editor = () => screen.getByRole('region', { name: /^New |^Edit / }); + const rule = (name: RegExp) => within(editor()).getByRole('group', { name }); + await user.click(screen.getByRole('button', { name: 'New class' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Chronicler'); + + const basics = within(editor()).getByRole('region', { name: 'Class basics' }); + await user.selectOptions(within(basics).getByRole('combobox', { name: 'Hit die' }), 'd8'); + const saves = within(basics).getByRole('group', { name: /^Saving throw proficiencies/ }); + await user.click(within(saves).getByRole('checkbox', { name: 'Intelligence' })); + await user.click(within(saves).getByRole('checkbox', { name: 'Wisdom' })); + const prerequisites = within(basics).getByRole('group', { name: /^Multiclass prerequisites/ }); + await user.type(within(prerequisites).getByRole('spinbutton', { name: 'Intelligence at least' }), '13'); + const skills = within(basics).getByRole('group', { name: /^Skill choice/ }); + await user.click(within(skills).getByRole('checkbox', { name: 'History' })); + await user.click(within(skills).getByRole('checkbox', { name: 'Arcana' })); + await user.click(within(skills).getByRole('checkbox', { name: 'Investigation' })); + await user.click(within(skills).getByRole('button', { name: 'Create skill choice' })); + await waitFor(() => expect(within(skills).getByText(/Choose 2 of 3 skills/)).toBeTruthy()); + expect(within(skills).getByText(/3 new option features published, 0 reused/)).toBeTruthy(); // announced, and focus stays in the group + expect(document.activeElement).toBe(within(skills).getByText('Skill choice (starting class only)')); + // Removing the choice and creating it again reuses the three published features, never publishes duplicates (review fix). + await user.click(within(skills).getByRole('button', { name: 'Remove the skill choice' })); + await waitFor(() => expect(within(skills).getByText(/Skill choice removed/)).toBeTruthy()); + await user.click(within(skills).getByRole('checkbox', { name: 'History' })); + await user.click(within(skills).getByRole('checkbox', { name: 'Arcana' })); + await user.click(within(skills).getByRole('checkbox', { name: 'Investigation' })); + await user.click(within(skills).getByRole('button', { name: 'Create skill choice' })); + await waitFor(() => expect(within(skills).getByText(/0 new option features published, 3 reused/)).toBeTruthy()); + expect(within(skills).getByText(/Choose 2 of 3 skills/)).toBeTruthy(); + await user.click(within(within(basics).getByRole('group', { name: 'Subclass' })).getByRole('checkbox', { name: /^This class has subclasses/ })); + + await user.click(within(editor()).getByRole('button', { name: 'Add class column' })); + const column = rule(/^Rule 1: Class column/); + await user.type(within(column).getByRole('textbox', { name: 'Column name' }), 'Ink'); + await user.clear(within(column).getByRole('textbox', { name: /^Key/ })); + await user.type(within(column).getByRole('textbox', { name: /^Key/ }), 'ink'); + const values = within(column).getByRole('textbox', { name: /^Values at class levels/ }); + await user.clear(values); + await user.type(values, '2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9'); + + await user.click(within(editor()).getByRole('button', { name: 'Add resource' })); + const ink = rule(/^Rule 2: Resource/); + await user.type(within(ink).getByRole('textbox', { name: 'Resource name' }), 'Ink'); + await user.clear(within(ink).getByRole('textbox', { name: /^Uses/ })); + // D61: the formula's preview, worked out by the real service against this draft (proficiency bonus 6 at level 20). + await user.type(within(ink).getByRole('textbox', { name: /^Uses/ }), 'PB'); + expect((await within(ink).findByText(/Level 20: 6/)).textContent).toMatch(/^Level 1: 2 · .* · Level 20: 6$/); + expect(within(ink).getByRole('textbox', { name: /^Uses/ }).getAttribute('aria-describedby')).toMatch(/^rule-resource-\d+-maximum-preview$/); + await user.clear(within(ink).getByRole('textbox', { name: /^Uses/ })); + await user.type(within(ink).getByRole('textbox', { name: /^Uses/ }), 'SCALE.ink'); + expect(await within(ink).findByText(/Level 1: 2 · .* · Level 20: 9$/)).toBeTruthy(); // the draft's own column + await user.click(within(editor()).getByRole('button', { name: 'Add recovery' })); // all, on a long rest + + await user.click(within(editor()).getByRole('button', { name: 'Add spellcasting' })); + const casting = rule(/^Rule 4: Spellcasting/); + await user.type(within(casting).getByRole('textbox', { name: /^Spell list key/ }), 'e2e-chronicle'); + const slots = ['1', '2', '3', '3, 1', '3, 2', '4, 2', '4, 2, 1', '4, 3, 1', '4, 3, 2', '4, 3, 2, 1', '4, 3, 3, 1', '4, 3, 3, 2', '4, 3, 3, 2, 1', '4, 3, 3, 3, 1', '4, 3, 3, 3, 2', '4, 3, 3, 3, 2, 1', '4, 3, 3, 3, 2, 1', '4, 3, 3, 3, 3, 1', '4, 3, 3, 3, 3, 2', '4, 3, 3, 3, 3, 2, 1']; + await user.type(within(casting).getByRole('textbox', { name: /^Spell slots/ }), slots.join('{Enter}')); + await user.selectOptions(within(casting).getByRole('combobox', { name: /^With other casters/ }), 'Its own table of caster levels'); + const share = within(casting).getByRole('textbox', { name: /^Caster levels it adds/ }); + await user.clear(share); + await user.type(share, '0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10, 11, 12, 12, 13'); + + await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); + await waitFor(() => expect(appStatus().textContent).toBe('Made E2E Chronicler available to characters.')); + + // A homebrew subclass joins the new class's subclass choice, which declares no options of its own. + await user.click(screen.getByRole('button', { name: 'New subclass' })); + await user.type(within(editor()).getByRole('textbox', { name: 'Name' }), 'E2E Order of Quills'); + const offered = within(editor()).getByRole('combobox', { name: 'Subclass of' }); + await waitFor(() => expect(within(offered).getByRole('option', { name: 'E2E Chronicler: Choose a subclass' })).toBeTruthy()); + await user.selectOptions(offered, 'E2E Chronicler: Choose a subclass'); + await user.click(within(editor()).getByRole('button', { name: 'Add modifier' })); // default: Initiative +1 + await user.click(within(editor()).getByRole('button', { name: 'Make available to characters' })); + await waitFor(() => expect(appStatus().textContent).toBe('Made E2E Order of Quills available to characters.')); + + // Level 1 in the builder: the class is offered like any other, with its skill choice. + await createCharacter(user, { name: 'E2E Scribe', family: 'srd-5.2.1', scores: { Intelligence: 16 }, cls: /^E2E Chronicler/ }); + await pick(user, /^Choose 2 skills/, /^E2E Chronicler: History/); + await pick(user, /^Choose 2 skills/, /^E2E Chronicler: Arcana/); + await user.click(await screen.findByRole('button', { name: 'Create and save' })); + let sheet = await screen.findByRole('article', { name: 'E2E Scribe' }); + await openTab(user, sheet, 'Skills and saves'); + expect(within(sheet).getByRole('heading', { name: /^History: \+5/ })).toBeTruthy(); // the chosen option grants it: Int +3, PB +2 + await openTab(user, sheet, 'Play'); + expect(within(within(sheet).getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Ink: 2 of 2' })).toBeTruthy(); + expect(within(within(sheet).getByRole('region', { name: 'Class columns' })).getByText('Ink: 2')).toBeTruthy(); + await openTab(user, sheet, 'Spells'); + expect(within(within(sheet).getByRole('region', { name: 'Spells and slots' })).getByRole('heading', { name: 'Level 1 slots: 1 of 1' })).toBeTruthy(); + + // Level 20, and Chronicler 5 with the SRD Wizard 3: the same published class, no code edits. + const options = await client.listContent('srd-5.2.1'); + const chronicler = options.find((o) => o.kind === 'class' && o.name === 'E2E Chronicler' && !o.superseded)!.reference; + const wizard = options.find((o) => o.kind === 'class' && o.name === 'Wizard' && o.compatible && !o.superseded)!.reference; + const order = options.find((o) => o.kind === 'subclass' && o.name === 'E2E Order of Quills' && !o.superseded)!.reference; + const scores = { str: 10, dex: 12, con: 14, int: 16, wis: 14, cha: 10 }; + await client.createCharacter({ + name: 'E2E Scribe 20', + rulesFamily: 'srd-5.2.1', + baseAbilities: scores, + pins: [], + classes: [{ class: chronicler, level: 20 }], + choices: [{ source: chronicler, choiceId: 'subclass', selected: [order] }], + }); + await client.createCharacter({ + name: 'E2E Scribe Wizard', + rulesFamily: 'srd-5.2.1', + baseAbilities: scores, + pins: [], + classes: [{ class: chronicler, level: 5 }, { class: wizard, level: 3 }], + choices: [], + }); + cleanup(); + render(); + + await user.click(await screen.findByRole('button', { name: /^E2E Scribe 20 / })); + sheet = await screen.findByRole('article', { name: 'E2E Scribe 20' }); + await openTab(user, sheet, 'Skills and saves'); + expect(within(sheet).getByRole('heading', { name: /^Hit point maximum: 143/ })).toBeTruthy(); // 8 + 19 × 5 + 20 × Con 2 + expect(within(sheet).getByRole('heading', { name: /^Initiative: \+2/ })).toBeTruthy(); // Dex +1, the homebrew subclass +1 + await openTab(user, sheet, 'Play'); + expect(within(within(sheet).getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Ink: 9 of 9' })).toBeTruthy(); + await openTab(user, sheet, 'Spells'); + expect(within(within(sheet).getByRole('region', { name: 'Spells and slots' })).getByRole('heading', { name: 'Level 7 slots: 1 of 1' })).toBeTruthy(); + + await user.click(screen.getByRole('button', { name: /^E2E Scribe Wizard/ })); + sheet = await screen.findByRole('article', { name: 'E2E Scribe Wizard' }); + await openTab(user, sheet, 'Spells'); + const spells = within(sheet).getByRole('region', { name: 'Spells and slots' }); + // Chronicler 5 counts 3 (its table) + Wizard 3: caster level 6 on the Multiclass Spellcaster table. + expect(within(spells).getByRole('heading', { name: 'Level 1 slots: 4 of 4' })).toBeTruthy(); + expect(within(spells).getByRole('heading', { name: 'Level 3 slots: 3 of 3' })).toBeTruthy(); + await openTab(user, sheet, 'Play'); + expect(within(within(sheet).getByRole('region', { name: 'Resources' })).getByRole('heading', { name: 'Ink: 4 of 4' })).toBeTruthy(); +}); diff --git a/src/Ui/src/components/ddb/DdbImportPanel.test.tsx b/src/Ui/src/components/ddb/DdbImportPanel.test.tsx index 7c41e6c9..1b1423af 100644 --- a/src/Ui/src/components/ddb/DdbImportPanel.test.tsx +++ b/src/Ui/src/components/ddb/DdbImportPanel.test.tsx @@ -1,5 +1,5 @@ // @vitest-environment jsdom -// The D&D Beyond import steps against a mocked client (the real flow runs in e2e/flow.e2e.tsx). Every value is invented. +// The D&D Beyond import steps against a mocked client (the real flow runs in e2e/character-import.e2e.tsx). Every value is invented. import { cleanup, render as renderPlain, screen, waitFor, within } from '@testing-library/react'; import type { ReactElement, ReactNode } from 'react'; import userEvent from '@testing-library/user-event'; diff --git a/src/Ui/vitest.e2e.config.ts b/src/Ui/vitest.e2e.config.ts index 0fbffe53..952fd380 100644 --- a/src/Ui/vitest.e2e.config.ts +++ b/src/Ui/vitest.e2e.config.ts @@ -9,6 +9,9 @@ export default defineConfig({ server: { fs: { allow: ['.', '../../docs/guides'] } }, test: { include: ['e2e/**/*.e2e.tsx'], + // One shared DevHost serves every file: sources sort by GUID and a test may rely on what an earlier test in its file + // created. Files run one after another, as the single flow file did, so no new cross-file load or ordering appears. + fileParallelism: false, environment: 'jsdom', globalSetup: ['e2e/devhost.setup.ts'], setupFiles: ['e2e/timeouts.setup.ts'], diff --git a/tests/AppService.Tests/SrdOrigins521Tests.cs b/tests/AppService.Tests/SrdOrigins521Tests.cs index 6d55e2ac..4fd64275 100644 --- a/tests/AppService.Tests/SrdOrigins521Tests.cs +++ b/tests/AppService.Tests/SrdOrigins521Tests.cs @@ -314,7 +314,7 @@ public void Every_new_revision_is_published_at_the_lowest_schema_version_it_need [Fact] public void New_names_are_unique_and_never_start_like_the_M1_species_or_background() { - // The e2e flow picks the Dwarf and the Soldier by a name prefix (flow.e2e.tsx), and tests look content up by name. + // The e2e flow picks the Dwarf and the Soldier by a name prefix (src/Ui/e2e/*.e2e.tsx), and tests look content up by name. // The feat "Ability Score Improvement" shares its SRD name with the class feature; imports match by kind. var names = Origins.Revisions.Concat(Feats.Revisions).Select(r => r.Name).ToList();