Compare commits
12 Commits
0.9.11
...
1de00e3d8e
| Author | SHA1 | Date | |
|---|---|---|---|
| 1de00e3d8e | |||
| f4fb69dbc7 | |||
| ef76b9c90b | |||
| 36122b500b | |||
| f4355a8675 | |||
| 209df13c32 | |||
| 4969ed069b | |||
| fba83bebd6 | |||
| f6766b729d | |||
| f10c67a5ba | |||
| 9437272fe0 | |||
| 541e04b732 |
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"threshold": 50,
|
||||
"minInstances": 3,
|
||||
"identifiers": false,
|
||||
"literals": false,
|
||||
"ignore": "dist|__tests__|node_modules",
|
||||
"reporter": "default",
|
||||
"truncate": 100
|
||||
}
|
||||
@@ -73,6 +73,7 @@ docs/agents/ RPI skill artifacts (research reports, plans)
|
||||
- **Tests** live in `packages/*/src/__tests__/*.test.ts`. Test pure functions directly; map acceptance scenarios and invariants from specs to individual `it()` blocks.
|
||||
- **Feature specs** live in `specs/NNN-feature-name/` with spec.md (and optionally plan.md, tasks.md for new work). Specs describe features, not individual changes. The project constitution is at `.specify/memory/constitution.md`.
|
||||
- **Component props** — max 8 explicitly declared props per component interface (enforced by `scripts/check-component-props.mjs`). Use React context for shared state; reserve props for per-instance config (data items, layout variants, refs).
|
||||
- **Export format compatibility** — When changing `Encounter`, `Combatant`, `PlayerCharacter`, or `UndoRedoState` types, verify that previously exported JSON files (version 1) still import correctly. If not, bump the `ExportBundle` version and add migration logic in `validateImportBundle()`.
|
||||
- **Quality gates** are enforced at pre-commit via Lefthook's `pnpm check` — the project's single earliest enforcement point. No gate may exist only as a CI step or manual process.
|
||||
|
||||
## Self-Review Checklist
|
||||
@@ -97,6 +98,8 @@ Speckit (`/speckit.*` skills) manages the spec-driven development pipeline. Spec
|
||||
- `rpi-plan` — interactive phased implementation plan in `docs/agents/plans/`
|
||||
- `rpi-implement` — execute a plan file phase by phase with automated + manual verification
|
||||
|
||||
**Research scope**: Research should include a scan for existing patterns similar to what the feature needs (e.g., shared UI primitives, duplicated validation logic, repeated state management patterns). Identify extraction and consolidation opportunities before implementation, not during.
|
||||
|
||||
### Choosing the right workflow by scope
|
||||
|
||||
| Scope | Workflow |
|
||||
@@ -114,6 +117,9 @@ Speckit manages **what** to build (specs as living documents). RPI manages **how
|
||||
- `specs/003-combatant-state/` — HP, AC, conditions, concentration, initiative
|
||||
- `specs/004-bestiary/` — search index, stat blocks, source management, panel UX
|
||||
- `specs/005-player-characters/` — persistent player character templates (CRUD), search & add to encounters, color/icon visual distinction, `PlayerCharacterStore` port
|
||||
- `specs/006-undo-redo/` — undo/redo for encounter state mutations
|
||||
- `specs/007-json-import-export/` — JSON import/export for full encounter state (encounter, undo/redo, player characters)
|
||||
- `specs/008-encounter-difficulty/` — Live encounter difficulty indicator (5.5e XP budget system), optional PC level field
|
||||
|
||||
## Constitution (key principles)
|
||||
|
||||
@@ -124,4 +130,3 @@ The constitution (`.specify/memory/constitution.md`) governs all feature work:
|
||||
3. **Clarification-First** — Ask before making non-trivial assumptions.
|
||||
4. **MVP Baseline** — Say "MVP baseline does not include X", never permanent bans.
|
||||
5. **Spec-driven features** — Features are described in living specs; evolve existing specs via `/integrate-issue`, create new ones via `/speckit.specify`. Bug fixes and tooling changes do not require specs.
|
||||
|
||||
|
||||
@@ -7,8 +7,10 @@ A local-first initiative tracker and encounter manager for tabletop RPGs (D&D 5e
|
||||
- **Initiative tracking** — add combatants (batch-add from bestiary, custom creatures with optional stats), roll initiative (manual or d20), cycle turns and rounds
|
||||
- **Encounter state** — HP, AC, conditions, concentration tracking with visual status indicators
|
||||
- **Bestiary integration** — import bestiary JSON sources, search creatures, and view full stat blocks
|
||||
- **Player characters** — create reusable player character templates with name, AC, HP, color, and icon; search and add them to encounters with pre-filled stats; manage (edit/delete) from a dedicated panel
|
||||
- **Player characters** — create reusable player character templates with name, AC, HP, level, color, and icon; search and add them to encounters with pre-filled stats; manage (edit/delete) from a dedicated panel
|
||||
- **Encounter difficulty** — live 3-bar indicator in the top bar showing encounter difficulty (Trivial/Low/Moderate/High) based on the 2024 5.5e XP budget system; automatically derived from PC levels and bestiary creature CRs
|
||||
- **Undo/redo** — reverse any encounter action with Undo/Redo buttons or keyboard shortcuts (Ctrl+Z / Ctrl+Shift+Z, Cmd on Mac); history persists across page reloads
|
||||
- **Import/export** — export the full encounter state (combatants, undo/redo history, player characters) as a JSON file or copy to clipboard; import from file upload or pasted JSON with validation and confirmation
|
||||
- **Persistent** — encounters survive page reloads via localStorage; bestiary data cached in IndexedDB; player characters stored independently
|
||||
|
||||
## Prerequisites
|
||||
|
||||
@@ -30,6 +30,13 @@ export function App() {
|
||||
const activeRowRef = useRef<HTMLDivElement>(null);
|
||||
const actionBarAnim = useActionBarAnimation(encounter.combatants.length);
|
||||
|
||||
// Close the side panel when the encounter becomes empty
|
||||
useEffect(() => {
|
||||
if (isEmpty) {
|
||||
sidePanel.dismissPanel();
|
||||
}
|
||||
}, [isEmpty, sidePanel.dismissPanel]);
|
||||
|
||||
// Auto-scroll to active combatant when turn changes
|
||||
const activeIndex = encounter.activeIndex;
|
||||
useEffect(() => {
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
import {
|
||||
combatantId,
|
||||
type Encounter,
|
||||
type ExportBundle,
|
||||
type PlayerCharacter,
|
||||
playerCharacterId,
|
||||
type UndoRedoState,
|
||||
} from "@initiative/domain";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
assembleExportBundle,
|
||||
bundleToJson,
|
||||
resolveFilename,
|
||||
validateImportBundle,
|
||||
} from "../persistence/export-import.js";
|
||||
|
||||
const ISO_TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;
|
||||
const DEFAULT_FILENAME_RE = /^initiative-export-\d{4}-\d{2}-\d{2}\.json$/;
|
||||
|
||||
const encounter: Encounter = {
|
||||
combatants: [
|
||||
{
|
||||
id: combatantId("c-1"),
|
||||
name: "Goblin",
|
||||
initiative: 15,
|
||||
maxHp: 7,
|
||||
currentHp: 7,
|
||||
ac: 15,
|
||||
},
|
||||
{
|
||||
id: combatantId("c-2"),
|
||||
name: "Aria",
|
||||
initiative: 18,
|
||||
maxHp: 45,
|
||||
currentHp: 40,
|
||||
ac: 16,
|
||||
color: "blue",
|
||||
icon: "sword",
|
||||
playerCharacterId: playerCharacterId("pc-1"),
|
||||
},
|
||||
],
|
||||
activeIndex: 0,
|
||||
roundNumber: 2,
|
||||
};
|
||||
|
||||
const undoRedoState: UndoRedoState = {
|
||||
undoStack: [
|
||||
{
|
||||
combatants: [{ id: combatantId("c-1"), name: "Goblin", initiative: 15 }],
|
||||
activeIndex: 0,
|
||||
roundNumber: 1,
|
||||
},
|
||||
],
|
||||
redoStack: [],
|
||||
};
|
||||
|
||||
const playerCharacters: PlayerCharacter[] = [
|
||||
{
|
||||
id: playerCharacterId("pc-1"),
|
||||
name: "Aria",
|
||||
ac: 16,
|
||||
maxHp: 45,
|
||||
color: "blue",
|
||||
icon: "sword",
|
||||
},
|
||||
];
|
||||
|
||||
describe("assembleExportBundle", () => {
|
||||
it("returns a bundle with version 1", () => {
|
||||
const bundle = assembleExportBundle(
|
||||
encounter,
|
||||
undoRedoState,
|
||||
playerCharacters,
|
||||
);
|
||||
expect(bundle.version).toBe(1);
|
||||
});
|
||||
|
||||
it("includes an ISO timestamp", () => {
|
||||
const bundle = assembleExportBundle(
|
||||
encounter,
|
||||
undoRedoState,
|
||||
playerCharacters,
|
||||
);
|
||||
expect(bundle.exportedAt).toMatch(ISO_TIMESTAMP_RE);
|
||||
});
|
||||
|
||||
it("includes the encounter", () => {
|
||||
const bundle = assembleExportBundle(
|
||||
encounter,
|
||||
undoRedoState,
|
||||
playerCharacters,
|
||||
);
|
||||
expect(bundle.encounter).toEqual(encounter);
|
||||
});
|
||||
|
||||
it("includes undo and redo stacks", () => {
|
||||
const bundle = assembleExportBundle(
|
||||
encounter,
|
||||
undoRedoState,
|
||||
playerCharacters,
|
||||
);
|
||||
expect(bundle.undoStack).toEqual(undoRedoState.undoStack);
|
||||
expect(bundle.redoStack).toEqual(undoRedoState.redoStack);
|
||||
});
|
||||
|
||||
it("includes player characters", () => {
|
||||
const bundle = assembleExportBundle(
|
||||
encounter,
|
||||
undoRedoState,
|
||||
playerCharacters,
|
||||
);
|
||||
expect(bundle.playerCharacters).toEqual(playerCharacters);
|
||||
});
|
||||
});
|
||||
|
||||
describe("assembleExportBundle with includeHistory", () => {
|
||||
it("excludes undo/redo stacks when includeHistory is false", () => {
|
||||
const bundle = assembleExportBundle(
|
||||
encounter,
|
||||
undoRedoState,
|
||||
playerCharacters,
|
||||
false,
|
||||
);
|
||||
expect(bundle.undoStack).toHaveLength(0);
|
||||
expect(bundle.redoStack).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("includes undo/redo stacks when includeHistory is true", () => {
|
||||
const bundle = assembleExportBundle(
|
||||
encounter,
|
||||
undoRedoState,
|
||||
playerCharacters,
|
||||
true,
|
||||
);
|
||||
expect(bundle.undoStack).toEqual(undoRedoState.undoStack);
|
||||
expect(bundle.redoStack).toEqual(undoRedoState.redoStack);
|
||||
});
|
||||
|
||||
it("includes undo/redo stacks by default", () => {
|
||||
const bundle = assembleExportBundle(
|
||||
encounter,
|
||||
undoRedoState,
|
||||
playerCharacters,
|
||||
);
|
||||
expect(bundle.undoStack).toEqual(undoRedoState.undoStack);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bundleToJson", () => {
|
||||
it("produces valid JSON that round-trips through validateImportBundle", () => {
|
||||
const bundle = assembleExportBundle(
|
||||
encounter,
|
||||
undoRedoState,
|
||||
playerCharacters,
|
||||
);
|
||||
const json = bundleToJson(bundle);
|
||||
const parsed: unknown = JSON.parse(json);
|
||||
const result = validateImportBundle(parsed);
|
||||
expect(typeof result).toBe("object");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveFilename", () => {
|
||||
it("uses date-based default when no name provided", () => {
|
||||
const result = resolveFilename();
|
||||
expect(result).toMatch(DEFAULT_FILENAME_RE);
|
||||
});
|
||||
|
||||
it("uses date-based default for empty string", () => {
|
||||
const result = resolveFilename("");
|
||||
expect(result).toMatch(DEFAULT_FILENAME_RE);
|
||||
});
|
||||
|
||||
it("uses date-based default for whitespace-only string", () => {
|
||||
const result = resolveFilename(" ");
|
||||
expect(result).toMatch(DEFAULT_FILENAME_RE);
|
||||
});
|
||||
|
||||
it("appends .json to a custom name", () => {
|
||||
expect(resolveFilename("my-encounter")).toBe("my-encounter.json");
|
||||
});
|
||||
|
||||
it("does not double-append .json", () => {
|
||||
expect(resolveFilename("my-encounter.json")).toBe("my-encounter.json");
|
||||
});
|
||||
|
||||
it("trims whitespace from custom name", () => {
|
||||
expect(resolveFilename(" my-encounter ")).toBe("my-encounter.json");
|
||||
});
|
||||
});
|
||||
|
||||
describe("round-trip: export then import", () => {
|
||||
it("produces identical state after round-trip", () => {
|
||||
const bundle = assembleExportBundle(
|
||||
encounter,
|
||||
undoRedoState,
|
||||
playerCharacters,
|
||||
);
|
||||
|
||||
const serialized = JSON.parse(JSON.stringify(bundle));
|
||||
const result = validateImportBundle(serialized);
|
||||
|
||||
expect(typeof result).toBe("object");
|
||||
const imported = result as ExportBundle;
|
||||
expect(imported.version).toBe(bundle.version);
|
||||
expect(imported.encounter).toEqual(bundle.encounter);
|
||||
expect(imported.undoStack).toEqual(bundle.undoStack);
|
||||
expect(imported.redoStack).toEqual(bundle.redoStack);
|
||||
expect(imported.playerCharacters).toEqual(bundle.playerCharacters);
|
||||
});
|
||||
|
||||
it("round-trips an empty encounter", () => {
|
||||
const emptyEncounter: Encounter = {
|
||||
combatants: [],
|
||||
activeIndex: 0,
|
||||
roundNumber: 1,
|
||||
};
|
||||
const emptyUndoRedo: UndoRedoState = {
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
};
|
||||
const bundle = assembleExportBundle(emptyEncounter, emptyUndoRedo, []);
|
||||
const serialized = JSON.parse(JSON.stringify(bundle));
|
||||
const result = validateImportBundle(serialized);
|
||||
|
||||
expect(typeof result).toBe("object");
|
||||
const imported = result as ExportBundle;
|
||||
expect(imported.encounter.combatants).toHaveLength(0);
|
||||
expect(imported.undoStack).toHaveLength(0);
|
||||
expect(imported.redoStack).toHaveLength(0);
|
||||
expect(imported.playerCharacters).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
import type { ExportBundle } from "@initiative/domain";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { validateImportBundle } from "../persistence/export-import.js";
|
||||
|
||||
function validBundle(): Record<string, unknown> {
|
||||
return {
|
||||
version: 1,
|
||||
exportedAt: "2026-03-27T12:00:00.000Z",
|
||||
encounter: {
|
||||
combatants: [{ id: "c-1", name: "Goblin", initiative: 15 }],
|
||||
activeIndex: 0,
|
||||
roundNumber: 1,
|
||||
},
|
||||
undoStack: [],
|
||||
redoStack: [],
|
||||
playerCharacters: [],
|
||||
};
|
||||
}
|
||||
|
||||
describe("validateImportBundle", () => {
|
||||
it("accepts a valid bundle", () => {
|
||||
const result = validateImportBundle(validBundle());
|
||||
expect(typeof result).toBe("object");
|
||||
const bundle = result as ExportBundle;
|
||||
expect(bundle.version).toBe(1);
|
||||
expect(bundle.encounter.combatants).toHaveLength(1);
|
||||
expect(bundle.encounter.combatants[0].name).toBe("Goblin");
|
||||
});
|
||||
|
||||
it("accepts a valid bundle with empty encounter", () => {
|
||||
const input = {
|
||||
...validBundle(),
|
||||
encounter: { combatants: [], activeIndex: 0, roundNumber: 1 },
|
||||
};
|
||||
const result = validateImportBundle(input);
|
||||
expect(typeof result).toBe("object");
|
||||
const bundle = result as ExportBundle;
|
||||
expect(bundle.encounter.combatants).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("accepts a bundle with undo/redo stacks", () => {
|
||||
const enc = {
|
||||
combatants: [{ id: "c-1", name: "Orc" }],
|
||||
activeIndex: 0,
|
||||
roundNumber: 1,
|
||||
};
|
||||
const input = {
|
||||
...validBundle(),
|
||||
undoStack: [enc],
|
||||
redoStack: [enc],
|
||||
};
|
||||
const result = validateImportBundle(input);
|
||||
expect(typeof result).toBe("object");
|
||||
const bundle = result as ExportBundle;
|
||||
expect(bundle.undoStack).toHaveLength(1);
|
||||
expect(bundle.redoStack).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("accepts a bundle with player characters", () => {
|
||||
const input = {
|
||||
...validBundle(),
|
||||
playerCharacters: [
|
||||
{
|
||||
id: "pc-1",
|
||||
name: "Aria",
|
||||
ac: 16,
|
||||
maxHp: 45,
|
||||
color: "blue",
|
||||
icon: "sword",
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = validateImportBundle(input);
|
||||
expect(typeof result).toBe("object");
|
||||
const bundle = result as ExportBundle;
|
||||
expect(bundle.playerCharacters).toHaveLength(1);
|
||||
expect(bundle.playerCharacters[0].name).toBe("Aria");
|
||||
});
|
||||
|
||||
it("rejects non-object input", () => {
|
||||
expect(validateImportBundle(null)).toBe("Invalid file format");
|
||||
expect(validateImportBundle(42)).toBe("Invalid file format");
|
||||
expect(validateImportBundle("string")).toBe("Invalid file format");
|
||||
expect(validateImportBundle([])).toBe("Invalid file format");
|
||||
expect(validateImportBundle(undefined)).toBe("Invalid file format");
|
||||
});
|
||||
|
||||
it("rejects missing version field", () => {
|
||||
const input = validBundle();
|
||||
delete input.version;
|
||||
expect(validateImportBundle(input)).toBe("Invalid file format");
|
||||
});
|
||||
|
||||
it("rejects version 0 or negative", () => {
|
||||
expect(validateImportBundle({ ...validBundle(), version: 0 })).toBe(
|
||||
"Invalid file format",
|
||||
);
|
||||
expect(validateImportBundle({ ...validBundle(), version: -1 })).toBe(
|
||||
"Invalid file format",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects unknown version", () => {
|
||||
expect(validateImportBundle({ ...validBundle(), version: 99 })).toBe(
|
||||
"Invalid file format",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects missing encounter field", () => {
|
||||
const input = validBundle();
|
||||
delete input.encounter;
|
||||
expect(validateImportBundle(input)).toBe("Invalid encounter data");
|
||||
});
|
||||
|
||||
it("rejects invalid encounter data", () => {
|
||||
expect(
|
||||
validateImportBundle({ ...validBundle(), encounter: "not an object" }),
|
||||
).toBe("Invalid encounter data");
|
||||
});
|
||||
|
||||
it("rejects missing undoStack", () => {
|
||||
const input = validBundle();
|
||||
delete input.undoStack;
|
||||
expect(validateImportBundle(input)).toBe("Invalid file format");
|
||||
});
|
||||
|
||||
it("rejects missing redoStack", () => {
|
||||
const input = validBundle();
|
||||
delete input.redoStack;
|
||||
expect(validateImportBundle(input)).toBe("Invalid file format");
|
||||
});
|
||||
|
||||
it("rejects missing playerCharacters", () => {
|
||||
const input = validBundle();
|
||||
delete input.playerCharacters;
|
||||
expect(validateImportBundle(input)).toBe("Invalid file format");
|
||||
});
|
||||
|
||||
it("rejects non-string exportedAt", () => {
|
||||
expect(validateImportBundle({ ...validBundle(), exportedAt: 12345 })).toBe(
|
||||
"Invalid file format",
|
||||
);
|
||||
});
|
||||
|
||||
it("drops invalid entries from undo stack", () => {
|
||||
const valid = {
|
||||
combatants: [{ id: "c-1", name: "Orc" }],
|
||||
activeIndex: 0,
|
||||
roundNumber: 1,
|
||||
};
|
||||
const input = {
|
||||
...validBundle(),
|
||||
undoStack: [valid, "invalid", { bad: true }, valid],
|
||||
};
|
||||
const result = validateImportBundle(input);
|
||||
expect(typeof result).toBe("object");
|
||||
const bundle = result as ExportBundle;
|
||||
expect(bundle.undoStack).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("drops invalid player characters", () => {
|
||||
const input = {
|
||||
...validBundle(),
|
||||
playerCharacters: [
|
||||
{ id: "pc-1", name: "Valid", ac: 10, maxHp: 20 },
|
||||
{ id: "", name: "Bad ID" },
|
||||
"not an object",
|
||||
{ id: "pc-3", name: "Also Valid", ac: 15, maxHp: 30 },
|
||||
],
|
||||
};
|
||||
const result = validateImportBundle(input);
|
||||
expect(typeof result).toBe("object");
|
||||
const bundle = result as ExportBundle;
|
||||
expect(bundle.playerCharacters).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("rejects JSON array instead of object", () => {
|
||||
expect(validateImportBundle([1, 2, 3])).toBe("Invalid file format");
|
||||
});
|
||||
|
||||
it("rejects encounter that fails rehydration (missing combatant fields)", () => {
|
||||
const input = {
|
||||
...validBundle(),
|
||||
encounter: {
|
||||
combatants: [{ noId: true }],
|
||||
activeIndex: 0,
|
||||
roundNumber: 1,
|
||||
},
|
||||
};
|
||||
expect(validateImportBundle(input)).toBe("Invalid encounter data");
|
||||
});
|
||||
|
||||
it("strips invalid color/icon from player characters but keeps the character", () => {
|
||||
const input = {
|
||||
...validBundle(),
|
||||
playerCharacters: [
|
||||
{
|
||||
id: "pc-1",
|
||||
name: "Test",
|
||||
ac: 10,
|
||||
maxHp: 20,
|
||||
color: "neon-pink",
|
||||
icon: "bazooka",
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = validateImportBundle(input);
|
||||
// rehydrateCharacter rejects characters with invalid color/icon members
|
||||
// that are not in the valid sets, so this character is dropped
|
||||
expect(typeof result).toBe("object");
|
||||
const bundle = result as ExportBundle;
|
||||
expect(bundle.playerCharacters).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("keeps player characters with valid optional color and icon", () => {
|
||||
const input = {
|
||||
...validBundle(),
|
||||
playerCharacters: [
|
||||
{
|
||||
id: "pc-1",
|
||||
name: "Aria",
|
||||
ac: 16,
|
||||
maxHp: 45,
|
||||
color: "blue",
|
||||
icon: "sword",
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = validateImportBundle(input);
|
||||
expect(typeof result).toBe("object");
|
||||
const bundle = result as ExportBundle;
|
||||
expect(bundle.playerCharacters).toHaveLength(1);
|
||||
expect(bundle.playerCharacters[0].color).toBe("blue");
|
||||
expect(bundle.playerCharacters[0].icon).toBe("sword");
|
||||
});
|
||||
|
||||
it("ignores unknown extra fields on the bundle", () => {
|
||||
const input = {
|
||||
...validBundle(),
|
||||
unknownField: "should be ignored",
|
||||
anotherExtra: 42,
|
||||
};
|
||||
const result = validateImportBundle(input);
|
||||
expect(typeof result).toBe("object");
|
||||
const bundle = result as ExportBundle;
|
||||
expect(bundle.version).toBe(1);
|
||||
expect("unknownField" in bundle).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -6,11 +6,19 @@ import { combatantId } from "@initiative/domain";
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Mock the context module
|
||||
// Mock the context modules
|
||||
vi.mock("../../contexts/encounter-context.js", () => ({
|
||||
useEncounterContext: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../contexts/player-characters-context.js", () => ({
|
||||
usePlayerCharactersContext: vi.fn().mockReturnValue({ characters: [] }),
|
||||
}));
|
||||
|
||||
vi.mock("../../contexts/bestiary-context.js", () => ({
|
||||
useBestiaryContext: vi.fn().mockReturnValue({ getCreature: () => undefined }),
|
||||
}));
|
||||
|
||||
import { useEncounterContext } from "../../contexts/encounter-context.js";
|
||||
import { TurnNavigation } from "../turn-navigation.js";
|
||||
|
||||
@@ -52,12 +60,17 @@ function mockContext(overrides: Partial<Encounter> = {}) {
|
||||
toggleCondition: vi.fn(),
|
||||
toggleConcentration: vi.fn(),
|
||||
addFromBestiary: vi.fn(),
|
||||
addMultipleFromBestiary: vi.fn(),
|
||||
addFromPlayerCharacter: vi.fn(),
|
||||
makeStore: vi.fn(),
|
||||
withUndo: vi.fn((action: () => unknown) => action()),
|
||||
undo: vi.fn(),
|
||||
redo: vi.fn(),
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
undoRedoState: { undoStack: [], redoStack: [] },
|
||||
setEncounter: vi.fn(),
|
||||
setUndoRedoState: vi.fn(),
|
||||
events: [],
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { PlayerCharacter } from "@initiative/domain";
|
||||
import {
|
||||
Check,
|
||||
Download,
|
||||
Eye,
|
||||
EyeOff,
|
||||
Import,
|
||||
@@ -8,13 +9,15 @@ import {
|
||||
Minus,
|
||||
Plus,
|
||||
Settings,
|
||||
Upload,
|
||||
Users,
|
||||
} from "lucide-react";
|
||||
import React, { type RefObject, useCallback, useState } from "react";
|
||||
import React, { type RefObject, useCallback, useRef, useState } from "react";
|
||||
import type { SearchResult } from "../contexts/bestiary-context.js";
|
||||
import { useBulkImportContext } from "../contexts/bulk-import-context.js";
|
||||
import { useEncounterContext } from "../contexts/encounter-context.js";
|
||||
import { useInitiativeRollsContext } from "../contexts/initiative-rolls-context.js";
|
||||
import { usePlayerCharactersContext } from "../contexts/player-characters-context.js";
|
||||
import {
|
||||
creatureKey,
|
||||
type QueuedCreature,
|
||||
@@ -23,9 +26,20 @@ import {
|
||||
} from "../hooks/use-action-bar-state.js";
|
||||
import { useLongPress } from "../hooks/use-long-press.js";
|
||||
import { cn } from "../lib/utils.js";
|
||||
import {
|
||||
assembleExportBundle,
|
||||
bundleToJson,
|
||||
readImportFile,
|
||||
triggerDownload,
|
||||
validateImportBundle,
|
||||
} from "../persistence/export-import.js";
|
||||
import { D20Icon } from "./d20-icon.js";
|
||||
import { ExportMethodDialog } from "./export-method-dialog.js";
|
||||
import { ImportConfirmDialog } from "./import-confirm-prompt.js";
|
||||
import { ImportMethodDialog } from "./import-method-dialog.js";
|
||||
import { PLAYER_COLOR_HEX, PLAYER_ICON_MAP } from "./player-icon-map.js";
|
||||
import { RollModeMenu } from "./roll-mode-menu.js";
|
||||
import { Toast } from "./toast.js";
|
||||
import { Button } from "./ui/button.js";
|
||||
import { Input } from "./ui/input.js";
|
||||
import { OverflowMenu, type OverflowMenuItem } from "./ui/overflow-menu.js";
|
||||
@@ -345,6 +359,8 @@ function buildOverflowItems(opts: {
|
||||
bestiaryLoaded: boolean;
|
||||
onBulkImport?: () => void;
|
||||
bulkImportDisabled?: boolean;
|
||||
onExportEncounter: () => void;
|
||||
onImportEncounter: () => void;
|
||||
onOpenSettings?: () => void;
|
||||
}): OverflowMenuItem[] {
|
||||
const items: OverflowMenuItem[] = [];
|
||||
@@ -370,6 +386,16 @@ function buildOverflowItems(opts: {
|
||||
disabled: opts.bulkImportDisabled,
|
||||
});
|
||||
}
|
||||
items.push({
|
||||
icon: <Download className="h-4 w-4" />,
|
||||
label: "Export Encounter",
|
||||
onClick: opts.onExportEncounter,
|
||||
});
|
||||
items.push({
|
||||
icon: <Upload className="h-4 w-4" />,
|
||||
label: "Import Encounter",
|
||||
onClick: opts.onImportEncounter,
|
||||
});
|
||||
if (opts.onOpenSettings) {
|
||||
items.push({
|
||||
icon: <Settings className="h-4 w-4" />,
|
||||
@@ -413,6 +439,116 @@ export function ActionBar({
|
||||
} = useActionBarState();
|
||||
|
||||
const { state: bulkImportState } = useBulkImportContext();
|
||||
const {
|
||||
encounter,
|
||||
undoRedoState,
|
||||
isEmpty: encounterIsEmpty,
|
||||
setEncounter,
|
||||
setUndoRedoState,
|
||||
} = useEncounterContext();
|
||||
const { characters: playerCharacters, replacePlayerCharacters } =
|
||||
usePlayerCharactersContext();
|
||||
|
||||
const importFileRef = useRef<HTMLInputElement>(null);
|
||||
const [importError, setImportError] = useState<string | null>(null);
|
||||
const [showExportMethod, setShowExportMethod] = useState(false);
|
||||
const [showImportMethod, setShowImportMethod] = useState(false);
|
||||
const [showImportConfirm, setShowImportConfirm] = useState(false);
|
||||
const pendingBundleRef = useRef<
|
||||
import("@initiative/domain").ExportBundle | null
|
||||
>(null);
|
||||
|
||||
const handleExportDownload = useCallback(
|
||||
(includeHistory: boolean, filename: string) => {
|
||||
const bundle = assembleExportBundle(
|
||||
encounter,
|
||||
undoRedoState,
|
||||
playerCharacters,
|
||||
includeHistory,
|
||||
);
|
||||
triggerDownload(bundle, filename);
|
||||
},
|
||||
[encounter, undoRedoState, playerCharacters],
|
||||
);
|
||||
|
||||
const handleExportClipboard = useCallback(
|
||||
(includeHistory: boolean) => {
|
||||
const bundle = assembleExportBundle(
|
||||
encounter,
|
||||
undoRedoState,
|
||||
playerCharacters,
|
||||
includeHistory,
|
||||
);
|
||||
void navigator.clipboard.writeText(bundleToJson(bundle));
|
||||
},
|
||||
[encounter, undoRedoState, playerCharacters],
|
||||
);
|
||||
|
||||
const applyImport = useCallback(
|
||||
(bundle: import("@initiative/domain").ExportBundle) => {
|
||||
setEncounter(bundle.encounter);
|
||||
setUndoRedoState({
|
||||
undoStack: bundle.undoStack,
|
||||
redoStack: bundle.redoStack,
|
||||
});
|
||||
replacePlayerCharacters([...bundle.playerCharacters]);
|
||||
},
|
||||
[setEncounter, setUndoRedoState, replacePlayerCharacters],
|
||||
);
|
||||
|
||||
const handleValidatedBundle = useCallback(
|
||||
(result: import("@initiative/domain").ExportBundle | string) => {
|
||||
if (typeof result === "string") {
|
||||
setImportError(result);
|
||||
return;
|
||||
}
|
||||
if (encounterIsEmpty) {
|
||||
applyImport(result);
|
||||
} else {
|
||||
pendingBundleRef.current = result;
|
||||
setShowImportConfirm(true);
|
||||
}
|
||||
},
|
||||
[encounterIsEmpty, applyImport],
|
||||
);
|
||||
|
||||
const handleImportFile = useCallback(
|
||||
async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
if (importFileRef.current) importFileRef.current.value = "";
|
||||
|
||||
setImportError(null);
|
||||
handleValidatedBundle(await readImportFile(file));
|
||||
},
|
||||
[handleValidatedBundle],
|
||||
);
|
||||
|
||||
const handleImportClipboard = useCallback(
|
||||
(text: string) => {
|
||||
setImportError(null);
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(text);
|
||||
handleValidatedBundle(validateImportBundle(parsed));
|
||||
} catch {
|
||||
setImportError("Invalid file format");
|
||||
}
|
||||
},
|
||||
[handleValidatedBundle],
|
||||
);
|
||||
|
||||
const handleImportConfirm = useCallback(() => {
|
||||
if (pendingBundleRef.current) {
|
||||
applyImport(pendingBundleRef.current);
|
||||
pendingBundleRef.current = null;
|
||||
}
|
||||
setShowImportConfirm(false);
|
||||
}, [applyImport]);
|
||||
|
||||
const handleImportCancel = useCallback(() => {
|
||||
pendingBundleRef.current = null;
|
||||
setShowImportConfirm(false);
|
||||
}, []);
|
||||
|
||||
const overflowItems = buildOverflowItems({
|
||||
onManagePlayers,
|
||||
@@ -420,6 +556,8 @@ export function ActionBar({
|
||||
bestiaryLoaded,
|
||||
onBulkImport: showBulkImport,
|
||||
bulkImportDisabled: bulkImportState.status === "loading",
|
||||
onExportEncounter: () => setShowExportMethod(true),
|
||||
onImportEncounter: () => setShowImportMethod(true),
|
||||
onOpenSettings,
|
||||
});
|
||||
|
||||
@@ -501,6 +639,37 @@ export function ActionBar({
|
||||
<RollAllButton />
|
||||
{overflowItems.length > 0 && <OverflowMenu items={overflowItems} />}
|
||||
</form>
|
||||
<input
|
||||
ref={importFileRef}
|
||||
type="file"
|
||||
accept=".json"
|
||||
className="hidden"
|
||||
onChange={handleImportFile}
|
||||
/>
|
||||
{!!importError && (
|
||||
<Toast
|
||||
message={importError}
|
||||
onDismiss={() => setImportError(null)}
|
||||
autoDismissMs={5000}
|
||||
/>
|
||||
)}
|
||||
<ExportMethodDialog
|
||||
open={showExportMethod}
|
||||
onDownload={handleExportDownload}
|
||||
onCopyToClipboard={handleExportClipboard}
|
||||
onClose={() => setShowExportMethod(false)}
|
||||
/>
|
||||
<ImportMethodDialog
|
||||
open={showImportMethod}
|
||||
onSelectFile={() => importFileRef.current?.click()}
|
||||
onSubmitClipboard={handleImportClipboard}
|
||||
onClose={() => setShowImportMethod(false)}
|
||||
/>
|
||||
<ImportConfirmDialog
|
||||
open={showImportConfirm}
|
||||
onConfirm={handleImportConfirm}
|
||||
onCancel={handleImportCancel}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,66 +3,17 @@ import {
|
||||
getConditionDescription,
|
||||
getConditionsForEdition,
|
||||
} from "@initiative/domain";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import {
|
||||
ArrowDown,
|
||||
Ban,
|
||||
BatteryLow,
|
||||
Droplet,
|
||||
EarOff,
|
||||
EyeOff,
|
||||
Gem,
|
||||
Ghost,
|
||||
Hand,
|
||||
Heart,
|
||||
Link,
|
||||
Moon,
|
||||
ShieldMinus,
|
||||
Siren,
|
||||
Snail,
|
||||
Sparkles,
|
||||
ZapOff,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import { useLayoutEffect, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { useRulesEditionContext } from "../contexts/rules-edition-context.js";
|
||||
import { useClickOutside } from "../hooks/use-click-outside.js";
|
||||
import { cn } from "../lib/utils";
|
||||
import {
|
||||
CONDITION_COLOR_CLASSES,
|
||||
CONDITION_ICON_MAP,
|
||||
} from "./condition-styles.js";
|
||||
import { Tooltip } from "./ui/tooltip.js";
|
||||
|
||||
const ICON_MAP: Record<string, LucideIcon> = {
|
||||
EyeOff,
|
||||
Heart,
|
||||
EarOff,
|
||||
BatteryLow,
|
||||
Siren,
|
||||
Hand,
|
||||
Ban,
|
||||
Ghost,
|
||||
ZapOff,
|
||||
Gem,
|
||||
Droplet,
|
||||
ArrowDown,
|
||||
Link,
|
||||
ShieldMinus,
|
||||
Snail,
|
||||
Sparkles,
|
||||
Moon,
|
||||
};
|
||||
|
||||
const COLOR_CLASSES: Record<string, string> = {
|
||||
neutral: "text-muted-foreground",
|
||||
pink: "text-pink-400",
|
||||
amber: "text-amber-400",
|
||||
orange: "text-orange-400",
|
||||
gray: "text-gray-400",
|
||||
violet: "text-violet-400",
|
||||
yellow: "text-yellow-400",
|
||||
slate: "text-slate-400",
|
||||
green: "text-green-400",
|
||||
indigo: "text-indigo-400",
|
||||
sky: "text-sky-400",
|
||||
};
|
||||
|
||||
interface ConditionPickerProps {
|
||||
anchorRef: React.RefObject<HTMLElement | null>;
|
||||
activeConditions: readonly ConditionId[] | undefined;
|
||||
@@ -104,15 +55,7 @@ export function ConditionPicker({
|
||||
setPos({ top, left: anchorRect.left, maxHeight });
|
||||
}, [anchorRef]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleClickOutside(e: MouseEvent) {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, [onClose]);
|
||||
useClickOutside(ref, onClose);
|
||||
|
||||
const { edition } = useRulesEditionContext();
|
||||
const conditions = getConditionsForEdition(edition);
|
||||
@@ -129,10 +72,11 @@ export function ConditionPicker({
|
||||
}
|
||||
>
|
||||
{conditions.map((def) => {
|
||||
const Icon = ICON_MAP[def.iconName];
|
||||
const Icon = CONDITION_ICON_MAP[def.iconName];
|
||||
if (!Icon) return null;
|
||||
const isActive = active.has(def.id);
|
||||
const colorClass = COLOR_CLASSES[def.color] ?? "text-muted-foreground";
|
||||
const colorClass =
|
||||
CONDITION_COLOR_CLASSES[def.color] ?? "text-muted-foreground";
|
||||
return (
|
||||
<Tooltip
|
||||
key={def.id}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import {
|
||||
ArrowDown,
|
||||
Ban,
|
||||
BatteryLow,
|
||||
Droplet,
|
||||
EarOff,
|
||||
EyeOff,
|
||||
Gem,
|
||||
Ghost,
|
||||
Hand,
|
||||
Heart,
|
||||
Link,
|
||||
Moon,
|
||||
ShieldMinus,
|
||||
Siren,
|
||||
Snail,
|
||||
Sparkles,
|
||||
ZapOff,
|
||||
} from "lucide-react";
|
||||
|
||||
export const CONDITION_ICON_MAP: Record<string, LucideIcon> = {
|
||||
EyeOff,
|
||||
Heart,
|
||||
EarOff,
|
||||
BatteryLow,
|
||||
Siren,
|
||||
Hand,
|
||||
Ban,
|
||||
Ghost,
|
||||
ZapOff,
|
||||
Gem,
|
||||
Droplet,
|
||||
ArrowDown,
|
||||
Link,
|
||||
ShieldMinus,
|
||||
Snail,
|
||||
Sparkles,
|
||||
Moon,
|
||||
};
|
||||
|
||||
export const CONDITION_COLOR_CLASSES: Record<string, string> = {
|
||||
neutral: "text-muted-foreground",
|
||||
pink: "text-pink-400",
|
||||
amber: "text-amber-400",
|
||||
orange: "text-orange-400",
|
||||
gray: "text-gray-400",
|
||||
violet: "text-violet-400",
|
||||
yellow: "text-yellow-400",
|
||||
slate: "text-slate-400",
|
||||
green: "text-green-400",
|
||||
indigo: "text-indigo-400",
|
||||
sky: "text-sky-400",
|
||||
};
|
||||
@@ -3,65 +3,15 @@ import {
|
||||
type ConditionId,
|
||||
getConditionDescription,
|
||||
} from "@initiative/domain";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
import {
|
||||
ArrowDown,
|
||||
Ban,
|
||||
BatteryLow,
|
||||
Droplet,
|
||||
EarOff,
|
||||
EyeOff,
|
||||
Gem,
|
||||
Ghost,
|
||||
Hand,
|
||||
Heart,
|
||||
Link,
|
||||
Moon,
|
||||
Plus,
|
||||
ShieldMinus,
|
||||
Siren,
|
||||
Snail,
|
||||
Sparkles,
|
||||
ZapOff,
|
||||
} from "lucide-react";
|
||||
import { Plus } from "lucide-react";
|
||||
import { useRulesEditionContext } from "../contexts/rules-edition-context.js";
|
||||
import { cn } from "../lib/utils.js";
|
||||
import {
|
||||
CONDITION_COLOR_CLASSES,
|
||||
CONDITION_ICON_MAP,
|
||||
} from "./condition-styles.js";
|
||||
import { Tooltip } from "./ui/tooltip.js";
|
||||
|
||||
const ICON_MAP: Record<string, LucideIcon> = {
|
||||
EyeOff,
|
||||
Heart,
|
||||
EarOff,
|
||||
BatteryLow,
|
||||
Siren,
|
||||
Hand,
|
||||
Ban,
|
||||
Ghost,
|
||||
ZapOff,
|
||||
Gem,
|
||||
Droplet,
|
||||
ArrowDown,
|
||||
Link,
|
||||
ShieldMinus,
|
||||
Snail,
|
||||
Sparkles,
|
||||
Moon,
|
||||
};
|
||||
|
||||
const COLOR_CLASSES: Record<string, string> = {
|
||||
neutral: "text-muted-foreground",
|
||||
pink: "text-pink-400",
|
||||
amber: "text-amber-400",
|
||||
orange: "text-orange-400",
|
||||
gray: "text-gray-400",
|
||||
violet: "text-violet-400",
|
||||
yellow: "text-yellow-400",
|
||||
slate: "text-slate-400",
|
||||
green: "text-green-400",
|
||||
indigo: "text-indigo-400",
|
||||
sky: "text-sky-400",
|
||||
};
|
||||
|
||||
interface ConditionTagsProps {
|
||||
conditions: readonly ConditionId[] | undefined;
|
||||
onRemove: (conditionId: ConditionId) => void;
|
||||
@@ -79,9 +29,10 @@ export function ConditionTags({
|
||||
{conditions?.map((condId) => {
|
||||
const def = CONDITION_DEFINITIONS.find((d) => d.id === condId);
|
||||
if (!def) return null;
|
||||
const Icon = ICON_MAP[def.iconName];
|
||||
const Icon = CONDITION_ICON_MAP[def.iconName];
|
||||
if (!Icon) return null;
|
||||
const colorClass = COLOR_CLASSES[def.color] ?? "text-muted-foreground";
|
||||
const colorClass =
|
||||
CONDITION_COLOR_CLASSES[def.color] ?? "text-muted-foreground";
|
||||
return (
|
||||
<Tooltip
|
||||
key={condId}
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
import type { PlayerCharacter } from "@initiative/domain";
|
||||
import { X } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { ColorPalette } from "./color-palette";
|
||||
import { IconGrid } from "./icon-grid";
|
||||
import { Button } from "./ui/button";
|
||||
import { Dialog } from "./ui/dialog";
|
||||
import { Input } from "./ui/input";
|
||||
|
||||
function parseLevel(value: string): number | undefined | "invalid" {
|
||||
if (value.trim() === "") return undefined;
|
||||
const n = Number.parseInt(value, 10);
|
||||
if (Number.isNaN(n) || n < 1 || n > 20) return "invalid";
|
||||
return n;
|
||||
}
|
||||
|
||||
interface CreatePlayerModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
@@ -15,6 +23,7 @@ interface CreatePlayerModalProps {
|
||||
maxHp: number,
|
||||
color: string | undefined,
|
||||
icon: string | undefined,
|
||||
level: number | undefined,
|
||||
) => void;
|
||||
playerCharacter?: PlayerCharacter;
|
||||
}
|
||||
@@ -25,12 +34,12 @@ export function CreatePlayerModal({
|
||||
onSave,
|
||||
playerCharacter,
|
||||
}: Readonly<CreatePlayerModalProps>) {
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const [name, setName] = useState("");
|
||||
const [ac, setAc] = useState("10");
|
||||
const [maxHp, setMaxHp] = useState("10");
|
||||
const [color, setColor] = useState("blue");
|
||||
const [icon, setIcon] = useState("sword");
|
||||
const [level, setLevel] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const isEdit = !!playerCharacter;
|
||||
@@ -43,45 +52,23 @@ export function CreatePlayerModal({
|
||||
setMaxHp(String(playerCharacter.maxHp));
|
||||
setColor(playerCharacter.color ?? "");
|
||||
setIcon(playerCharacter.icon ?? "");
|
||||
setLevel(
|
||||
playerCharacter.level === undefined
|
||||
? ""
|
||||
: String(playerCharacter.level),
|
||||
);
|
||||
} else {
|
||||
setName("");
|
||||
setAc("10");
|
||||
setMaxHp("10");
|
||||
setColor("");
|
||||
setIcon("");
|
||||
setLevel("");
|
||||
}
|
||||
setError("");
|
||||
}
|
||||
}, [open, playerCharacter]);
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
if (!dialog) return;
|
||||
if (open && !dialog.open) {
|
||||
dialog.showModal();
|
||||
} else if (!open && dialog.open) {
|
||||
dialog.close();
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
if (!dialog) return;
|
||||
function handleCancel(e: Event) {
|
||||
e.preventDefault();
|
||||
onClose();
|
||||
}
|
||||
function handleBackdropClick(e: MouseEvent) {
|
||||
if (e.target === dialog) onClose();
|
||||
}
|
||||
dialog.addEventListener("cancel", handleCancel);
|
||||
dialog.addEventListener("mousedown", handleBackdropClick);
|
||||
return () => {
|
||||
dialog.removeEventListener("cancel", handleCancel);
|
||||
dialog.removeEventListener("mousedown", handleBackdropClick);
|
||||
};
|
||||
}, [onClose]);
|
||||
|
||||
const handleSubmit = (e: React.SubmitEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const trimmed = name.trim();
|
||||
@@ -99,15 +86,24 @@ export function CreatePlayerModal({
|
||||
setError("Max HP must be at least 1");
|
||||
return;
|
||||
}
|
||||
onSave(trimmed, acNum, hpNum, color || undefined, icon || undefined);
|
||||
const levelNum = parseLevel(level);
|
||||
if (levelNum === "invalid") {
|
||||
setError("Level must be between 1 and 20");
|
||||
return;
|
||||
}
|
||||
onSave(
|
||||
trimmed,
|
||||
acNum,
|
||||
hpNum,
|
||||
color || undefined,
|
||||
icon || undefined,
|
||||
levelNum,
|
||||
);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={dialogRef}
|
||||
className="card-glow m-auto w-full max-w-md rounded-lg border border-border bg-card p-6 backdrop:bg-black/50"
|
||||
>
|
||||
<Dialog open={open} onClose={onClose} className="card-glow w-full max-w-md">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h2 className="font-semibold text-foreground text-lg">
|
||||
{isEdit ? "Edit Player" : "Create Player"}
|
||||
@@ -166,6 +162,20 @@ export function CreatePlayerModal({
|
||||
className="text-center"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<span className="mb-1 block text-muted-foreground text-sm">
|
||||
Level
|
||||
</span>
|
||||
<Input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
value={level}
|
||||
onChange={(e) => setLevel(e.target.value)}
|
||||
placeholder="1-20"
|
||||
aria-label="Level"
|
||||
className="text-center"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
@@ -187,6 +197,6 @@ export function CreatePlayerModal({
|
||||
<Button type="submit">{isEdit ? "Save" : "Create"}</Button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { DifficultyResult, DifficultyTier } from "@initiative/domain";
|
||||
import { cn } from "../lib/utils.js";
|
||||
|
||||
const TIER_CONFIG: Record<
|
||||
DifficultyTier,
|
||||
{ filledBars: number; color: string; label: string }
|
||||
> = {
|
||||
trivial: { filledBars: 0, color: "", label: "Trivial" },
|
||||
low: { filledBars: 1, color: "bg-green-500", label: "Low" },
|
||||
moderate: { filledBars: 2, color: "bg-yellow-500", label: "Moderate" },
|
||||
high: { filledBars: 3, color: "bg-red-500", label: "High" },
|
||||
};
|
||||
|
||||
const BAR_HEIGHTS = ["h-2", "h-3", "h-4"] as const;
|
||||
|
||||
export function DifficultyIndicator({ result }: { result: DifficultyResult }) {
|
||||
const config = TIER_CONFIG[result.tier];
|
||||
const tooltip = `${config.label} encounter difficulty`;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex items-end gap-0.5"
|
||||
title={tooltip}
|
||||
role="img"
|
||||
aria-label={tooltip}
|
||||
>
|
||||
{BAR_HEIGHTS.map((height, i) => (
|
||||
<div
|
||||
key={height}
|
||||
className={cn(
|
||||
"w-1 rounded-sm",
|
||||
height,
|
||||
i < config.filledBars ? config.color : "bg-muted",
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { Check, ClipboardCopy, Download } from "lucide-react";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Dialog, DialogHeader } from "./ui/dialog.js";
|
||||
import { Input } from "./ui/input.js";
|
||||
|
||||
interface ExportMethodDialogProps {
|
||||
open: boolean;
|
||||
onDownload: (includeHistory: boolean, filename: string) => void;
|
||||
onCopyToClipboard: (includeHistory: boolean) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function ExportMethodDialog({
|
||||
open,
|
||||
onDownload,
|
||||
onCopyToClipboard,
|
||||
onClose,
|
||||
}: Readonly<ExportMethodDialogProps>) {
|
||||
const [includeHistory, setIncludeHistory] = useState(false);
|
||||
const [filename, setFilename] = useState("");
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
setIncludeHistory(false);
|
||||
setFilename("");
|
||||
setCopied(false);
|
||||
onClose();
|
||||
}, [onClose]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={handleClose} className="w-80">
|
||||
<DialogHeader title="Export Encounter" onClose={handleClose} />
|
||||
<div className="mb-3">
|
||||
<Input
|
||||
type="text"
|
||||
value={filename}
|
||||
onChange={(e) => setFilename(e.target.value)}
|
||||
placeholder="Filename (optional)"
|
||||
/>
|
||||
</div>
|
||||
<label className="mb-4 flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includeHistory}
|
||||
onChange={(e) => setIncludeHistory(e.target.checked)}
|
||||
className="accent-accent"
|
||||
/>
|
||||
<span className="text-foreground">Include undo/redo history</span>
|
||||
</label>
|
||||
<div className="flex flex-col gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-3 rounded-lg border border-border px-4 py-3 text-left text-foreground text-sm hover:bg-hover-neutral-bg"
|
||||
onClick={() => {
|
||||
onDownload(includeHistory, filename);
|
||||
handleClose();
|
||||
}}
|
||||
>
|
||||
<Download className="h-5 w-5 text-muted-foreground" />
|
||||
<div>
|
||||
<div className="font-medium">Download file</div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
Save as a JSON file
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-3 rounded-lg border border-border px-4 py-3 text-left text-foreground text-sm hover:bg-hover-neutral-bg"
|
||||
onClick={() => {
|
||||
onCopyToClipboard(includeHistory);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}}
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="h-5 w-5 text-green-400" />
|
||||
) : (
|
||||
<ClipboardCopy className="h-5 w-5 text-muted-foreground" />
|
||||
)}
|
||||
<div>
|
||||
<div className="font-medium">
|
||||
{copied ? "Copied!" : "Copy to clipboard"}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
Copy JSON to your clipboard
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useClickOutside } from "../hooks/use-click-outside.js";
|
||||
import { Input } from "./ui/input";
|
||||
|
||||
const DIGITS_ONLY_REGEX = /^\d+$/;
|
||||
@@ -48,15 +49,7 @@ export function HpAdjustPopover({
|
||||
requestAnimationFrame(() => inputRef.current?.focus());
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
function handleClickOutside(e: MouseEvent) {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, [onClose]);
|
||||
useClickOutside(ref, onClose);
|
||||
|
||||
const parsedValue =
|
||||
inputValue === "" ? null : Number.parseInt(inputValue, 10);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Button } from "./ui/button.js";
|
||||
import { Dialog } from "./ui/dialog.js";
|
||||
|
||||
interface ImportConfirmDialogProps {
|
||||
open: boolean;
|
||||
onConfirm: () => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function ImportConfirmDialog({
|
||||
open,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: Readonly<ImportConfirmDialogProps>) {
|
||||
return (
|
||||
<Dialog open={open} onClose={onCancel}>
|
||||
<h2 className="mb-2 font-semibold text-lg">Replace current encounter?</h2>
|
||||
<p className="mb-4 text-muted-foreground text-sm">
|
||||
Importing will replace your current encounter, undo/redo history, and
|
||||
player characters. This cannot be undone.
|
||||
</p>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="button" onClick={onConfirm}>
|
||||
Import
|
||||
</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { ClipboardPaste, FileUp } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button } from "./ui/button.js";
|
||||
import { Dialog, DialogHeader } from "./ui/dialog.js";
|
||||
|
||||
interface ImportMethodDialogProps {
|
||||
open: boolean;
|
||||
onSelectFile: () => void;
|
||||
onSubmitClipboard: (text: string) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function ImportMethodDialog({
|
||||
open,
|
||||
onSelectFile,
|
||||
onSubmitClipboard,
|
||||
onClose,
|
||||
}: Readonly<ImportMethodDialogProps>) {
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const [mode, setMode] = useState<"pick" | "paste">("pick");
|
||||
const [pasteText, setPasteText] = useState("");
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
setMode("pick");
|
||||
setPasteText("");
|
||||
onClose();
|
||||
}, [onClose]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setMode("pick");
|
||||
setPasteText("");
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === "paste") {
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
}, [mode]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={handleClose} className="w-80">
|
||||
<DialogHeader title="Import Encounter" onClose={handleClose} />
|
||||
{mode === "pick" && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-3 rounded-lg border border-border px-4 py-3 text-left text-foreground text-sm hover:bg-hover-neutral-bg"
|
||||
onClick={() => {
|
||||
handleClose();
|
||||
onSelectFile();
|
||||
}}
|
||||
>
|
||||
<FileUp className="h-5 w-5 text-muted-foreground" />
|
||||
<div>
|
||||
<div className="font-medium">From file</div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
Upload a JSON file
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center gap-3 rounded-lg border border-border px-4 py-3 text-left text-foreground text-sm hover:bg-hover-neutral-bg"
|
||||
onClick={() => setMode("paste")}
|
||||
>
|
||||
<ClipboardPaste className="h-5 w-5 text-muted-foreground" />
|
||||
<div>
|
||||
<div className="font-medium">Paste content</div>
|
||||
<div className="text-muted-foreground text-xs">
|
||||
Paste JSON content directly
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{mode === "paste" && (
|
||||
<div className="flex flex-col gap-3">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={pasteText}
|
||||
onChange={(e) => setPasteText(e.target.value)}
|
||||
placeholder="Paste exported JSON here..."
|
||||
className="h-32 w-full resize-none rounded-md border border-border bg-background px-3 py-2 font-mono text-foreground text-xs placeholder:text-muted-foreground focus:border-accent focus:outline-none"
|
||||
/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
setMode("pick");
|
||||
setPasteText("");
|
||||
}}
|
||||
>
|
||||
Back
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={pasteText.trim().length === 0}
|
||||
onClick={() => {
|
||||
const text = pasteText;
|
||||
handleClose();
|
||||
onSubmitClipboard(text);
|
||||
}}
|
||||
>
|
||||
Import
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -35,7 +35,7 @@ export const PlayerCharacterSection = function PlayerCharacterSectionInner({
|
||||
setEditingPlayer(undefined);
|
||||
setManagementOpen(true);
|
||||
}}
|
||||
onSave={(name, ac, maxHp, color, icon) => {
|
||||
onSave={(name, ac, maxHp, color, icon, level) => {
|
||||
if (editingPlayer) {
|
||||
editCharacter(editingPlayer.id, {
|
||||
name,
|
||||
@@ -43,9 +43,10 @@ export const PlayerCharacterSection = function PlayerCharacterSectionInner({
|
||||
maxHp,
|
||||
color: color ?? null,
|
||||
icon: icon ?? null,
|
||||
level: level ?? null,
|
||||
});
|
||||
} else {
|
||||
createCharacter(name, ac, maxHp, color, icon);
|
||||
createCharacter(name, ac, maxHp, color, icon, level);
|
||||
}
|
||||
}}
|
||||
playerCharacter={editingPlayer}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { PlayerCharacter, PlayerCharacterId } from "@initiative/domain";
|
||||
import { Pencil, Plus, Trash2, X } from "lucide-react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { Pencil, Plus, Trash2 } from "lucide-react";
|
||||
import { PLAYER_COLOR_HEX, PLAYER_ICON_MAP } from "./player-icon-map";
|
||||
import { Button } from "./ui/button";
|
||||
import { ConfirmButton } from "./ui/confirm-button";
|
||||
import { Dialog, DialogHeader } from "./ui/dialog";
|
||||
|
||||
interface PlayerManagementProps {
|
||||
open: boolean;
|
||||
@@ -22,54 +22,9 @@ export function PlayerManagement({
|
||||
onDelete,
|
||||
onCreate,
|
||||
}: Readonly<PlayerManagementProps>) {
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
if (!dialog) return;
|
||||
if (open && !dialog.open) {
|
||||
dialog.showModal();
|
||||
} else if (!open && dialog.open) {
|
||||
dialog.close();
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
if (!dialog) return;
|
||||
function handleCancel(e: Event) {
|
||||
e.preventDefault();
|
||||
onClose();
|
||||
}
|
||||
function handleBackdropClick(e: MouseEvent) {
|
||||
if (e.target === dialog) onClose();
|
||||
}
|
||||
dialog.addEventListener("cancel", handleCancel);
|
||||
dialog.addEventListener("mousedown", handleBackdropClick);
|
||||
return () => {
|
||||
dialog.removeEventListener("cancel", handleCancel);
|
||||
dialog.removeEventListener("mousedown", handleBackdropClick);
|
||||
};
|
||||
}, [onClose]);
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={dialogRef}
|
||||
className="card-glow m-auto w-full max-w-md rounded-lg border border-border bg-card p-6 backdrop:bg-black/50"
|
||||
>
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h2 className="font-semibold text-foreground text-lg">
|
||||
Player Characters
|
||||
</h2>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onClose}
|
||||
className="text-muted-foreground"
|
||||
>
|
||||
<X size={20} />
|
||||
</Button>
|
||||
</div>
|
||||
<Dialog open={open} onClose={onClose} className="card-glow w-full max-w-md">
|
||||
<DialogHeader title="Player Characters" onClose={onClose} />
|
||||
|
||||
{characters.length === 0 ? (
|
||||
<div className="flex flex-col items-center gap-3 py-8 text-center">
|
||||
@@ -101,6 +56,11 @@ export function PlayerManagement({
|
||||
<span className="text-muted-foreground text-xs tabular-nums">
|
||||
HP {pc.maxHp}
|
||||
</span>
|
||||
{pc.level !== undefined && (
|
||||
<span className="text-muted-foreground text-xs tabular-nums">
|
||||
Lv {pc.level}
|
||||
</span>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
@@ -128,6 +88,6 @@ export function PlayerManagement({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</dialog>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { RollMode } from "@initiative/domain";
|
||||
import { ChevronsDown, ChevronsUp } from "lucide-react";
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import { useLayoutEffect, useRef, useState } from "react";
|
||||
import { useClickOutside } from "../hooks/use-click-outside.js";
|
||||
|
||||
interface RollModeMenuProps {
|
||||
readonly position: { x: number; y: number };
|
||||
@@ -34,22 +35,7 @@ export function RollModeMenu({
|
||||
setPos({ top, left });
|
||||
}, [position.x, position.y]);
|
||||
|
||||
useEffect(() => {
|
||||
function handleMouseDown(e: MouseEvent) {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") onClose();
|
||||
}
|
||||
document.addEventListener("mousedown", handleMouseDown);
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", handleMouseDown);
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, [onClose]);
|
||||
useClickOutside(ref, onClose);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import type { RulesEdition } from "@initiative/domain";
|
||||
import { Monitor, Moon, Sun, X } from "lucide-react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { Monitor, Moon, Sun } from "lucide-react";
|
||||
import { useRulesEditionContext } from "../contexts/rules-edition-context.js";
|
||||
import { useThemeContext } from "../contexts/theme-context.js";
|
||||
import { cn } from "../lib/utils.js";
|
||||
import { Button } from "./ui/button.js";
|
||||
import { Dialog, DialogHeader } from "./ui/dialog.js";
|
||||
|
||||
interface SettingsModalProps {
|
||||
open: boolean;
|
||||
@@ -27,51 +26,12 @@ const THEME_OPTIONS: {
|
||||
];
|
||||
|
||||
export function SettingsModal({ open, onClose }: Readonly<SettingsModalProps>) {
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const { edition, setEdition } = useRulesEditionContext();
|
||||
const { preference, setPreference } = useThemeContext();
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
if (!dialog) return;
|
||||
if (open && !dialog.open) dialog.showModal();
|
||||
else if (!open && dialog.open) dialog.close();
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
if (!dialog) return;
|
||||
function handleCancel(e: Event) {
|
||||
e.preventDefault();
|
||||
onClose();
|
||||
}
|
||||
function handleBackdropClick(e: MouseEvent) {
|
||||
if (e.target === dialog) onClose();
|
||||
}
|
||||
dialog.addEventListener("cancel", handleCancel);
|
||||
dialog.addEventListener("mousedown", handleBackdropClick);
|
||||
return () => {
|
||||
dialog.removeEventListener("cancel", handleCancel);
|
||||
dialog.removeEventListener("mousedown", handleBackdropClick);
|
||||
};
|
||||
}, [onClose]);
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={dialogRef}
|
||||
className="card-glow m-auto w-full max-w-sm rounded-lg border border-border bg-card p-6 backdrop:bg-black/50"
|
||||
>
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h2 className="font-semibold text-foreground text-lg">Settings</h2>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onClose}
|
||||
className="text-muted-foreground"
|
||||
>
|
||||
<X size={20} />
|
||||
</Button>
|
||||
</div>
|
||||
<Dialog open={open} onClose={onClose} className="card-glow w-full max-w-sm">
|
||||
<DialogHeader title="Settings" onClose={onClose} />
|
||||
|
||||
<div className="flex flex-col gap-5">
|
||||
<div>
|
||||
@@ -124,6 +84,6 @@ export function SettingsModal({ open, onClose }: Readonly<SettingsModalProps>) {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</dialog>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -34,6 +34,31 @@ function SectionDivider() {
|
||||
);
|
||||
}
|
||||
|
||||
function TraitSection({
|
||||
entries,
|
||||
heading,
|
||||
}: Readonly<{
|
||||
entries: readonly { name: string; text: string }[] | undefined;
|
||||
heading?: string;
|
||||
}>) {
|
||||
if (!entries || entries.length === 0) return null;
|
||||
return (
|
||||
<>
|
||||
<SectionDivider />
|
||||
{heading ? (
|
||||
<h3 className="font-bold text-base text-stat-heading">{heading}</h3>
|
||||
) : null}
|
||||
<div className="space-y-2">
|
||||
{entries.map((e) => (
|
||||
<div key={e.name} className="text-sm">
|
||||
<span className="font-semibold italic">{e.name}.</span> {e.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatBlock({ creature }: Readonly<StatBlockProps>) {
|
||||
const abilities = [
|
||||
{ label: "STR", score: creature.abilities.str },
|
||||
@@ -134,19 +159,7 @@ export function StatBlock({ creature }: Readonly<StatBlockProps>) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Traits */}
|
||||
{creature.traits && creature.traits.length > 0 && (
|
||||
<>
|
||||
<SectionDivider />
|
||||
<div className="space-y-2">
|
||||
{creature.traits.map((t) => (
|
||||
<div key={t.name} className="text-sm">
|
||||
<span className="font-semibold italic">{t.name}.</span> {t.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<TraitSection entries={creature.traits} />
|
||||
|
||||
{/* Spellcasting */}
|
||||
{creature.spellcasting && creature.spellcasting.length > 0 && (
|
||||
@@ -190,52 +203,9 @@ export function StatBlock({ creature }: Readonly<StatBlockProps>) {
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
{creature.actions && creature.actions.length > 0 && (
|
||||
<>
|
||||
<SectionDivider />
|
||||
<h3 className="font-bold text-base text-stat-heading">Actions</h3>
|
||||
<div className="space-y-2">
|
||||
{creature.actions.map((a) => (
|
||||
<div key={a.name} className="text-sm">
|
||||
<span className="font-semibold italic">{a.name}.</span> {a.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Bonus Actions */}
|
||||
{creature.bonusActions && creature.bonusActions.length > 0 && (
|
||||
<>
|
||||
<SectionDivider />
|
||||
<h3 className="font-bold text-base text-stat-heading">
|
||||
Bonus Actions
|
||||
</h3>
|
||||
<div className="space-y-2">
|
||||
{creature.bonusActions.map((a) => (
|
||||
<div key={a.name} className="text-sm">
|
||||
<span className="font-semibold italic">{a.name}.</span> {a.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Reactions */}
|
||||
{creature.reactions && creature.reactions.length > 0 && (
|
||||
<>
|
||||
<SectionDivider />
|
||||
<h3 className="font-bold text-base text-stat-heading">Reactions</h3>
|
||||
<div className="space-y-2">
|
||||
{creature.reactions.map((a) => (
|
||||
<div key={a.name} className="text-sm">
|
||||
<span className="font-semibold italic">{a.name}.</span> {a.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<TraitSection entries={creature.actions} heading="Actions" />
|
||||
<TraitSection entries={creature.bonusActions} heading="Bonus Actions" />
|
||||
<TraitSection entries={creature.reactions} heading="Reactions" />
|
||||
|
||||
{/* Legendary Actions */}
|
||||
{!!creature.legendaryActions && (
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Redo2, StepBack, StepForward, Trash2, Undo2 } from "lucide-react";
|
||||
import { useEncounterContext } from "../contexts/encounter-context.js";
|
||||
import { useDifficulty } from "../hooks/use-difficulty.js";
|
||||
import { DifficultyIndicator } from "./difficulty-indicator.js";
|
||||
import { Button } from "./ui/button.js";
|
||||
import { ConfirmButton } from "./ui/confirm-button.js";
|
||||
|
||||
@@ -15,6 +17,7 @@ export function TurnNavigation() {
|
||||
canRedo,
|
||||
} = useEncounterContext();
|
||||
|
||||
const difficulty = useDifficulty();
|
||||
const hasCombatants = encounter.combatants.length > 0;
|
||||
const isAtStart = encounter.roundNumber === 1 && encounter.activeIndex === 0;
|
||||
const activeCombatant = encounter.combatants[encounter.activeIndex];
|
||||
@@ -66,6 +69,7 @@ export function TurnNavigation() {
|
||||
) : (
|
||||
<span className="text-muted-foreground">No combatants</span>
|
||||
)}
|
||||
{difficulty && <DifficultyIndicator result={difficulty} />}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-shrink-0 items-center gap-3">
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useClickOutside } from "../../hooks/use-click-outside.js";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { Button } from "./button";
|
||||
|
||||
@@ -42,32 +43,7 @@ export function ConfirmButton({
|
||||
return () => clearTimeout(timerRef.current);
|
||||
}, []);
|
||||
|
||||
// Click-outside listener when confirming
|
||||
useEffect(() => {
|
||||
if (!isConfirming) return;
|
||||
|
||||
function handleMouseDown(e: MouseEvent) {
|
||||
if (
|
||||
wrapperRef.current &&
|
||||
!wrapperRef.current.contains(e.target as Node)
|
||||
) {
|
||||
revert();
|
||||
}
|
||||
}
|
||||
|
||||
function handleEscapeKey(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") {
|
||||
revert();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("mousedown", handleMouseDown);
|
||||
document.addEventListener("keydown", handleEscapeKey);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", handleMouseDown);
|
||||
document.removeEventListener("keydown", handleEscapeKey);
|
||||
};
|
||||
}, [isConfirming, revert]);
|
||||
useClickOutside(wrapperRef, revert, isConfirming);
|
||||
|
||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { X } from "lucide-react";
|
||||
import { type ReactNode, useEffect, useRef } from "react";
|
||||
import { cn } from "../../lib/utils.js";
|
||||
import { Button } from "./button.js";
|
||||
|
||||
interface DialogProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function Dialog({ open, onClose, className, children }: DialogProps) {
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
if (!dialog) return;
|
||||
if (open && !dialog.open) dialog.showModal();
|
||||
else if (!open && dialog.open) dialog.close();
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
const dialog = dialogRef.current;
|
||||
if (!dialog) return;
|
||||
function handleCancel(e: Event) {
|
||||
e.preventDefault();
|
||||
onClose();
|
||||
}
|
||||
function handleBackdropClick(e: MouseEvent) {
|
||||
if (e.target === dialog) onClose();
|
||||
}
|
||||
dialog.addEventListener("cancel", handleCancel);
|
||||
dialog.addEventListener("mousedown", handleBackdropClick);
|
||||
return () => {
|
||||
dialog.removeEventListener("cancel", handleCancel);
|
||||
dialog.removeEventListener("mousedown", handleBackdropClick);
|
||||
};
|
||||
}, [onClose]);
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={dialogRef}
|
||||
className={cn(
|
||||
"m-auto rounded-lg border border-border bg-card text-foreground shadow-xl backdrop:bg-black/50",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="p-6">{children}</div>
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function DialogHeader({
|
||||
title,
|
||||
onClose,
|
||||
}: Readonly<{ title: string; onClose: () => void }>) {
|
||||
return (
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h2 className="font-semibold text-foreground text-lg">{title}</h2>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onClose}
|
||||
className="text-muted-foreground"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { EllipsisVertical } from "lucide-react";
|
||||
import { type ReactNode, useEffect, useRef, useState } from "react";
|
||||
import { type ReactNode, useRef, useState } from "react";
|
||||
import { useClickOutside } from "../../hooks/use-click-outside.js";
|
||||
import { Button } from "./button";
|
||||
|
||||
export interface OverflowMenuItem {
|
||||
@@ -18,23 +19,7 @@ export function OverflowMenu({ items }: OverflowMenuProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function handleMouseDown(e: MouseEvent) {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) {
|
||||
setOpen(false);
|
||||
}
|
||||
}
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") setOpen(false);
|
||||
}
|
||||
document.addEventListener("mousedown", handleMouseDown);
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", handleMouseDown);
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, [open]);
|
||||
useClickOutside(ref, () => setOpen(false), open);
|
||||
|
||||
return (
|
||||
<div ref={ref} className="relative">
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
// @vitest-environment jsdom
|
||||
import type {
|
||||
Combatant,
|
||||
CreatureId,
|
||||
Encounter,
|
||||
PlayerCharacter,
|
||||
} from "@initiative/domain";
|
||||
import { combatantId, creatureId, playerCharacterId } from "@initiative/domain";
|
||||
import { renderHook } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../contexts/encounter-context.js", () => ({
|
||||
useEncounterContext: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../contexts/player-characters-context.js", () => ({
|
||||
usePlayerCharactersContext: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../contexts/bestiary-context.js", () => ({
|
||||
useBestiaryContext: vi.fn(),
|
||||
}));
|
||||
|
||||
import { useBestiaryContext } from "../../contexts/bestiary-context.js";
|
||||
import { useEncounterContext } from "../../contexts/encounter-context.js";
|
||||
import { usePlayerCharactersContext } from "../../contexts/player-characters-context.js";
|
||||
import { useDifficulty } from "../use-difficulty.js";
|
||||
|
||||
const mockEncounterContext = vi.mocked(useEncounterContext);
|
||||
const mockPlayerCharactersContext = vi.mocked(usePlayerCharactersContext);
|
||||
const mockBestiaryContext = vi.mocked(useBestiaryContext);
|
||||
|
||||
const pcId1 = playerCharacterId("pc-1");
|
||||
const pcId2 = playerCharacterId("pc-2");
|
||||
const crId1 = creatureId("creature-1");
|
||||
const _crId2 = creatureId("creature-2");
|
||||
|
||||
function setup(options: {
|
||||
combatants: Combatant[];
|
||||
characters: PlayerCharacter[];
|
||||
creatures: Map<CreatureId, { cr: string }>;
|
||||
}) {
|
||||
const encounter = {
|
||||
combatants: options.combatants,
|
||||
activeIndex: 0,
|
||||
roundNumber: 1,
|
||||
} as Encounter;
|
||||
|
||||
mockEncounterContext.mockReturnValue({
|
||||
encounter,
|
||||
} as ReturnType<typeof useEncounterContext>);
|
||||
|
||||
mockPlayerCharactersContext.mockReturnValue({
|
||||
characters: options.characters,
|
||||
} as ReturnType<typeof usePlayerCharactersContext>);
|
||||
|
||||
mockBestiaryContext.mockReturnValue({
|
||||
getCreature: (id: CreatureId) => options.creatures.get(id),
|
||||
} as ReturnType<typeof useBestiaryContext>);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("useDifficulty", () => {
|
||||
it("returns difficulty result for leveled PCs and bestiary monsters", () => {
|
||||
setup({
|
||||
combatants: [
|
||||
{ id: combatantId("c1"), name: "Hero", playerCharacterId: pcId1 },
|
||||
{ id: combatantId("c2"), name: "Goblin", creatureId: crId1 },
|
||||
],
|
||||
characters: [{ id: pcId1, name: "Hero", ac: 15, maxHp: 30, level: 1 }],
|
||||
creatures: new Map([[crId1, { cr: "1/4" }]]),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDifficulty());
|
||||
|
||||
expect(result.current).not.toBeNull();
|
||||
expect(result.current?.tier).toBe("low");
|
||||
expect(result.current?.totalMonsterXp).toBe(50);
|
||||
});
|
||||
|
||||
describe("returns null when data is insufficient (ED-2)", () => {
|
||||
it("returns null when encounter has no combatants", () => {
|
||||
setup({ combatants: [], characters: [], creatures: new Map() });
|
||||
|
||||
const { result } = renderHook(() => useDifficulty());
|
||||
expect(result.current).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when only custom combatants (no creatureId)", () => {
|
||||
setup({
|
||||
combatants: [
|
||||
{
|
||||
id: combatantId("c1"),
|
||||
name: "Custom",
|
||||
playerCharacterId: pcId1,
|
||||
},
|
||||
],
|
||||
characters: [{ id: pcId1, name: "Hero", ac: 15, maxHp: 30, level: 5 }],
|
||||
creatures: new Map(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDifficulty());
|
||||
expect(result.current).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when bestiary monsters present but no PC combatants", () => {
|
||||
setup({
|
||||
combatants: [
|
||||
{ id: combatantId("c1"), name: "Goblin", creatureId: crId1 },
|
||||
],
|
||||
characters: [],
|
||||
creatures: new Map([[crId1, { cr: "1" }]]),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDifficulty());
|
||||
expect(result.current).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when PC combatants have no level", () => {
|
||||
setup({
|
||||
combatants: [
|
||||
{
|
||||
id: combatantId("c1"),
|
||||
name: "Hero",
|
||||
playerCharacterId: pcId1,
|
||||
},
|
||||
{ id: combatantId("c2"), name: "Goblin", creatureId: crId1 },
|
||||
],
|
||||
characters: [{ id: pcId1, name: "Hero", ac: 15, maxHp: 30 }],
|
||||
creatures: new Map([[crId1, { cr: "1" }]]),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDifficulty());
|
||||
expect(result.current).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when PC combatant references unknown player character", () => {
|
||||
setup({
|
||||
combatants: [
|
||||
{
|
||||
id: combatantId("c1"),
|
||||
name: "Hero",
|
||||
playerCharacterId: pcId2,
|
||||
},
|
||||
{ id: combatantId("c2"), name: "Goblin", creatureId: crId1 },
|
||||
],
|
||||
characters: [{ id: pcId1, name: "Other", ac: 15, maxHp: 30, level: 5 }],
|
||||
creatures: new Map([[crId1, { cr: "1" }]]),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDifficulty());
|
||||
expect(result.current).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("handles mixed combatants: only leveled PCs and bestiary monsters contribute", () => {
|
||||
// Party: one leveled PC, one without level (excluded)
|
||||
// Monsters: one bestiary creature, one custom (excluded)
|
||||
setup({
|
||||
combatants: [
|
||||
{
|
||||
id: combatantId("c1"),
|
||||
name: "Leveled",
|
||||
playerCharacterId: pcId1,
|
||||
},
|
||||
{
|
||||
id: combatantId("c2"),
|
||||
name: "No Level",
|
||||
playerCharacterId: pcId2,
|
||||
},
|
||||
{ id: combatantId("c3"), name: "Goblin", creatureId: crId1 },
|
||||
{ id: combatantId("c4"), name: "Custom Monster" },
|
||||
],
|
||||
characters: [
|
||||
{ id: pcId1, name: "Leveled", ac: 15, maxHp: 30, level: 1 },
|
||||
{ id: pcId2, name: "No Level", ac: 12, maxHp: 20 },
|
||||
],
|
||||
creatures: new Map([[crId1, { cr: "1" }]]),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDifficulty());
|
||||
|
||||
expect(result.current).not.toBeNull();
|
||||
// 1 level-1 PC: budget low=50, mod=75, high=100
|
||||
// 1 CR 1 monster: 200 XP → high (200 >= 100)
|
||||
expect(result.current?.tier).toBe("high");
|
||||
expect(result.current?.totalMonsterXp).toBe(200);
|
||||
expect(result.current?.partyBudget.low).toBe(50);
|
||||
});
|
||||
|
||||
it("includes duplicate PC combatants in budget", () => {
|
||||
// Same PC added twice → counts twice
|
||||
setup({
|
||||
combatants: [
|
||||
{
|
||||
id: combatantId("c1"),
|
||||
name: "Hero 1",
|
||||
playerCharacterId: pcId1,
|
||||
},
|
||||
{
|
||||
id: combatantId("c2"),
|
||||
name: "Hero 2",
|
||||
playerCharacterId: pcId1,
|
||||
},
|
||||
{ id: combatantId("c3"), name: "Goblin", creatureId: crId1 },
|
||||
],
|
||||
characters: [{ id: pcId1, name: "Hero", ac: 15, maxHp: 30, level: 1 }],
|
||||
creatures: new Map([[crId1, { cr: "1/4" }]]),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDifficulty());
|
||||
|
||||
expect(result.current).not.toBeNull();
|
||||
// 2x level 1: budget low=100
|
||||
expect(result.current?.partyBudget.low).toBe(100);
|
||||
});
|
||||
});
|
||||
@@ -42,7 +42,14 @@ describe("usePlayerCharacters", () => {
|
||||
const { result } = renderHook(() => usePlayerCharacters());
|
||||
|
||||
act(() => {
|
||||
result.current.createCharacter("Vex", 15, 28, undefined, undefined);
|
||||
result.current.createCharacter(
|
||||
"Vex",
|
||||
15,
|
||||
28,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
expect(result.current.characters).toHaveLength(1);
|
||||
@@ -57,7 +64,14 @@ describe("usePlayerCharacters", () => {
|
||||
|
||||
let error: unknown;
|
||||
act(() => {
|
||||
error = result.current.createCharacter("", 15, 28, undefined, undefined);
|
||||
error = result.current.createCharacter(
|
||||
"",
|
||||
15,
|
||||
28,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
expect(error).toMatchObject({ kind: "domain-error" });
|
||||
@@ -68,7 +82,14 @@ describe("usePlayerCharacters", () => {
|
||||
const { result } = renderHook(() => usePlayerCharacters());
|
||||
|
||||
act(() => {
|
||||
result.current.createCharacter("Vex", 15, 28, undefined, undefined);
|
||||
result.current.createCharacter(
|
||||
"Vex",
|
||||
15,
|
||||
28,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
const id = result.current.characters[0].id;
|
||||
@@ -85,7 +106,14 @@ describe("usePlayerCharacters", () => {
|
||||
const { result } = renderHook(() => usePlayerCharacters());
|
||||
|
||||
act(() => {
|
||||
result.current.createCharacter("Vex", 15, 28, undefined, undefined);
|
||||
result.current.createCharacter(
|
||||
"Vex",
|
||||
15,
|
||||
28,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
const id = result.current.characters[0].id;
|
||||
|
||||
@@ -26,8 +26,12 @@ export function creatureKey(r: SearchResult): string {
|
||||
}
|
||||
|
||||
export function useActionBarState() {
|
||||
const { addCombatant, addFromBestiary, addFromPlayerCharacter } =
|
||||
useEncounterContext();
|
||||
const {
|
||||
addCombatant,
|
||||
addFromBestiary,
|
||||
addMultipleFromBestiary,
|
||||
addFromPlayerCharacter,
|
||||
} = useEncounterContext();
|
||||
const { search: bestiarySearch, isLoaded: bestiaryLoaded } =
|
||||
useBestiaryContext();
|
||||
const { characters: playerCharacters } = usePlayerCharactersContext();
|
||||
@@ -92,11 +96,24 @@ export function useActionBarState() {
|
||||
|
||||
const confirmQueued = useCallback(() => {
|
||||
if (!queued) return;
|
||||
for (let i = 0; i < queued.count; i++) {
|
||||
if (queued.count === 1) {
|
||||
handleAddFromBestiary(queued.result);
|
||||
} else {
|
||||
const creatureId = addMultipleFromBestiary(queued.result, queued.count);
|
||||
const isDesktop = globalThis.matchMedia("(min-width: 1024px)").matches;
|
||||
if (creatureId && panelView.mode === "closed" && isDesktop) {
|
||||
showCreature(creatureId);
|
||||
}
|
||||
}
|
||||
clearInput();
|
||||
}, [queued, handleAddFromBestiary, clearInput]);
|
||||
}, [
|
||||
queued,
|
||||
handleAddFromBestiary,
|
||||
addMultipleFromBestiary,
|
||||
panelView.mode,
|
||||
showCreature,
|
||||
clearInput,
|
||||
]);
|
||||
|
||||
const parseNum = (v: string): number | undefined => {
|
||||
if (v.trim() === "") return undefined;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { RefObject } from "react";
|
||||
import { useEffect } from "react";
|
||||
|
||||
export function useClickOutside(
|
||||
ref: RefObject<HTMLElement | null>,
|
||||
onClose: () => void,
|
||||
active = true,
|
||||
): void {
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
|
||||
function handleMouseDown(e: MouseEvent) {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") onClose();
|
||||
}
|
||||
document.addEventListener("mousedown", handleMouseDown);
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", handleMouseDown);
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, [ref, onClose, active]);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type {
|
||||
Combatant,
|
||||
CreatureId,
|
||||
DifficultyResult,
|
||||
PlayerCharacter,
|
||||
} from "@initiative/domain";
|
||||
import { calculateEncounterDifficulty } from "@initiative/domain";
|
||||
import { useMemo } from "react";
|
||||
import { useBestiaryContext } from "../contexts/bestiary-context.js";
|
||||
import { useEncounterContext } from "../contexts/encounter-context.js";
|
||||
import { usePlayerCharactersContext } from "../contexts/player-characters-context.js";
|
||||
|
||||
function derivePartyLevels(
|
||||
combatants: readonly Combatant[],
|
||||
characters: readonly PlayerCharacter[],
|
||||
): number[] {
|
||||
const levels: number[] = [];
|
||||
for (const c of combatants) {
|
||||
if (!c.playerCharacterId) continue;
|
||||
const pc = characters.find((p) => p.id === c.playerCharacterId);
|
||||
if (pc?.level !== undefined) levels.push(pc.level);
|
||||
}
|
||||
return levels;
|
||||
}
|
||||
|
||||
function deriveMonsterCrs(
|
||||
combatants: readonly Combatant[],
|
||||
getCreature: (id: CreatureId) => { cr: string } | undefined,
|
||||
): string[] {
|
||||
const crs: string[] = [];
|
||||
for (const c of combatants) {
|
||||
if (!c.creatureId) continue;
|
||||
const creature = getCreature(c.creatureId);
|
||||
if (creature) crs.push(creature.cr);
|
||||
}
|
||||
return crs;
|
||||
}
|
||||
|
||||
export function useDifficulty(): DifficultyResult | null {
|
||||
const { encounter } = useEncounterContext();
|
||||
const { characters } = usePlayerCharactersContext();
|
||||
const { getCreature } = useBestiaryContext();
|
||||
|
||||
return useMemo(() => {
|
||||
const partyLevels = derivePartyLevels(encounter.combatants, characters);
|
||||
const monsterCrs = deriveMonsterCrs(encounter.combatants, getCreature);
|
||||
|
||||
if (partyLevels.length === 0 || monsterCrs.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return calculateEncounterDifficulty(partyLevels, monsterCrs);
|
||||
}, [encounter.combatants, characters, getCreature]);
|
||||
}
|
||||
+115
-150
@@ -22,6 +22,7 @@ import type {
|
||||
CombatantInit,
|
||||
ConditionId,
|
||||
CreatureId,
|
||||
DomainError,
|
||||
DomainEvent,
|
||||
Encounter,
|
||||
PlayerCharacter,
|
||||
@@ -120,167 +121,90 @@ export function useEncounter() {
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
const advanceTurn = useCallback(() => {
|
||||
const result = withUndo(() => advanceTurnUseCase(makeStore()));
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
}, [makeStore, withUndo]);
|
||||
|
||||
const retreatTurn = useCallback(() => {
|
||||
const result = withUndo(() => retreatTurnUseCase(makeStore()));
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
}, [makeStore, withUndo]);
|
||||
const dispatchAction = useCallback(
|
||||
(action: () => DomainEvent[] | DomainError) => {
|
||||
const result = withUndo(action);
|
||||
if (!isDomainError(result)) {
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
}
|
||||
},
|
||||
[withUndo],
|
||||
);
|
||||
|
||||
const nextId = useRef(deriveNextId(encounter));
|
||||
|
||||
const advanceTurn = useCallback(
|
||||
() => dispatchAction(() => advanceTurnUseCase(makeStore())),
|
||||
[makeStore, dispatchAction],
|
||||
);
|
||||
|
||||
const retreatTurn = useCallback(
|
||||
() => dispatchAction(() => retreatTurnUseCase(makeStore())),
|
||||
[makeStore, dispatchAction],
|
||||
);
|
||||
|
||||
const addCombatant = useCallback(
|
||||
(name: string, init?: CombatantInit) => {
|
||||
const id = combatantId(`c-${++nextId.current}`);
|
||||
const result = withUndo(() =>
|
||||
addCombatantUseCase(makeStore(), id, name, init),
|
||||
);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
dispatchAction(() => addCombatantUseCase(makeStore(), id, name, init));
|
||||
},
|
||||
[makeStore, withUndo],
|
||||
[makeStore, dispatchAction],
|
||||
);
|
||||
|
||||
const removeCombatant = useCallback(
|
||||
(id: CombatantId) => {
|
||||
const result = withUndo(() => removeCombatantUseCase(makeStore(), id));
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
},
|
||||
[makeStore, withUndo],
|
||||
(id: CombatantId) =>
|
||||
dispatchAction(() => removeCombatantUseCase(makeStore(), id)),
|
||||
[makeStore, dispatchAction],
|
||||
);
|
||||
|
||||
const editCombatant = useCallback(
|
||||
(id: CombatantId, newName: string) => {
|
||||
const result = withUndo(() =>
|
||||
editCombatantUseCase(makeStore(), id, newName),
|
||||
);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
},
|
||||
[makeStore, withUndo],
|
||||
(id: CombatantId, newName: string) =>
|
||||
dispatchAction(() => editCombatantUseCase(makeStore(), id, newName)),
|
||||
[makeStore, dispatchAction],
|
||||
);
|
||||
|
||||
const setInitiative = useCallback(
|
||||
(id: CombatantId, value: number | undefined) => {
|
||||
const result = withUndo(() =>
|
||||
setInitiativeUseCase(makeStore(), id, value),
|
||||
);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
},
|
||||
[makeStore, withUndo],
|
||||
(id: CombatantId, value: number | undefined) =>
|
||||
dispatchAction(() => setInitiativeUseCase(makeStore(), id, value)),
|
||||
[makeStore, dispatchAction],
|
||||
);
|
||||
|
||||
const setHp = useCallback(
|
||||
(id: CombatantId, maxHp: number | undefined) => {
|
||||
const result = withUndo(() => setHpUseCase(makeStore(), id, maxHp));
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
},
|
||||
[makeStore, withUndo],
|
||||
(id: CombatantId, maxHp: number | undefined) =>
|
||||
dispatchAction(() => setHpUseCase(makeStore(), id, maxHp)),
|
||||
[makeStore, dispatchAction],
|
||||
);
|
||||
|
||||
const adjustHp = useCallback(
|
||||
(id: CombatantId, delta: number) => {
|
||||
const result = withUndo(() => adjustHpUseCase(makeStore(), id, delta));
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
},
|
||||
[makeStore, withUndo],
|
||||
(id: CombatantId, delta: number) =>
|
||||
dispatchAction(() => adjustHpUseCase(makeStore(), id, delta)),
|
||||
[makeStore, dispatchAction],
|
||||
);
|
||||
|
||||
const setTempHp = useCallback(
|
||||
(id: CombatantId, tempHp: number | undefined) => {
|
||||
const result = withUndo(() => setTempHpUseCase(makeStore(), id, tempHp));
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
},
|
||||
[makeStore, withUndo],
|
||||
(id: CombatantId, tempHp: number | undefined) =>
|
||||
dispatchAction(() => setTempHpUseCase(makeStore(), id, tempHp)),
|
||||
[makeStore, dispatchAction],
|
||||
);
|
||||
|
||||
const setAc = useCallback(
|
||||
(id: CombatantId, value: number | undefined) => {
|
||||
const result = withUndo(() => setAcUseCase(makeStore(), id, value));
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
},
|
||||
[makeStore, withUndo],
|
||||
(id: CombatantId, value: number | undefined) =>
|
||||
dispatchAction(() => setAcUseCase(makeStore(), id, value)),
|
||||
[makeStore, dispatchAction],
|
||||
);
|
||||
|
||||
const toggleCondition = useCallback(
|
||||
(id: CombatantId, conditionId: ConditionId) => {
|
||||
const result = withUndo(() =>
|
||||
(id: CombatantId, conditionId: ConditionId) =>
|
||||
dispatchAction(() =>
|
||||
toggleConditionUseCase(makeStore(), id, conditionId),
|
||||
);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
},
|
||||
[makeStore, withUndo],
|
||||
),
|
||||
[makeStore, dispatchAction],
|
||||
);
|
||||
|
||||
const toggleConcentration = useCallback(
|
||||
(id: CombatantId) => {
|
||||
const result = withUndo(() =>
|
||||
toggleConcentrationUseCase(makeStore(), id),
|
||||
);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
},
|
||||
[makeStore, withUndo],
|
||||
(id: CombatantId) =>
|
||||
dispatchAction(() => toggleConcentrationUseCase(makeStore(), id)),
|
||||
[makeStore, dispatchAction],
|
||||
);
|
||||
|
||||
const clearEncounter = useCallback(() => {
|
||||
@@ -298,15 +222,11 @@ export function useEncounter() {
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
}, [makeStore]);
|
||||
|
||||
const addFromBestiary = useCallback(
|
||||
(entry: BestiaryIndexEntry): CreatureId | null => {
|
||||
const snapshot = encounterRef.current;
|
||||
const resolveAndRename = useCallback(
|
||||
(name: string): string => {
|
||||
const store = makeStore();
|
||||
const existingNames = store.get().combatants.map((c) => c.name);
|
||||
const { newName, renames } = resolveCreatureName(
|
||||
entry.name,
|
||||
existingNames,
|
||||
);
|
||||
const { newName, renames } = resolveCreatureName(name, existingNames);
|
||||
|
||||
for (const { from, to } of renames) {
|
||||
const target = store.get().combatants.find((c) => c.name === from);
|
||||
@@ -315,6 +235,17 @@ export function useEncounter() {
|
||||
}
|
||||
}
|
||||
|
||||
return newName;
|
||||
},
|
||||
[makeStore],
|
||||
);
|
||||
|
||||
const addOneFromBestiary = useCallback(
|
||||
(
|
||||
entry: BestiaryIndexEntry,
|
||||
): { cId: CreatureId; events: DomainEvent[] } | null => {
|
||||
const newName = resolveAndRename(entry.name);
|
||||
|
||||
const slug = entry.name
|
||||
.toLowerCase()
|
||||
.replaceAll(/[^a-z0-9]+/g, "-")
|
||||
@@ -328,8 +259,20 @@ export function useEncounter() {
|
||||
creatureId: cId,
|
||||
});
|
||||
|
||||
if (isDomainError(result)) {
|
||||
store.save(snapshot);
|
||||
if (isDomainError(result)) return null;
|
||||
|
||||
return { cId, events: result };
|
||||
},
|
||||
[makeStore, resolveAndRename],
|
||||
);
|
||||
|
||||
const addFromBestiary = useCallback(
|
||||
(entry: BestiaryIndexEntry): CreatureId | null => {
|
||||
const snapshot = encounterRef.current;
|
||||
const added = addOneFromBestiary(entry);
|
||||
|
||||
if (!added) {
|
||||
makeStore().save(snapshot);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -337,25 +280,42 @@ export function useEncounter() {
|
||||
undoRedoRef.current = newState;
|
||||
setUndoRedoState(newState);
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
return cId;
|
||||
setEvents((prev) => [...prev, ...added.events]);
|
||||
return added.cId;
|
||||
},
|
||||
[makeStore],
|
||||
[makeStore, addOneFromBestiary],
|
||||
);
|
||||
|
||||
const addMultipleFromBestiary = useCallback(
|
||||
(entry: BestiaryIndexEntry, count: number): CreatureId | null => {
|
||||
const snapshot = encounterRef.current;
|
||||
const allEvents: DomainEvent[] = [];
|
||||
let lastCId: CreatureId | null = null;
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const added = addOneFromBestiary(entry);
|
||||
if (!added) {
|
||||
makeStore().save(snapshot);
|
||||
return null;
|
||||
}
|
||||
allEvents.push(...added.events);
|
||||
lastCId = added.cId;
|
||||
}
|
||||
|
||||
const newState = pushUndo(undoRedoRef.current, snapshot);
|
||||
undoRedoRef.current = newState;
|
||||
setUndoRedoState(newState);
|
||||
|
||||
setEvents((prev) => [...prev, ...allEvents]);
|
||||
return lastCId;
|
||||
},
|
||||
[makeStore, addOneFromBestiary],
|
||||
);
|
||||
|
||||
const addFromPlayerCharacter = useCallback(
|
||||
(pc: PlayerCharacter) => {
|
||||
const snapshot = encounterRef.current;
|
||||
const store = makeStore();
|
||||
const existingNames = store.get().combatants.map((c) => c.name);
|
||||
const { newName, renames } = resolveCreatureName(pc.name, existingNames);
|
||||
|
||||
for (const { from, to } of renames) {
|
||||
const target = store.get().combatants.find((c) => c.name === from);
|
||||
if (target) {
|
||||
editCombatantUseCase(makeStore(), target.id, to);
|
||||
}
|
||||
}
|
||||
const newName = resolveAndRename(pc.name);
|
||||
|
||||
const id = combatantId(`c-${++nextId.current}`);
|
||||
const result = addCombatantUseCase(makeStore(), id, newName, {
|
||||
@@ -367,7 +327,7 @@ export function useEncounter() {
|
||||
});
|
||||
|
||||
if (isDomainError(result)) {
|
||||
store.save(snapshot);
|
||||
makeStore().save(snapshot);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -377,7 +337,7 @@ export function useEncounter() {
|
||||
|
||||
setEvents((prev) => [...prev, ...result]);
|
||||
},
|
||||
[makeStore],
|
||||
[makeStore, resolveAndRename],
|
||||
);
|
||||
|
||||
const undoAction = useCallback(() => {
|
||||
@@ -405,6 +365,7 @@ export function useEncounter() {
|
||||
|
||||
return {
|
||||
encounter,
|
||||
undoRedoState,
|
||||
events,
|
||||
isEmpty,
|
||||
hasTempHp,
|
||||
@@ -426,9 +387,13 @@ export function useEncounter() {
|
||||
toggleCondition,
|
||||
toggleConcentration,
|
||||
addFromBestiary,
|
||||
addMultipleFromBestiary,
|
||||
addFromPlayerCharacter,
|
||||
undo: undoAction,
|
||||
redo: redoAction,
|
||||
setEncounter,
|
||||
setUndoRedoState,
|
||||
makeStore,
|
||||
withUndo,
|
||||
} as const;
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ function rollDice(): number {
|
||||
}
|
||||
|
||||
export function useInitiativeRolls() {
|
||||
const { encounter, makeStore } = useEncounterContext();
|
||||
const { encounter, makeStore, withUndo } = useEncounterContext();
|
||||
const { getCreature } = useBestiaryContext();
|
||||
const { showCreature } = useSidePanelContext();
|
||||
|
||||
@@ -28,12 +28,8 @@ export function useInitiativeRolls() {
|
||||
(id: CombatantId, mode: RollMode = "normal") => {
|
||||
const diceRolls: [number, ...number[]] =
|
||||
mode === "normal" ? [rollDice()] : [rollDice(), rollDice()];
|
||||
const result = rollInitiativeUseCase(
|
||||
makeStore(),
|
||||
id,
|
||||
diceRolls,
|
||||
getCreature,
|
||||
mode,
|
||||
const result = withUndo(() =>
|
||||
rollInitiativeUseCase(makeStore(), id, diceRolls, getCreature, mode),
|
||||
);
|
||||
if (isDomainError(result)) {
|
||||
setRollSingleSkipped(true);
|
||||
@@ -43,22 +39,19 @@ export function useInitiativeRolls() {
|
||||
}
|
||||
}
|
||||
},
|
||||
[makeStore, getCreature, encounter.combatants, showCreature],
|
||||
[makeStore, getCreature, withUndo, encounter.combatants, showCreature],
|
||||
);
|
||||
|
||||
const handleRollAllInitiative = useCallback(
|
||||
(mode: RollMode = "normal") => {
|
||||
const result = rollAllInitiativeUseCase(
|
||||
makeStore(),
|
||||
rollDice,
|
||||
getCreature,
|
||||
mode,
|
||||
const result = withUndo(() =>
|
||||
rollAllInitiativeUseCase(makeStore(), rollDice, getCreature, mode),
|
||||
);
|
||||
if (!isDomainError(result) && result.skippedNoSource > 0) {
|
||||
setRollSkippedCount(result.skippedNoSource);
|
||||
}
|
||||
},
|
||||
[makeStore, getCreature],
|
||||
[makeStore, getCreature, withUndo],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -28,6 +28,7 @@ interface EditFields {
|
||||
readonly maxHp?: number;
|
||||
readonly color?: string | null;
|
||||
readonly icon?: string | null;
|
||||
readonly level?: number | null;
|
||||
}
|
||||
|
||||
export function usePlayerCharacters() {
|
||||
@@ -57,6 +58,7 @@ export function usePlayerCharacters() {
|
||||
maxHp: number,
|
||||
color: string | undefined,
|
||||
icon: string | undefined,
|
||||
level: number | undefined,
|
||||
) => {
|
||||
const id = generatePcId();
|
||||
const result = createPlayerCharacterUseCase(
|
||||
@@ -67,6 +69,7 @@ export function usePlayerCharacters() {
|
||||
maxHp,
|
||||
color,
|
||||
icon,
|
||||
level,
|
||||
);
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
@@ -103,6 +106,7 @@ export function usePlayerCharacters() {
|
||||
createCharacter,
|
||||
editCharacter,
|
||||
deleteCharacter,
|
||||
replacePlayerCharacters: setCharacters,
|
||||
makeStore,
|
||||
} as const;
|
||||
}
|
||||
|
||||
@@ -122,64 +122,7 @@ describe("loadEncounter", () => {
|
||||
expect(loadEncounter()).toBeNull();
|
||||
});
|
||||
|
||||
// US3: Corrupt data scenarios
|
||||
it("returns null for non-object JSON (string)", () => {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify("hello"));
|
||||
expect(loadEncounter()).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for non-object JSON (number)", () => {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(42));
|
||||
expect(loadEncounter()).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for non-object JSON (array)", () => {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify([1, 2, 3]));
|
||||
expect(loadEncounter()).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for non-object JSON (null)", () => {
|
||||
localStorage.setItem(STORAGE_KEY, "null");
|
||||
expect(loadEncounter()).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when combatants is a string instead of array", () => {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
combatants: "not-array",
|
||||
activeIndex: 0,
|
||||
roundNumber: 1,
|
||||
}),
|
||||
);
|
||||
expect(loadEncounter()).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when activeIndex is a string instead of number", () => {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
combatants: [{ id: "1", name: "Aria" }],
|
||||
activeIndex: "zero",
|
||||
roundNumber: 1,
|
||||
}),
|
||||
);
|
||||
expect(loadEncounter()).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when combatant entry is missing id", () => {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
combatants: [{ name: "Aria" }],
|
||||
activeIndex: 0,
|
||||
roundNumber: 1,
|
||||
}),
|
||||
);
|
||||
expect(loadEncounter()).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when combatant entry is missing name", () => {
|
||||
it("returns null when combatant has invalid required fields", () => {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
@@ -191,88 +134,6 @@ describe("loadEncounter", () => {
|
||||
expect(loadEncounter()).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for negative roundNumber", () => {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
combatants: [{ id: "1", name: "Aria" }],
|
||||
activeIndex: 0,
|
||||
roundNumber: -1,
|
||||
}),
|
||||
);
|
||||
expect(loadEncounter()).toBeNull();
|
||||
});
|
||||
|
||||
it("returns empty encounter for zero combatants (cleared state)", () => {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({ combatants: [], activeIndex: 0, roundNumber: 1 }),
|
||||
);
|
||||
const result = loadEncounter();
|
||||
expect(result).toEqual({
|
||||
combatants: [],
|
||||
activeIndex: 0,
|
||||
roundNumber: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("round-trip preserves combatant AC value", () => {
|
||||
const result = createEncounter(
|
||||
[{ id: combatantId("1"), name: "Aria", ac: 18 }],
|
||||
0,
|
||||
1,
|
||||
);
|
||||
if (isDomainError(result)) throw new Error("unreachable");
|
||||
saveEncounter(result);
|
||||
const loaded = loadEncounter();
|
||||
expect(loaded?.combatants[0].ac).toBe(18);
|
||||
});
|
||||
|
||||
it("round-trip preserves combatant without AC", () => {
|
||||
const result = createEncounter(
|
||||
[{ id: combatantId("1"), name: "Aria" }],
|
||||
0,
|
||||
1,
|
||||
);
|
||||
if (isDomainError(result)) throw new Error("unreachable");
|
||||
saveEncounter(result);
|
||||
const loaded = loadEncounter();
|
||||
expect(loaded?.combatants[0].ac).toBeUndefined();
|
||||
});
|
||||
|
||||
it("discards invalid AC values during rehydration", () => {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
combatants: [
|
||||
{ id: "1", name: "Neg", ac: -1 },
|
||||
{ id: "2", name: "Float", ac: 3.5 },
|
||||
{ id: "3", name: "Str", ac: "high" },
|
||||
],
|
||||
activeIndex: 0,
|
||||
roundNumber: 1,
|
||||
}),
|
||||
);
|
||||
const loaded = loadEncounter();
|
||||
expect(loaded).not.toBeNull();
|
||||
expect(loaded?.combatants[0].ac).toBeUndefined();
|
||||
expect(loaded?.combatants[1].ac).toBeUndefined();
|
||||
expect(loaded?.combatants[2].ac).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves AC of 0 during rehydration", () => {
|
||||
localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
combatants: [{ id: "1", name: "Aria", ac: 0 }],
|
||||
activeIndex: 0,
|
||||
roundNumber: 1,
|
||||
}),
|
||||
);
|
||||
const loaded = loadEncounter();
|
||||
expect(loaded?.combatants[0].ac).toBe(0);
|
||||
});
|
||||
|
||||
it("saving after modifications persists the latest state", () => {
|
||||
const encounter = makeEncounter();
|
||||
saveEncounter(encounter);
|
||||
|
||||
@@ -90,102 +90,7 @@ describe("player-character-storage", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("per-character validation", () => {
|
||||
it("discards character with missing name", () => {
|
||||
mockStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify([
|
||||
{ id: "pc-1", ac: 10, maxHp: 50, color: "blue", icon: "sword" },
|
||||
]),
|
||||
);
|
||||
expect(loadPlayerCharacters()).toEqual([]);
|
||||
});
|
||||
|
||||
it("discards character with empty name", () => {
|
||||
mockStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify([
|
||||
{
|
||||
id: "pc-1",
|
||||
name: "",
|
||||
ac: 10,
|
||||
maxHp: 50,
|
||||
color: "blue",
|
||||
icon: "sword",
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(loadPlayerCharacters()).toEqual([]);
|
||||
});
|
||||
|
||||
it("discards character with invalid color", () => {
|
||||
mockStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify([
|
||||
{
|
||||
id: "pc-1",
|
||||
name: "Test",
|
||||
ac: 10,
|
||||
maxHp: 50,
|
||||
color: "neon",
|
||||
icon: "sword",
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(loadPlayerCharacters()).toEqual([]);
|
||||
});
|
||||
|
||||
it("discards character with invalid icon", () => {
|
||||
mockStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify([
|
||||
{
|
||||
id: "pc-1",
|
||||
name: "Test",
|
||||
ac: 10,
|
||||
maxHp: 50,
|
||||
color: "blue",
|
||||
icon: "banana",
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(loadPlayerCharacters()).toEqual([]);
|
||||
});
|
||||
|
||||
it("discards character with negative AC", () => {
|
||||
mockStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify([
|
||||
{
|
||||
id: "pc-1",
|
||||
name: "Test",
|
||||
ac: -1,
|
||||
maxHp: 50,
|
||||
color: "blue",
|
||||
icon: "sword",
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(loadPlayerCharacters()).toEqual([]);
|
||||
});
|
||||
|
||||
it("discards character with maxHp of 0", () => {
|
||||
mockStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify([
|
||||
{
|
||||
id: "pc-1",
|
||||
name: "Test",
|
||||
ac: 10,
|
||||
maxHp: 0,
|
||||
color: "blue",
|
||||
icon: "sword",
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(loadPlayerCharacters()).toEqual([]);
|
||||
});
|
||||
|
||||
describe("delegation to domain rehydration", () => {
|
||||
it("keeps valid characters and discards invalid ones", () => {
|
||||
mockStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
import {
|
||||
type ConditionId,
|
||||
combatantId,
|
||||
type Combatant,
|
||||
createEncounter,
|
||||
creatureId,
|
||||
type Encounter,
|
||||
isDomainError,
|
||||
playerCharacterId,
|
||||
VALID_CONDITION_IDS,
|
||||
VALID_PLAYER_COLORS,
|
||||
VALID_PLAYER_ICONS,
|
||||
rehydrateCombatant,
|
||||
} from "@initiative/domain";
|
||||
|
||||
const STORAGE_KEY = "initiative:encounter";
|
||||
@@ -21,93 +16,6 @@ export function saveEncounter(encounter: Encounter): void {
|
||||
}
|
||||
}
|
||||
|
||||
function validateAc(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= 0
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function validateConditions(value: unknown): ConditionId[] | undefined {
|
||||
if (!Array.isArray(value)) return undefined;
|
||||
const valid = value.filter(
|
||||
(v): v is ConditionId =>
|
||||
typeof v === "string" && VALID_CONDITION_IDS.has(v),
|
||||
);
|
||||
return valid.length > 0 ? valid : undefined;
|
||||
}
|
||||
|
||||
function validateCreatureId(value: unknown) {
|
||||
return typeof value === "string" && value.length > 0
|
||||
? creatureId(value)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function validateHp(
|
||||
rawMaxHp: unknown,
|
||||
rawCurrentHp: unknown,
|
||||
): { maxHp: number; currentHp: number } | undefined {
|
||||
if (
|
||||
typeof rawMaxHp !== "number" ||
|
||||
!Number.isInteger(rawMaxHp) ||
|
||||
rawMaxHp < 1
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const validCurrentHp =
|
||||
typeof rawCurrentHp === "number" &&
|
||||
Number.isInteger(rawCurrentHp) &&
|
||||
rawCurrentHp >= 0 &&
|
||||
rawCurrentHp <= rawMaxHp;
|
||||
return {
|
||||
maxHp: rawMaxHp,
|
||||
currentHp: validCurrentHp ? rawCurrentHp : rawMaxHp,
|
||||
};
|
||||
}
|
||||
|
||||
function rehydrateCombatant(c: unknown) {
|
||||
const entry = c as Record<string, unknown>;
|
||||
const base = {
|
||||
id: combatantId(entry.id as string),
|
||||
name: entry.name as string,
|
||||
initiative:
|
||||
typeof entry.initiative === "number" ? entry.initiative : undefined,
|
||||
};
|
||||
|
||||
const color =
|
||||
typeof entry.color === "string" && VALID_PLAYER_COLORS.has(entry.color)
|
||||
? entry.color
|
||||
: undefined;
|
||||
const icon =
|
||||
typeof entry.icon === "string" && VALID_PLAYER_ICONS.has(entry.icon)
|
||||
? entry.icon
|
||||
: undefined;
|
||||
const pcId =
|
||||
typeof entry.playerCharacterId === "string" &&
|
||||
entry.playerCharacterId.length > 0
|
||||
? playerCharacterId(entry.playerCharacterId)
|
||||
: undefined;
|
||||
|
||||
const shared = {
|
||||
...base,
|
||||
ac: validateAc(entry.ac),
|
||||
conditions: validateConditions(entry.conditions),
|
||||
isConcentrating: entry.isConcentrating === true ? true : undefined,
|
||||
creatureId: validateCreatureId(entry.creatureId),
|
||||
color,
|
||||
icon,
|
||||
playerCharacterId: pcId,
|
||||
};
|
||||
|
||||
const hp = validateHp(entry.maxHp, entry.currentHp);
|
||||
return hp ? { ...shared, ...hp } : shared;
|
||||
}
|
||||
|
||||
function isValidCombatantEntry(c: unknown): boolean {
|
||||
if (typeof c !== "object" || c === null || Array.isArray(c)) return false;
|
||||
const entry = c as Record<string, unknown>;
|
||||
return typeof entry.id === "string" && typeof entry.name === "string";
|
||||
}
|
||||
|
||||
export function rehydrateEncounter(parsed: unknown): Encounter | null {
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
|
||||
return null;
|
||||
@@ -129,14 +37,21 @@ export function rehydrateEncounter(parsed: unknown): Encounter | null {
|
||||
};
|
||||
}
|
||||
|
||||
if (!combatants.every(isValidCombatantEntry)) return null;
|
||||
const rehydrated: Combatant[] = [];
|
||||
for (const c of combatants) {
|
||||
const result = rehydrateCombatant(c);
|
||||
if (result === null) return null;
|
||||
rehydrated.push(result);
|
||||
}
|
||||
|
||||
const rehydrated = combatants.map(rehydrateCombatant);
|
||||
const encounter = createEncounter(
|
||||
rehydrated,
|
||||
obj.activeIndex,
|
||||
obj.roundNumber,
|
||||
);
|
||||
if (isDomainError(encounter)) return null;
|
||||
|
||||
const result = createEncounter(rehydrated, obj.activeIndex, obj.roundNumber);
|
||||
if (isDomainError(result)) return null;
|
||||
|
||||
return result;
|
||||
return encounter;
|
||||
}
|
||||
|
||||
export function loadEncounter(): Encounter | null {
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import type {
|
||||
Encounter,
|
||||
ExportBundle,
|
||||
PlayerCharacter,
|
||||
UndoRedoState,
|
||||
} from "@initiative/domain";
|
||||
import { rehydratePlayerCharacter } from "@initiative/domain";
|
||||
import { rehydrateEncounter } from "./encounter-storage.js";
|
||||
|
||||
function rehydrateStack(raw: unknown[]): Encounter[] {
|
||||
const result: Encounter[] = [];
|
||||
for (const entry of raw) {
|
||||
const rehydrated = rehydrateEncounter(entry);
|
||||
if (rehydrated !== null) {
|
||||
result.push(rehydrated);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function rehydrateCharacters(raw: unknown[]): PlayerCharacter[] {
|
||||
const result: PlayerCharacter[] = [];
|
||||
for (const entry of raw) {
|
||||
const rehydrated = rehydratePlayerCharacter(entry);
|
||||
if (rehydrated !== null) {
|
||||
result.push(rehydrated);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function validateImportBundle(data: unknown): ExportBundle | string {
|
||||
if (typeof data !== "object" || data === null || Array.isArray(data)) {
|
||||
return "Invalid file format";
|
||||
}
|
||||
|
||||
const obj = data as Record<string, unknown>;
|
||||
|
||||
if (typeof obj.version !== "number" || obj.version !== 1) {
|
||||
return "Invalid file format";
|
||||
}
|
||||
if (typeof obj.exportedAt !== "string") {
|
||||
return "Invalid file format";
|
||||
}
|
||||
if (!Array.isArray(obj.undoStack) || !Array.isArray(obj.redoStack)) {
|
||||
return "Invalid file format";
|
||||
}
|
||||
if (!Array.isArray(obj.playerCharacters)) {
|
||||
return "Invalid file format";
|
||||
}
|
||||
|
||||
const encounter = rehydrateEncounter(obj.encounter);
|
||||
if (encounter === null) {
|
||||
return "Invalid encounter data";
|
||||
}
|
||||
|
||||
return {
|
||||
version: 1,
|
||||
exportedAt: obj.exportedAt,
|
||||
encounter,
|
||||
undoStack: rehydrateStack(obj.undoStack),
|
||||
redoStack: rehydrateStack(obj.redoStack),
|
||||
playerCharacters: rehydrateCharacters(obj.playerCharacters),
|
||||
};
|
||||
}
|
||||
|
||||
export function assembleExportBundle(
|
||||
encounter: Encounter,
|
||||
undoRedoState: UndoRedoState,
|
||||
playerCharacters: readonly PlayerCharacter[],
|
||||
includeHistory = true,
|
||||
): ExportBundle {
|
||||
return {
|
||||
version: 1,
|
||||
exportedAt: new Date().toISOString(),
|
||||
encounter,
|
||||
undoStack: includeHistory ? undoRedoState.undoStack : [],
|
||||
redoStack: includeHistory ? undoRedoState.redoStack : [],
|
||||
playerCharacters: [...playerCharacters],
|
||||
};
|
||||
}
|
||||
|
||||
export function bundleToJson(bundle: ExportBundle): string {
|
||||
return JSON.stringify(bundle, null, 2);
|
||||
}
|
||||
|
||||
export function resolveFilename(name?: string): string {
|
||||
const base =
|
||||
name?.trim() ||
|
||||
`initiative-export-${new Date().toISOString().slice(0, 10)}`;
|
||||
return base.endsWith(".json") ? base : `${base}.json`;
|
||||
}
|
||||
|
||||
export function triggerDownload(bundle: ExportBundle, name?: string): void {
|
||||
const blob = new Blob([bundleToJson(bundle)], { type: "application/json" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
const filename = resolveFilename(name);
|
||||
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = filename;
|
||||
anchor.click();
|
||||
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
export async function readImportFile(
|
||||
file: File,
|
||||
): Promise<ExportBundle | string> {
|
||||
try {
|
||||
const text = await file.text();
|
||||
const parsed: unknown = JSON.parse(text);
|
||||
return validateImportBundle(parsed);
|
||||
} catch {
|
||||
return "Invalid file format";
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,5 @@
|
||||
import type { PlayerCharacter } from "@initiative/domain";
|
||||
import {
|
||||
playerCharacterId,
|
||||
VALID_PLAYER_COLORS,
|
||||
VALID_PLAYER_ICONS,
|
||||
} from "@initiative/domain";
|
||||
import { rehydratePlayerCharacter } from "@initiative/domain";
|
||||
|
||||
const STORAGE_KEY = "initiative:player-characters";
|
||||
|
||||
@@ -15,46 +11,6 @@ export function savePlayerCharacters(characters: PlayerCharacter[]): void {
|
||||
}
|
||||
}
|
||||
|
||||
function isValidOptionalMember(
|
||||
value: unknown,
|
||||
valid: ReadonlySet<string>,
|
||||
): boolean {
|
||||
return value === undefined || (typeof value === "string" && valid.has(value));
|
||||
}
|
||||
|
||||
function rehydrateCharacter(raw: unknown): PlayerCharacter | null {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw))
|
||||
return null;
|
||||
const entry = raw as Record<string, unknown>;
|
||||
|
||||
if (typeof entry.id !== "string" || entry.id.length === 0) return null;
|
||||
if (typeof entry.name !== "string" || entry.name.trim().length === 0)
|
||||
return null;
|
||||
if (
|
||||
typeof entry.ac !== "number" ||
|
||||
!Number.isInteger(entry.ac) ||
|
||||
entry.ac < 0
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
typeof entry.maxHp !== "number" ||
|
||||
!Number.isInteger(entry.maxHp) ||
|
||||
entry.maxHp < 1
|
||||
)
|
||||
return null;
|
||||
if (!isValidOptionalMember(entry.color, VALID_PLAYER_COLORS)) return null;
|
||||
if (!isValidOptionalMember(entry.icon, VALID_PLAYER_ICONS)) return null;
|
||||
|
||||
return {
|
||||
id: playerCharacterId(entry.id),
|
||||
name: entry.name,
|
||||
ac: entry.ac,
|
||||
maxHp: entry.maxHp,
|
||||
color: entry.color as PlayerCharacter["color"],
|
||||
icon: entry.icon as PlayerCharacter["icon"],
|
||||
};
|
||||
}
|
||||
|
||||
export function loadPlayerCharacters(): PlayerCharacter[] {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
@@ -65,7 +21,7 @@ export function loadPlayerCharacters(): PlayerCharacter[] {
|
||||
|
||||
const characters: PlayerCharacter[] = [];
|
||||
for (const item of parsed) {
|
||||
const pc = rehydrateCharacter(item);
|
||||
const pc = rehydratePlayerCharacter(item);
|
||||
if (pc !== null) {
|
||||
characters.push(pc);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
---
|
||||
date: 2026-03-28T01:35:07.925247+00:00
|
||||
git_commit: f4fb69dbc763fefe4a73b3491c27093bbd06af0d
|
||||
branch: main
|
||||
topic: "Entity rehydration: current implementation and migration surface"
|
||||
tags: [research, codebase, rehydration, persistence, domain, player-character, combatant]
|
||||
status: complete
|
||||
---
|
||||
|
||||
# Research: Entity Rehydration — Current Implementation and Migration Surface
|
||||
|
||||
## Research Question
|
||||
|
||||
Map all entity rehydration logic (reconstructing typed domain objects from untyped JSON) across the codebase. Document what validation each rehydration function performs, where it lives, how functions cross-reference each other, and what the domain layer already provides that could replace adapter-level validation. This research supports Issue #20: Move entity rehydration to domain layer.
|
||||
|
||||
## Summary
|
||||
|
||||
Entity rehydration currently lives entirely in `apps/web/src/persistence/`. Two primary rehydration functions exist:
|
||||
|
||||
1. **`rehydrateCharacter`** in `player-character-storage.ts` — validates and reconstructs `PlayerCharacter` from unknown JSON
|
||||
2. **`rehydrateCombatant`** (private) + **`rehydrateEncounter`** (exported) in `encounter-storage.ts` — validates and reconstructs `Combatant`/`Encounter` from unknown JSON
|
||||
|
||||
These are consumed by three call sites: localStorage loading, undo/redo stack loading, and JSON import validation. The domain layer already contains parallel validation logic in `createPlayerCharacter`, `addCombatant`/`validateInit`, and `createEncounter`, but the rehydration functions duplicate this validation with subtly different rules (rehydration is lenient/recovering; creation is strict/rejecting).
|
||||
|
||||
## Detailed Findings
|
||||
|
||||
### 1. PlayerCharacter Rehydration
|
||||
|
||||
**File**: `apps/web/src/persistence/player-character-storage.ts:25-65`
|
||||
|
||||
`rehydrateCharacter(raw: unknown): PlayerCharacter | null` performs:
|
||||
|
||||
| Field | Validation | Behavior on invalid |
|
||||
|-------|-----------|-------------------|
|
||||
| `id` | `typeof string`, non-empty | Return `null` (reject entire PC) |
|
||||
| `name` | `typeof string`, non-empty after trim | Return `null` |
|
||||
| `ac` | `typeof number`, integer, `>= 0` | Return `null` |
|
||||
| `maxHp` | `typeof number`, integer, `>= 1` | Return `null` |
|
||||
| `color` | Optional; if present, must be in `VALID_PLAYER_COLORS` | Return `null` |
|
||||
| `icon` | Optional; if present, must be in `VALID_PLAYER_ICONS` | Return `null` |
|
||||
| `level` | Optional; if present, must be integer 1-20 | Return `null` |
|
||||
|
||||
Constructs result via branded `playerCharacterId()` and type assertions for color/icon.
|
||||
|
||||
**Helper**: `isValidOptionalMember(value, validSet)` — shared check for optional set-membership fields (lines 18-23).
|
||||
|
||||
**Callers**:
|
||||
- `loadPlayerCharacters()` (same file, line 67) — loads from localStorage
|
||||
- `rehydrateCharacters()` in `export-import.ts:21-30` — filters PCs during import validation
|
||||
|
||||
### 2. Combatant Rehydration
|
||||
|
||||
**File**: `apps/web/src/persistence/encounter-storage.ts:67-103`
|
||||
|
||||
`rehydrateCombatant(c: unknown)` (private, no return type annotation) performs:
|
||||
|
||||
| Field | Validation | Behavior on invalid |
|
||||
|-------|-----------|-------------------|
|
||||
| `id` | Cast directly (`entry.id as string`) | No validation (relies on `isValidCombatantEntry` pre-check) |
|
||||
| `name` | Cast directly (`entry.name as string`) | No validation (relies on pre-check) |
|
||||
| `initiative` | `typeof number` or `undefined` | Defaults to `undefined` |
|
||||
| `ac` | Via `validateAc`: integer `>= 0` | Defaults to `undefined` |
|
||||
| `conditions` | Via `validateConditions`: array, each in `VALID_CONDITION_IDS` | Defaults to `undefined` |
|
||||
| `isConcentrating` | Strictly `=== true` | Defaults to `undefined` |
|
||||
| `creatureId` | Via `validateCreatureId`: non-empty string | Defaults to `undefined` |
|
||||
| `color` | String in `VALID_PLAYER_COLORS` | Defaults to `undefined` |
|
||||
| `icon` | String in `VALID_PLAYER_ICONS` | Defaults to `undefined` |
|
||||
| `playerCharacterId` | Non-empty string | Defaults to `undefined` |
|
||||
| `maxHp` / `currentHp` | Via `validateHp`: maxHp integer >= 1, currentHp integer 0..maxHp | Defaults to `undefined`; invalid currentHp falls back to maxHp |
|
||||
|
||||
**Key difference from PC rehydration**: Combatant rehydration is *lenient* — invalid optional fields are silently dropped rather than rejecting the entire entity. Only `id` and `name` are required (checked by `isValidCombatantEntry` at line 105-109 before `rehydrateCombatant` is called).
|
||||
|
||||
**Helper functions** (all private):
|
||||
- `validateAc(value)` — lines 24-28
|
||||
- `validateConditions(value)` — lines 30-37
|
||||
- `validateCreatureId(value)` — lines 39-43
|
||||
- `validateHp(rawMaxHp, rawCurrentHp)` — lines 45-65
|
||||
|
||||
### 3. Encounter Rehydration
|
||||
|
||||
**File**: `apps/web/src/persistence/encounter-storage.ts:111-140`
|
||||
|
||||
`rehydrateEncounter(parsed: unknown): Encounter | null` validates the encounter envelope:
|
||||
- Must be a non-null, non-array object
|
||||
- `combatants` must be an array
|
||||
- `activeIndex` must be a number
|
||||
- `roundNumber` must be a number
|
||||
- Empty combatant array → returns hardcoded `{ combatants: [], activeIndex: 0, roundNumber: 1 }`
|
||||
- All entries must pass `isValidCombatantEntry` (id + name check)
|
||||
- Maps entries through `rehydrateCombatant`, then passes to domain's `createEncounter` for invariant enforcement
|
||||
|
||||
**Callers**:
|
||||
- `loadEncounter()` (same file, line 142) — localStorage
|
||||
- `loadStack()` in `undo-redo-storage.ts:17-36` — undo/redo stacks from localStorage
|
||||
- `rehydrateStack()` in `export-import.ts:10-19` — import validation
|
||||
- `validateImportBundle()` in `export-import.ts:32-65` — import validation (direct call for the main encounter)
|
||||
|
||||
### 4. Import Bundle Validation
|
||||
|
||||
**File**: `apps/web/src/persistence/export-import.ts:32-65`
|
||||
|
||||
`validateImportBundle(data: unknown): ExportBundle | string` validates the bundle envelope:
|
||||
- Version must be `1`
|
||||
- `exportedAt` must be a string
|
||||
- `undoStack` and `redoStack` must be arrays
|
||||
- `playerCharacters` must be an array
|
||||
- Delegates to `rehydrateEncounter` for the encounter
|
||||
- Delegates to `rehydrateStack` (which calls `rehydrateEncounter`) for undo/redo
|
||||
- Delegates to `rehydrateCharacters` (which calls `rehydrateCharacter`) for PCs
|
||||
|
||||
This function validates the *envelope* structure. Entity-level validation is fully delegated.
|
||||
|
||||
### 5. Domain Layer Validation (Existing)
|
||||
|
||||
The domain already contains validation for the same fields, but in *creation* context (typed inputs, DomainError returns):
|
||||
|
||||
**`createPlayerCharacter`** (`packages/domain/src/create-player-character.ts:17-100`):
|
||||
- Same field rules as `rehydrateCharacter`: name non-empty, ac >= 0 integer, maxHp >= 1 integer, color/icon in valid sets, level 1-20
|
||||
- Returns `DomainError` on invalid input (not `null`)
|
||||
|
||||
**`validateInit`** in `addCombatant` (`packages/domain/src/add-combatant.ts:27-53`):
|
||||
- Validates maxHp (positive integer), ac (non-negative integer), initiative (integer)
|
||||
- Does NOT validate conditions, color, icon, playerCharacterId, creatureId, isConcentrating
|
||||
|
||||
**`createEncounter`** (`packages/domain/src/types.ts:50-71`):
|
||||
- Validates activeIndex bounds and roundNumber (positive integer)
|
||||
- Already used by `rehydrateEncounter` as the final step
|
||||
|
||||
**`editPlayerCharacter`** (`packages/domain/src/edit-player-character.ts`):
|
||||
- `validateFields` validates the same PC fields for edits
|
||||
|
||||
### 6. Validation Overlap and Gaps
|
||||
|
||||
| Field | Rehydration validates | Domain validates |
|
||||
|-------|----------------------|-----------------|
|
||||
| PC.id | Non-empty string | N/A (caller provides) |
|
||||
| PC.name | Non-empty string | Non-empty (trimmed) |
|
||||
| PC.ac | Integer >= 0 | Integer >= 0 |
|
||||
| PC.maxHp | Integer >= 1 | Integer >= 1 |
|
||||
| PC.color | In VALID_PLAYER_COLORS | In VALID_PLAYER_COLORS |
|
||||
| PC.icon | In VALID_PLAYER_ICONS | In VALID_PLAYER_ICONS |
|
||||
| PC.level | Integer 1-20 | Integer 1-20 |
|
||||
| Combatant.id | Non-empty string (via pre-check) | N/A (caller provides) |
|
||||
| Combatant.name | String type (via pre-check) | Non-empty (trimmed) |
|
||||
| Combatant.initiative | `typeof number` | Integer |
|
||||
| Combatant.ac | Integer >= 0 | Integer >= 0 |
|
||||
| Combatant.maxHp | Integer >= 1 | Integer >= 1 |
|
||||
| Combatant.currentHp | Integer 0..maxHp | N/A (set = maxHp on add) |
|
||||
| Combatant.tempHp | **Not validated** | N/A |
|
||||
| Combatant.conditions | Each in VALID_CONDITION_IDS | N/A (toggleCondition checks) |
|
||||
| Combatant.isConcentrating | Strictly `true` or dropped | N/A (toggleConcentration) |
|
||||
| Combatant.creatureId | Non-empty string | N/A (passed through) |
|
||||
| Combatant.color | In VALID_PLAYER_COLORS | N/A (passed through) |
|
||||
| Combatant.icon | In VALID_PLAYER_ICONS | N/A (passed through) |
|
||||
| Combatant.playerCharacterId | Non-empty string | N/A (passed through) |
|
||||
|
||||
Key observations:
|
||||
- Rehydration validates `id` (required for identity); domain creation functions receive `id` as a typed parameter
|
||||
- Combatant rehydration does NOT validate `tempHp` at all — it's silently passed through or ignored
|
||||
- Combatant rehydration checks `initiative` as `typeof number` but domain checks `Number.isInteger` — slightly different strictness
|
||||
- Domain validation for combatant optional fields is scattered across individual mutation functions, not centralized
|
||||
|
||||
### 7. Test Coverage
|
||||
|
||||
**Persistence tests** (adapter layer):
|
||||
- `encounter-storage.test.ts` — ~27 tests covering round-trip, corrupt data, AC validation, edge cases
|
||||
- `player-character-storage.test.ts` — ~17 tests covering round-trip, corrupt data, field validation, level
|
||||
|
||||
**Import tests** (adapter layer):
|
||||
- `validate-import-bundle.test.ts` — ~21 tests covering envelope validation, graceful recovery, PC filtering
|
||||
- `export-import.test.ts` — ~15 tests covering bundle assembly, round-trip, filename resolution
|
||||
|
||||
**Domain tests**: No rehydration tests exist in `packages/domain/` — all rehydration testing is in the adapter layer.
|
||||
|
||||
### 8. Cross-Reference Map
|
||||
|
||||
```
|
||||
loadPlayerCharacters() ──→ rehydrateCharacter()
|
||||
↑
|
||||
validateImportBundle() ──→ rehydrateCharacters() ──┘
|
||||
├─→ rehydrateEncounter() ──→ isValidCombatantEntry()
|
||||
│ ├─→ rehydrateCombatant() ──→ validateAc()
|
||||
│ │ ├─→ validateConditions()
|
||||
│ │ ├─→ validateCreatureId()
|
||||
│ │ └─→ validateHp()
|
||||
│ └─→ createEncounter() [domain]
|
||||
└─→ rehydrateStack() ───→ rehydrateEncounter() [same as above]
|
||||
|
||||
loadEncounter() ───────→ rehydrateEncounter() [same as above]
|
||||
|
||||
loadUndoRedoStacks() ──→ loadStack() ──→ rehydrateEncounter() [same as above]
|
||||
```
|
||||
|
||||
## Code References
|
||||
|
||||
- `apps/web/src/persistence/player-character-storage.ts:25-65` — `rehydrateCharacter` (PC rehydration)
|
||||
- `apps/web/src/persistence/player-character-storage.ts:18-23` — `isValidOptionalMember` helper
|
||||
- `apps/web/src/persistence/encounter-storage.ts:24-28` — `validateAc` helper
|
||||
- `apps/web/src/persistence/encounter-storage.ts:30-37` — `validateConditions` helper
|
||||
- `apps/web/src/persistence/encounter-storage.ts:39-43` — `validateCreatureId` helper
|
||||
- `apps/web/src/persistence/encounter-storage.ts:45-65` — `validateHp` helper
|
||||
- `apps/web/src/persistence/encounter-storage.ts:67-103` — `rehydrateCombatant` (combatant rehydration)
|
||||
- `apps/web/src/persistence/encounter-storage.ts:105-109` — `isValidCombatantEntry` (pre-check)
|
||||
- `apps/web/src/persistence/encounter-storage.ts:111-140` — `rehydrateEncounter` (encounter envelope rehydration)
|
||||
- `apps/web/src/persistence/export-import.ts:10-30` — `rehydrateStack` / `rehydrateCharacters` (collection wrappers)
|
||||
- `apps/web/src/persistence/export-import.ts:32-65` — `validateImportBundle` (import envelope validation)
|
||||
- `apps/web/src/persistence/undo-redo-storage.ts:17-36` — `loadStack` (undo/redo rehydration)
|
||||
- `packages/domain/src/create-player-character.ts:17-100` — PC creation validation
|
||||
- `packages/domain/src/add-combatant.ts:27-53` — `validateInit` (combatant creation validation)
|
||||
- `packages/domain/src/types.ts:50-71` — `createEncounter` (encounter invariant enforcement)
|
||||
- `packages/domain/src/types.ts:12-26` — `Combatant` type definition
|
||||
- `packages/domain/src/player-character-types.ts:70-83` — `PlayerCharacter` type definition
|
||||
|
||||
## Architecture Documentation
|
||||
|
||||
### Current pattern
|
||||
Rehydration is an adapter concern — persistence adapters validate raw JSON and construct typed domain objects. The domain provides creation functions that validate typed inputs for new entities, but no functions for reconstructing entities from untyped serialized data.
|
||||
|
||||
### Rehydration vs. creation semantics
|
||||
Rehydration and creation serve different purposes:
|
||||
- **Creation** (domain): Validates business rules for *new* entities. Receives typed parameters. Returns `DomainError` on failure.
|
||||
- **Rehydration** (adapter): Reconstructs *previously valid* entities from serialized JSON. Receives `unknown`. Returns `null` on failure. May be lenient (combatants drop invalid optional fields) or strict (PCs reject on any invalid field).
|
||||
|
||||
### Delegation chain
|
||||
`rehydrateEncounter` already delegates to `createEncounter` for encounter-level invariants. The entity-level rehydration functions (`rehydrateCharacter`, `rehydrateCombatant`) do NOT delegate to any domain function — they re-implement field validation inline.
|
||||
|
||||
### tempHp gap
|
||||
`Combatant.tempHp` is defined in the domain type but has no validation in the current rehydration code. It appears to be silently included or excluded depending on what `rehydrateCombatant` constructs (it's not in the explicit field list, so it would be dropped during rehydration).
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. **Should `rehydrateCombatant` remain lenient (drop invalid optional fields) or become strict like `rehydrateCharacter` (reject on any invalid field)?** The current asymmetry is intentional: combatants can exist with minimal data (just id + name), while PCs always require ac/maxHp.
|
||||
|
||||
2. **Should `tempHp` be validated during rehydration?** It's currently missing from combatant rehydration but is a valid field on the type.
|
||||
|
||||
3. **Should `rehydrateEncounter` move to domain too, or only the entity-level functions?** The issue acceptance criteria says "validateImportBundle and rehydrateEncounter are unchanged" — but `rehydrateEncounter` currently lives alongside `rehydrateCombatant` and would need to import from domain instead of calling the local function.
|
||||
|
||||
4. **Should `isValidCombatantEntry` (the pre-check) be part of the domain rehydration or remain in the adapter?** It's currently the gate that ensures `id` and `name` exist before `rehydrateCombatant` is called.
|
||||
+3
-1
@@ -11,6 +11,7 @@
|
||||
"@biomejs/biome": "2.4.8",
|
||||
"@vitest/coverage-v8": "^4.1.0",
|
||||
"jscpd": "^4.0.8",
|
||||
"jsinspect-plus": "^3.1.3",
|
||||
"knip": "^5.88.1",
|
||||
"lefthook": "^2.1.4",
|
||||
"oxlint": "^1.56.0",
|
||||
@@ -29,10 +30,11 @@
|
||||
"test:watch": "vitest",
|
||||
"knip": "knip",
|
||||
"jscpd": "jscpd",
|
||||
"jsinspect": "jsinspect -c .jsinspectrc apps/web/src packages/domain/src packages/application/src",
|
||||
"oxlint": "oxlint --tsconfig apps/web/tsconfig.json --type-aware",
|
||||
"check:ignores": "node scripts/check-lint-ignores.mjs",
|
||||
"check:classnames": "node scripts/check-cn-classnames.mjs",
|
||||
"check:props": "node scripts/check-component-props.mjs",
|
||||
"check": "pnpm audit --audit-level=high && knip && biome check . && oxlint --tsconfig apps/web/tsconfig.json --type-aware && node scripts/check-lint-ignores.mjs && node scripts/check-cn-classnames.mjs && node scripts/check-component-props.mjs && tsc --build && vitest run && jscpd"
|
||||
"check": "pnpm audit --audit-level=high && knip && biome check . && oxlint --tsconfig apps/web/tsconfig.json --type-aware && node scripts/check-lint-ignores.mjs && node scripts/check-cn-classnames.mjs && node scripts/check-component-props.mjs && tsc --build && vitest run && jscpd && pnpm jsinspect"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ import {
|
||||
type CombatantInit,
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
isDomainError,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function addCombatantUseCase(
|
||||
store: EncounterStore,
|
||||
@@ -14,13 +14,7 @@ export function addCombatantUseCase(
|
||||
name: string,
|
||||
init?: CombatantInit,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = addCombatant(encounter, id, name, init);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) =>
|
||||
addCombatant(encounter, id, name, init),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,22 +3,16 @@ import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
isDomainError,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function adjustHpUseCase(
|
||||
store: EncounterStore,
|
||||
combatantId: CombatantId,
|
||||
delta: number,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = adjustHp(encounter, combatantId, delta);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) =>
|
||||
adjustHp(encounter, combatantId, delta),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,20 +2,12 @@ import {
|
||||
advanceTurn,
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
isDomainError,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function advanceTurnUseCase(
|
||||
store: EncounterStore,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = advanceTurn(encounter);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) => advanceTurn(encounter));
|
||||
}
|
||||
|
||||
@@ -2,20 +2,12 @@ import {
|
||||
clearEncounter,
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
isDomainError,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function clearEncounterUseCase(
|
||||
store: EncounterStore,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = clearEncounter(encounter);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) => clearEncounter(encounter));
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ export function createPlayerCharacterUseCase(
|
||||
maxHp: number,
|
||||
color: string | undefined,
|
||||
icon: string | undefined,
|
||||
level?: number,
|
||||
): DomainEvent[] | DomainError {
|
||||
const characters = store.getAll();
|
||||
const result = createPlayerCharacter(
|
||||
@@ -25,6 +26,7 @@ export function createPlayerCharacterUseCase(
|
||||
maxHp,
|
||||
color,
|
||||
icon,
|
||||
level,
|
||||
);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
|
||||
@@ -3,22 +3,16 @@ import {
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
editCombatant,
|
||||
isDomainError,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function editCombatantUseCase(
|
||||
store: EncounterStore,
|
||||
id: CombatantId,
|
||||
newName: string,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = editCombatant(encounter, id, newName);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) =>
|
||||
editCombatant(encounter, id, newName),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ interface EditFields {
|
||||
readonly maxHp?: number;
|
||||
readonly color?: string | null;
|
||||
readonly icon?: string | null;
|
||||
readonly level?: number | null;
|
||||
}
|
||||
|
||||
export function editPlayerCharacterUseCase(
|
||||
|
||||
@@ -2,22 +2,16 @@ import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
isDomainError,
|
||||
removeCombatant,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function removeCombatantUseCase(
|
||||
store: EncounterStore,
|
||||
id: CombatantId,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = removeCombatant(encounter, id);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) =>
|
||||
removeCombatant(encounter, id),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,21 +1,13 @@
|
||||
import {
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
isDomainError,
|
||||
retreatTurn,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function retreatTurnUseCase(
|
||||
store: EncounterStore,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = retreatTurn(encounter);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) => retreatTurn(encounter));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
type Encounter,
|
||||
isDomainError,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
|
||||
interface EncounterActionResult {
|
||||
readonly encounter: Encounter;
|
||||
readonly events: DomainEvent[];
|
||||
}
|
||||
|
||||
export function runEncounterAction(
|
||||
store: EncounterStore,
|
||||
action: (encounter: Encounter) => EncounterActionResult | DomainError,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = action(encounter);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
}
|
||||
@@ -2,23 +2,17 @@ import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
isDomainError,
|
||||
setAc,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function setAcUseCase(
|
||||
store: EncounterStore,
|
||||
combatantId: CombatantId,
|
||||
value: number | undefined,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = setAc(encounter, combatantId, value);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) =>
|
||||
setAc(encounter, combatantId, value),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,23 +2,17 @@ import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
isDomainError,
|
||||
setHp,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function setHpUseCase(
|
||||
store: EncounterStore,
|
||||
combatantId: CombatantId,
|
||||
maxHp: number | undefined,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = setHp(encounter, combatantId, maxHp);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) =>
|
||||
setHp(encounter, combatantId, maxHp),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,23 +2,17 @@ import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
isDomainError,
|
||||
setInitiative,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function setInitiativeUseCase(
|
||||
store: EncounterStore,
|
||||
combatantId: CombatantId,
|
||||
value: number | undefined,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = setInitiative(encounter, combatantId, value);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) =>
|
||||
setInitiative(encounter, combatantId, value),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,23 +2,17 @@ import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
isDomainError,
|
||||
setTempHp,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function setTempHpUseCase(
|
||||
store: EncounterStore,
|
||||
combatantId: CombatantId,
|
||||
tempHp: number | undefined,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = setTempHp(encounter, combatantId, tempHp);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) =>
|
||||
setTempHp(encounter, combatantId, tempHp),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,22 +2,16 @@ import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
isDomainError,
|
||||
toggleConcentration,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function toggleConcentrationUseCase(
|
||||
store: EncounterStore,
|
||||
combatantId: CombatantId,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = toggleConcentration(encounter, combatantId);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) =>
|
||||
toggleConcentration(encounter, combatantId),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,23 +3,17 @@ import {
|
||||
type ConditionId,
|
||||
type DomainError,
|
||||
type DomainEvent,
|
||||
isDomainError,
|
||||
toggleCondition,
|
||||
} from "@initiative/domain";
|
||||
import type { EncounterStore } from "./ports.js";
|
||||
import { runEncounterAction } from "./run-encounter-action.js";
|
||||
|
||||
export function toggleConditionUseCase(
|
||||
store: EncounterStore,
|
||||
combatantId: CombatantId,
|
||||
conditionId: ConditionId,
|
||||
): DomainEvent[] | DomainError {
|
||||
const encounter = store.get();
|
||||
const result = toggleCondition(encounter, combatantId, conditionId);
|
||||
|
||||
if (isDomainError(result)) {
|
||||
return result;
|
||||
}
|
||||
|
||||
store.save(result.encounter);
|
||||
return result.events;
|
||||
return runEncounterAction(store, (encounter) =>
|
||||
toggleCondition(encounter, combatantId, conditionId),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ function success(
|
||||
maxHp,
|
||||
color,
|
||||
icon,
|
||||
undefined,
|
||||
);
|
||||
if (isDomainError(result)) {
|
||||
throw new Error(`Expected success, got error: ${result.message}`);
|
||||
@@ -241,4 +242,76 @@ describe("createPlayerCharacter", () => {
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0].type).toBe("PlayerCharacterCreated");
|
||||
});
|
||||
|
||||
it("creates a player character with a valid level", () => {
|
||||
const result = createPlayerCharacter(
|
||||
[],
|
||||
id,
|
||||
"Test",
|
||||
10,
|
||||
50,
|
||||
"blue",
|
||||
"sword",
|
||||
5,
|
||||
);
|
||||
if (isDomainError(result)) throw new Error(result.message);
|
||||
expect(result.characters[0].level).toBe(5);
|
||||
});
|
||||
|
||||
it("creates a player character without a level", () => {
|
||||
const result = createPlayerCharacter(
|
||||
[],
|
||||
id,
|
||||
"Test",
|
||||
10,
|
||||
50,
|
||||
"blue",
|
||||
"sword",
|
||||
undefined,
|
||||
);
|
||||
if (isDomainError(result)) throw new Error(result.message);
|
||||
expect(result.characters[0].level).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects level below 1", () => {
|
||||
const result = createPlayerCharacter(
|
||||
[],
|
||||
id,
|
||||
"Test",
|
||||
10,
|
||||
50,
|
||||
"blue",
|
||||
"sword",
|
||||
0,
|
||||
);
|
||||
expectDomainError(result, "invalid-level");
|
||||
});
|
||||
|
||||
it("rejects level above 20", () => {
|
||||
const result = createPlayerCharacter(
|
||||
[],
|
||||
id,
|
||||
"Test",
|
||||
10,
|
||||
50,
|
||||
"blue",
|
||||
"sword",
|
||||
21,
|
||||
);
|
||||
expectDomainError(result, "invalid-level");
|
||||
});
|
||||
|
||||
it("rejects non-integer level", () => {
|
||||
const result = createPlayerCharacter(
|
||||
[],
|
||||
id,
|
||||
"Test",
|
||||
10,
|
||||
50,
|
||||
"blue",
|
||||
"sword",
|
||||
3.5,
|
||||
);
|
||||
expectDomainError(result, "invalid-level");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -110,4 +110,33 @@ describe("editPlayerCharacter", () => {
|
||||
expect(event.oldName).toBe("Aragorn");
|
||||
expect(event.newName).toBe("Strider");
|
||||
});
|
||||
|
||||
it("sets level on a player character", () => {
|
||||
const result = editPlayerCharacter([makePC()], id, { level: 5 });
|
||||
if (isDomainError(result)) throw new Error(result.message);
|
||||
expect(result.characters[0].level).toBe(5);
|
||||
});
|
||||
|
||||
it("clears level when set to null", () => {
|
||||
const result = editPlayerCharacter([makePC({ level: 5 })], id, {
|
||||
level: null,
|
||||
});
|
||||
if (isDomainError(result)) throw new Error(result.message);
|
||||
expect(result.characters[0].level).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects invalid level", () => {
|
||||
const result = editPlayerCharacter([makePC()], id, { level: 0 });
|
||||
expectDomainError(result, "invalid-level");
|
||||
});
|
||||
|
||||
it("rejects level above 20", () => {
|
||||
const result = editPlayerCharacter([makePC()], id, { level: 21 });
|
||||
expectDomainError(result, "invalid-level");
|
||||
});
|
||||
|
||||
it("rejects non-integer level", () => {
|
||||
const result = editPlayerCharacter([makePC()], id, { level: 3.5 });
|
||||
expectDomainError(result, "invalid-level");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
calculateEncounterDifficulty,
|
||||
crToXp,
|
||||
} from "../encounter-difficulty.js";
|
||||
|
||||
describe("crToXp", () => {
|
||||
it("returns 0 for CR 0", () => {
|
||||
expect(crToXp("0")).toBe(0);
|
||||
});
|
||||
|
||||
it("returns 25 for CR 1/8", () => {
|
||||
expect(crToXp("1/8")).toBe(25);
|
||||
});
|
||||
|
||||
it("returns 50 for CR 1/4", () => {
|
||||
expect(crToXp("1/4")).toBe(50);
|
||||
});
|
||||
|
||||
it("returns 100 for CR 1/2", () => {
|
||||
expect(crToXp("1/2")).toBe(100);
|
||||
});
|
||||
|
||||
it("returns 200 for CR 1", () => {
|
||||
expect(crToXp("1")).toBe(200);
|
||||
});
|
||||
|
||||
it("returns 155000 for CR 30", () => {
|
||||
expect(crToXp("30")).toBe(155000);
|
||||
});
|
||||
|
||||
it("returns 0 for unknown CR", () => {
|
||||
expect(crToXp("99")).toBe(0);
|
||||
expect(crToXp("")).toBe(0);
|
||||
expect(crToXp("abc")).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("calculateEncounterDifficulty", () => {
|
||||
it("returns trivial when monster XP is below Low threshold", () => {
|
||||
// 4x level 1: Low = 200, Moderate = 300, High = 400
|
||||
// 1x CR 0 = 0 XP → trivial
|
||||
const result = calculateEncounterDifficulty([1, 1, 1, 1], ["0"]);
|
||||
expect(result.tier).toBe("trivial");
|
||||
expect(result.totalMonsterXp).toBe(0);
|
||||
expect(result.partyBudget).toEqual({
|
||||
low: 200,
|
||||
moderate: 300,
|
||||
high: 400,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns low for 4x level 1 vs Bugbear (CR 1)", () => {
|
||||
// DMG example: 4x level 1 PCs vs 1 Bugbear (CR 1, 200 XP)
|
||||
// Low = 200, Moderate = 300 → 200 >= 200 but < 300 → Low
|
||||
const result = calculateEncounterDifficulty([1, 1, 1, 1], ["1"]);
|
||||
expect(result.tier).toBe("low");
|
||||
expect(result.totalMonsterXp).toBe(200);
|
||||
});
|
||||
|
||||
it("returns moderate for 5x level 3 vs 1125 XP", () => {
|
||||
// 5x level 3: Low = 750, Moderate = 1125, High = 2000
|
||||
// 1125 XP >= 1125 Moderate but < 2000 High → Moderate
|
||||
// Using CR 3 (700) + CR 2 (450) = 1150 XP ≈ 1125 threshold
|
||||
// Let's use exact: 5 * 225 = 1125 moderate budget
|
||||
// Need monsters that sum exactly to 1125: CR 3 (700) + CR 2 (450) = 1150
|
||||
const result = calculateEncounterDifficulty([3, 3, 3, 3, 3], ["3", "2"]);
|
||||
expect(result.tier).toBe("moderate");
|
||||
expect(result.totalMonsterXp).toBe(1150);
|
||||
expect(result.partyBudget.moderate).toBe(1125);
|
||||
});
|
||||
|
||||
it("returns high when XP meets High threshold", () => {
|
||||
// 4x level 1: High = 400
|
||||
// 2x CR 1 = 400 XP → High
|
||||
const result = calculateEncounterDifficulty([1, 1, 1, 1], ["1", "1"]);
|
||||
expect(result.tier).toBe("high");
|
||||
expect(result.totalMonsterXp).toBe(400);
|
||||
});
|
||||
|
||||
it("caps at high when XP far exceeds threshold", () => {
|
||||
// 4x level 1: High = 400
|
||||
// CR 30 = 155000 XP → still High (no tier above)
|
||||
const result = calculateEncounterDifficulty([1, 1, 1, 1], ["30"]);
|
||||
expect(result.tier).toBe("high");
|
||||
expect(result.totalMonsterXp).toBe(155000);
|
||||
});
|
||||
|
||||
it("handles mixed party levels", () => {
|
||||
// 3x level 3 + 1x level 2
|
||||
// level 3: low=150, mod=225, high=400 (x3 = 450, 675, 1200)
|
||||
// level 2: low=100, mod=150, high=200 (x1 = 100, 150, 200)
|
||||
// Total: low=550, mod=825, high=1400
|
||||
const result = calculateEncounterDifficulty([3, 3, 3, 2], ["3"]);
|
||||
expect(result.partyBudget).toEqual({
|
||||
low: 550,
|
||||
moderate: 825,
|
||||
high: 1400,
|
||||
});
|
||||
expect(result.totalMonsterXp).toBe(700);
|
||||
expect(result.tier).toBe("low");
|
||||
});
|
||||
|
||||
it("returns trivial with empty monster array", () => {
|
||||
const result = calculateEncounterDifficulty([5, 5], []);
|
||||
expect(result.tier).toBe("trivial");
|
||||
expect(result.totalMonsterXp).toBe(0);
|
||||
});
|
||||
|
||||
it("returns high with empty party array (zero budget thresholds)", () => {
|
||||
// Domain function treats empty party as zero budgets — any XP exceeds all thresholds.
|
||||
// The useDifficulty hook guards this path by returning null when no leveled PCs exist.
|
||||
const result = calculateEncounterDifficulty([], ["1"]);
|
||||
expect(result.tier).toBe("high");
|
||||
expect(result.totalMonsterXp).toBe(200);
|
||||
expect(result.partyBudget).toEqual({ low: 0, moderate: 0, high: 0 });
|
||||
});
|
||||
|
||||
it("handles fractional CRs", () => {
|
||||
const result = calculateEncounterDifficulty(
|
||||
[1, 1, 1, 1],
|
||||
["1/8", "1/4", "1/2"],
|
||||
);
|
||||
expect(result.totalMonsterXp).toBe(175); // 25 + 50 + 100
|
||||
expect(result.tier).toBe("trivial"); // 175 < 200 Low
|
||||
});
|
||||
|
||||
it("ignores unknown CRs (0 XP)", () => {
|
||||
const result = calculateEncounterDifficulty([1, 1, 1, 1], ["unknown"]);
|
||||
expect(result.totalMonsterXp).toBe(0);
|
||||
expect(result.tier).toBe("trivial");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,241 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { rehydrateCombatant } from "../rehydrate-combatant.js";
|
||||
|
||||
function validCombatant(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "c-1",
|
||||
name: "Goblin",
|
||||
initiative: 12,
|
||||
ac: 15,
|
||||
maxHp: 7,
|
||||
currentHp: 5,
|
||||
tempHp: 3,
|
||||
conditions: ["poisoned"],
|
||||
isConcentrating: true,
|
||||
creatureId: "creature-goblin",
|
||||
color: "red",
|
||||
icon: "skull",
|
||||
playerCharacterId: "pc-1",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function minimalCombatant() {
|
||||
return { id: "c-1", name: "Goblin" };
|
||||
}
|
||||
|
||||
describe("rehydrateCombatant", () => {
|
||||
describe("valid input", () => {
|
||||
it("accepts a combatant with all fields", () => {
|
||||
const result = rehydrateCombatant(validCombatant());
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.name).toBe("Goblin");
|
||||
expect(result?.initiative).toBe(12);
|
||||
expect(result?.ac).toBe(15);
|
||||
expect(result?.maxHp).toBe(7);
|
||||
expect(result?.currentHp).toBe(5);
|
||||
expect(result?.tempHp).toBe(3);
|
||||
expect(result?.conditions).toEqual(["poisoned"]);
|
||||
expect(result?.isConcentrating).toBe(true);
|
||||
expect(result?.creatureId).toBe("creature-goblin");
|
||||
expect(result?.color).toBe("red");
|
||||
expect(result?.icon).toBe("skull");
|
||||
expect(result?.playerCharacterId).toBe("pc-1");
|
||||
});
|
||||
|
||||
it("accepts a minimal combatant (id + name only)", () => {
|
||||
const result = rehydrateCombatant(minimalCombatant());
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.id).toBe("c-1");
|
||||
expect(result?.name).toBe("Goblin");
|
||||
expect(result?.initiative).toBeUndefined();
|
||||
expect(result?.ac).toBeUndefined();
|
||||
expect(result?.maxHp).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves branded CombatantId", () => {
|
||||
const result = rehydrateCombatant(minimalCombatant());
|
||||
expect(result?.id).toBe("c-1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("required field rejection", () => {
|
||||
it.each([
|
||||
null,
|
||||
42,
|
||||
"string",
|
||||
[1, 2],
|
||||
undefined,
|
||||
])("rejects non-object input: %j", (input) => {
|
||||
expect(rehydrateCombatant(input)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects missing id", () => {
|
||||
const { id: _, ...rest } = minimalCombatant();
|
||||
expect(rehydrateCombatant(rest)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects empty id", () => {
|
||||
expect(rehydrateCombatant({ ...minimalCombatant(), id: "" })).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects missing name", () => {
|
||||
const { name: _, ...rest } = minimalCombatant();
|
||||
expect(rehydrateCombatant(rest)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects non-string name", () => {
|
||||
expect(
|
||||
rehydrateCombatant({ ...minimalCombatant(), name: 42 }),
|
||||
).toBeNull();
|
||||
expect(
|
||||
rehydrateCombatant({ ...minimalCombatant(), name: null }),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("optional field leniency", () => {
|
||||
it("drops invalid ac — keeps combatant", () => {
|
||||
for (const ac of [-1, 1.5, "15"]) {
|
||||
const result = rehydrateCombatant({ ...minimalCombatant(), ac });
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.ac).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("drops invalid maxHp — keeps combatant", () => {
|
||||
for (const maxHp of [0, 1.5, "7"]) {
|
||||
const result = rehydrateCombatant({ ...minimalCombatant(), maxHp });
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.maxHp).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back currentHp to maxHp when currentHp invalid", () => {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
maxHp: 10,
|
||||
currentHp: "bad",
|
||||
});
|
||||
expect(result?.maxHp).toBe(10);
|
||||
expect(result?.currentHp).toBe(10);
|
||||
});
|
||||
|
||||
it("falls back currentHp to maxHp when currentHp > maxHp", () => {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
maxHp: 10,
|
||||
currentHp: 15,
|
||||
});
|
||||
expect(result?.maxHp).toBe(10);
|
||||
expect(result?.currentHp).toBe(10);
|
||||
});
|
||||
|
||||
it("drops invalid initiative — keeps combatant", () => {
|
||||
for (const initiative of [1.5, "12"]) {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
initiative,
|
||||
});
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.initiative).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("drops invalid conditions — keeps combatant", () => {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
conditions: "poisoned",
|
||||
});
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.conditions).toBeUndefined();
|
||||
});
|
||||
|
||||
it("drops unknown condition IDs", () => {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
conditions: ["fake-condition"],
|
||||
});
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.conditions).toBeUndefined();
|
||||
});
|
||||
|
||||
it("filters valid conditions from mixed array", () => {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
conditions: ["poisoned", "fake", "blinded"],
|
||||
});
|
||||
expect(result?.conditions).toEqual(["poisoned", "blinded"]);
|
||||
});
|
||||
|
||||
it("drops invalid color — keeps combatant", () => {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
color: "neon",
|
||||
});
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.color).toBeUndefined();
|
||||
});
|
||||
|
||||
it("drops invalid icon — keeps combatant", () => {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
icon: "rocket",
|
||||
});
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.icon).toBeUndefined();
|
||||
});
|
||||
|
||||
it("drops isConcentrating when not strictly true", () => {
|
||||
for (const isConcentrating of [false, "true", 1]) {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
isConcentrating,
|
||||
});
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.isConcentrating).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("drops invalid creatureId", () => {
|
||||
for (const creatureId of ["", 42]) {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
creatureId,
|
||||
});
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.creatureId).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("drops invalid playerCharacterId", () => {
|
||||
for (const playerCharacterId of ["", 42]) {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
playerCharacterId,
|
||||
});
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.playerCharacterId).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("drops invalid tempHp — keeps combatant", () => {
|
||||
for (const tempHp of [-1, 1.5, "3"]) {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
tempHp,
|
||||
});
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.tempHp).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves valid tempHp of 0", () => {
|
||||
const result = rehydrateCombatant({
|
||||
...minimalCombatant(),
|
||||
tempHp: 0,
|
||||
});
|
||||
expect(result?.tempHp).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { rehydratePlayerCharacter } from "../rehydrate-player-character.js";
|
||||
|
||||
function validPc(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: "pc-1",
|
||||
name: "Aria",
|
||||
ac: 16,
|
||||
maxHp: 45,
|
||||
color: "blue",
|
||||
icon: "sword",
|
||||
level: 5,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("rehydratePlayerCharacter", () => {
|
||||
describe("valid input", () => {
|
||||
it("accepts a valid PC with all fields", () => {
|
||||
const result = rehydratePlayerCharacter(validPc());
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.name).toBe("Aria");
|
||||
expect(result?.ac).toBe(16);
|
||||
expect(result?.maxHp).toBe(45);
|
||||
expect(result?.color).toBe("blue");
|
||||
expect(result?.icon).toBe("sword");
|
||||
expect(result?.level).toBe(5);
|
||||
});
|
||||
|
||||
it("accepts a valid PC without optional color/icon/level", () => {
|
||||
const result = rehydratePlayerCharacter(
|
||||
validPc({ color: undefined, icon: undefined, level: undefined }),
|
||||
);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.color).toBeUndefined();
|
||||
expect(result?.icon).toBeUndefined();
|
||||
expect(result?.level).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves branded PlayerCharacterId", () => {
|
||||
const result = rehydratePlayerCharacter(validPc());
|
||||
expect(result?.id).toBe("pc-1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("required field rejection", () => {
|
||||
it.each([
|
||||
null,
|
||||
42,
|
||||
"string",
|
||||
[1, 2],
|
||||
undefined,
|
||||
])("rejects non-object input: %j", (input) => {
|
||||
expect(rehydratePlayerCharacter(input)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects missing id", () => {
|
||||
const { id: _, ...rest } = validPc();
|
||||
expect(rehydratePlayerCharacter(rest)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects empty id", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ id: "" }))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects missing name", () => {
|
||||
const { name: _, ...rest } = validPc();
|
||||
expect(rehydratePlayerCharacter(rest)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects empty/whitespace name", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ name: "" }))).toBeNull();
|
||||
expect(rehydratePlayerCharacter(validPc({ name: " " }))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects missing ac", () => {
|
||||
const { ac: _, ...rest } = validPc();
|
||||
expect(rehydratePlayerCharacter(rest)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects negative ac", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ ac: -1 }))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects float ac", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ ac: 1.5 }))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects string ac", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ ac: "16" }))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects missing maxHp", () => {
|
||||
const { maxHp: _, ...rest } = validPc();
|
||||
expect(rehydratePlayerCharacter(rest)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects maxHp of 0", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ maxHp: 0 }))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects float maxHp", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ maxHp: 1.5 }))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects string maxHp", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ maxHp: "45" }))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("optional field rejection (strict)", () => {
|
||||
it("rejects invalid color", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ color: "neon" }))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects invalid icon", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ icon: "rocket" }))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects level 0", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ level: 0 }))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects level 21", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ level: 21 }))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects float level", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ level: 3.5 }))).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects string level", () => {
|
||||
expect(rehydratePlayerCharacter(validPc({ level: "5" }))).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,11 @@
|
||||
import type { DomainEvent } from "./events.js";
|
||||
import type { CombatantId, DomainError, Encounter } from "./types.js";
|
||||
import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type Encounter,
|
||||
findCombatant,
|
||||
isDomainError,
|
||||
} from "./types.js";
|
||||
|
||||
export interface AdjustHpSuccess {
|
||||
readonly encounter: Encounter;
|
||||
@@ -17,17 +23,9 @@ export function adjustHp(
|
||||
combatantId: CombatantId,
|
||||
delta: number,
|
||||
): AdjustHpSuccess | DomainError {
|
||||
const targetIdx = encounter.combatants.findIndex((c) => c.id === combatantId);
|
||||
|
||||
if (targetIdx === -1) {
|
||||
return {
|
||||
kind: "domain-error",
|
||||
code: "combatant-not-found",
|
||||
message: `No combatant found with ID "${combatantId}"`,
|
||||
};
|
||||
}
|
||||
|
||||
const target = encounter.combatants[targetIdx];
|
||||
const found = findCombatant(encounter, combatantId);
|
||||
if (isDomainError(found)) return found;
|
||||
const { combatant: target } = found;
|
||||
|
||||
if (target.maxHp === undefined || target.currentHp === undefined) {
|
||||
return {
|
||||
|
||||
@@ -22,6 +22,7 @@ export function createPlayerCharacter(
|
||||
maxHp: number,
|
||||
color: string | undefined,
|
||||
icon: string | undefined,
|
||||
level?: number,
|
||||
): CreatePlayerCharacterSuccess | DomainError {
|
||||
const trimmed = name.trim();
|
||||
|
||||
@@ -65,6 +66,17 @@ export function createPlayerCharacter(
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
level !== undefined &&
|
||||
(!Number.isInteger(level) || level < 1 || level > 20)
|
||||
) {
|
||||
return {
|
||||
kind: "domain-error",
|
||||
code: "invalid-level",
|
||||
message: "Level must be an integer between 1 and 20",
|
||||
};
|
||||
}
|
||||
|
||||
const newCharacter: PlayerCharacter = {
|
||||
id,
|
||||
name: trimmed,
|
||||
@@ -72,6 +84,7 @@ export function createPlayerCharacter(
|
||||
maxHp,
|
||||
color: color as PlayerCharacter["color"],
|
||||
icon: icon as PlayerCharacter["icon"],
|
||||
level,
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import type { DomainEvent } from "./events.js";
|
||||
import type { CombatantId, DomainError, Encounter } from "./types.js";
|
||||
import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type Encounter,
|
||||
findCombatant,
|
||||
isDomainError,
|
||||
} from "./types.js";
|
||||
|
||||
export interface EditCombatantSuccess {
|
||||
readonly encounter: Encounter;
|
||||
@@ -30,17 +36,9 @@ export function editCombatant(
|
||||
};
|
||||
}
|
||||
|
||||
const index = encounter.combatants.findIndex((c) => c.id === id);
|
||||
|
||||
if (index === -1) {
|
||||
return {
|
||||
kind: "domain-error",
|
||||
code: "combatant-not-found",
|
||||
message: `No combatant found with ID "${id}"`,
|
||||
};
|
||||
}
|
||||
|
||||
const oldName = encounter.combatants[index].name;
|
||||
const found = findCombatant(encounter, id);
|
||||
if (isDomainError(found)) return found;
|
||||
const oldName = found.combatant.name;
|
||||
|
||||
return {
|
||||
encounter: {
|
||||
|
||||
@@ -20,6 +20,7 @@ interface EditFields {
|
||||
readonly maxHp?: number;
|
||||
readonly color?: string | null;
|
||||
readonly icon?: string | null;
|
||||
readonly level?: number | null;
|
||||
}
|
||||
|
||||
function validateFields(fields: EditFields): DomainError | null {
|
||||
@@ -72,6 +73,17 @@ function validateFields(fields: EditFields): DomainError | null {
|
||||
message: `Invalid icon: ${fields.icon}`,
|
||||
};
|
||||
}
|
||||
if (
|
||||
fields.level !== undefined &&
|
||||
fields.level !== null &&
|
||||
(!Number.isInteger(fields.level) || fields.level < 1 || fields.level > 20)
|
||||
) {
|
||||
return {
|
||||
kind: "domain-error",
|
||||
code: "invalid-level",
|
||||
message: "Level must be an integer between 1 and 20",
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -92,6 +104,8 @@ function applyFields(
|
||||
fields.icon === undefined
|
||||
? existing.icon
|
||||
: ((fields.icon as PlayerCharacter["icon"]) ?? undefined),
|
||||
level:
|
||||
fields.level === undefined ? existing.level : (fields.level ?? undefined),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -120,7 +134,8 @@ export function editPlayerCharacter(
|
||||
updated.ac === existing.ac &&
|
||||
updated.maxHp === existing.maxHp &&
|
||||
updated.color === existing.color &&
|
||||
updated.icon === existing.icon
|
||||
updated.icon === existing.icon &&
|
||||
updated.level === existing.level
|
||||
) {
|
||||
return {
|
||||
kind: "domain-error",
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
export type DifficultyTier = "trivial" | "low" | "moderate" | "high";
|
||||
|
||||
export interface DifficultyResult {
|
||||
readonly tier: DifficultyTier;
|
||||
readonly totalMonsterXp: number;
|
||||
readonly partyBudget: {
|
||||
readonly low: number;
|
||||
readonly moderate: number;
|
||||
readonly high: number;
|
||||
};
|
||||
}
|
||||
|
||||
/** Maps challenge rating strings to XP values (standard 5e). */
|
||||
const CR_TO_XP: Readonly<Record<string, number>> = {
|
||||
"0": 0,
|
||||
"1/8": 25,
|
||||
"1/4": 50,
|
||||
"1/2": 100,
|
||||
"1": 200,
|
||||
"2": 450,
|
||||
"3": 700,
|
||||
"4": 1100,
|
||||
"5": 1800,
|
||||
"6": 2300,
|
||||
"7": 2900,
|
||||
"8": 3900,
|
||||
"9": 5000,
|
||||
"10": 5900,
|
||||
"11": 7200,
|
||||
"12": 8400,
|
||||
"13": 10000,
|
||||
"14": 11500,
|
||||
"15": 13000,
|
||||
"16": 15000,
|
||||
"17": 18000,
|
||||
"18": 20000,
|
||||
"19": 22000,
|
||||
"20": 25000,
|
||||
"21": 33000,
|
||||
"22": 41000,
|
||||
"23": 50000,
|
||||
"24": 62000,
|
||||
"25": 75000,
|
||||
"26": 90000,
|
||||
"27": 105000,
|
||||
"28": 120000,
|
||||
"29": 135000,
|
||||
"30": 155000,
|
||||
};
|
||||
|
||||
/** Maps character level (1-20) to XP budget thresholds (2024 5.5e DMG). */
|
||||
const XP_BUDGET_PER_CHARACTER: Readonly<
|
||||
Record<number, { low: number; moderate: number; high: number }>
|
||||
> = {
|
||||
1: { low: 50, moderate: 75, high: 100 },
|
||||
2: { low: 100, moderate: 150, high: 200 },
|
||||
3: { low: 150, moderate: 225, high: 400 },
|
||||
4: { low: 250, moderate: 375, high: 500 },
|
||||
5: { low: 500, moderate: 750, high: 1100 },
|
||||
6: { low: 600, moderate: 1000, high: 1400 },
|
||||
7: { low: 750, moderate: 1300, high: 1700 },
|
||||
8: { low: 1000, moderate: 1700, high: 2100 },
|
||||
9: { low: 1300, moderate: 2000, high: 2600 },
|
||||
10: { low: 1600, moderate: 2300, high: 3100 },
|
||||
11: { low: 1900, moderate: 2900, high: 4100 },
|
||||
12: { low: 2200, moderate: 3700, high: 4700 },
|
||||
13: { low: 2600, moderate: 4200, high: 5400 },
|
||||
14: { low: 2900, moderate: 4900, high: 6200 },
|
||||
15: { low: 3300, moderate: 5400, high: 7800 },
|
||||
16: { low: 3800, moderate: 6100, high: 9800 },
|
||||
17: { low: 4500, moderate: 7200, high: 11700 },
|
||||
18: { low: 5000, moderate: 8700, high: 14200 },
|
||||
19: { low: 5500, moderate: 10700, high: 17200 },
|
||||
20: { low: 6400, moderate: 13200, high: 22000 },
|
||||
};
|
||||
|
||||
/** Returns the XP value for a given CR string. Returns 0 for unknown CRs. */
|
||||
export function crToXp(cr: string): number {
|
||||
return CR_TO_XP[cr] ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates encounter difficulty from party levels and monster CRs.
|
||||
* Both arrays should be pre-filtered (only PCs with levels, only bestiary-linked monsters).
|
||||
*/
|
||||
export function calculateEncounterDifficulty(
|
||||
partyLevels: readonly number[],
|
||||
monsterCrs: readonly string[],
|
||||
): DifficultyResult {
|
||||
let budgetLow = 0;
|
||||
let budgetModerate = 0;
|
||||
let budgetHigh = 0;
|
||||
|
||||
for (const level of partyLevels) {
|
||||
const budget = XP_BUDGET_PER_CHARACTER[level];
|
||||
if (budget) {
|
||||
budgetLow += budget.low;
|
||||
budgetModerate += budget.moderate;
|
||||
budgetHigh += budget.high;
|
||||
}
|
||||
}
|
||||
|
||||
let totalMonsterXp = 0;
|
||||
for (const cr of monsterCrs) {
|
||||
totalMonsterXp += crToXp(cr);
|
||||
}
|
||||
|
||||
let tier: DifficultyTier = "trivial";
|
||||
if (totalMonsterXp >= budgetHigh) {
|
||||
tier = "high";
|
||||
} else if (totalMonsterXp >= budgetModerate) {
|
||||
tier = "moderate";
|
||||
} else if (totalMonsterXp >= budgetLow) {
|
||||
tier = "low";
|
||||
}
|
||||
|
||||
return {
|
||||
tier,
|
||||
totalMonsterXp,
|
||||
partyBudget: {
|
||||
low: budgetLow,
|
||||
moderate: budgetModerate,
|
||||
high: budgetHigh,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { PlayerCharacter } from "./player-character-types.js";
|
||||
import type { Encounter } from "./types.js";
|
||||
|
||||
export interface ExportBundle {
|
||||
readonly version: number;
|
||||
readonly exportedAt: string;
|
||||
readonly encounter: Encounter;
|
||||
readonly undoStack: readonly Encounter[];
|
||||
readonly redoStack: readonly Encounter[];
|
||||
readonly playerCharacters: readonly PlayerCharacter[];
|
||||
}
|
||||
@@ -48,6 +48,12 @@ export {
|
||||
type EditPlayerCharacterSuccess,
|
||||
editPlayerCharacter,
|
||||
} from "./edit-player-character.js";
|
||||
export {
|
||||
calculateEncounterDifficulty,
|
||||
crToXp,
|
||||
type DifficultyResult,
|
||||
type DifficultyTier,
|
||||
} from "./encounter-difficulty.js";
|
||||
export type {
|
||||
AcSet,
|
||||
CombatantAdded,
|
||||
@@ -71,6 +77,7 @@ export type {
|
||||
TurnAdvanced,
|
||||
TurnRetreated,
|
||||
} from "./events.js";
|
||||
export type { ExportBundle } from "./export-bundle.js";
|
||||
export { deriveHpStatus, type HpStatus } from "./hp-status.js";
|
||||
export {
|
||||
calculateInitiative,
|
||||
@@ -87,6 +94,8 @@ export {
|
||||
VALID_PLAYER_COLORS,
|
||||
VALID_PLAYER_ICONS,
|
||||
} from "./player-character-types.js";
|
||||
export { rehydrateCombatant } from "./rehydrate-combatant.js";
|
||||
export { rehydratePlayerCharacter } from "./rehydrate-player-character.js";
|
||||
export {
|
||||
type RemoveCombatantSuccess,
|
||||
removeCombatant,
|
||||
@@ -119,6 +128,7 @@ export {
|
||||
createEncounter,
|
||||
type DomainError,
|
||||
type Encounter,
|
||||
findCombatant,
|
||||
isDomainError,
|
||||
} from "./types.js";
|
||||
export {
|
||||
|
||||
@@ -74,6 +74,7 @@ export interface PlayerCharacter {
|
||||
readonly maxHp: number;
|
||||
readonly color?: PlayerColor;
|
||||
readonly icon?: PlayerIcon;
|
||||
readonly level?: number;
|
||||
}
|
||||
|
||||
export interface PlayerCharacterList {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import type { ConditionId } from "./conditions.js";
|
||||
import { VALID_CONDITION_IDS } from "./conditions.js";
|
||||
import { creatureId } from "./creature-types.js";
|
||||
import {
|
||||
playerCharacterId,
|
||||
VALID_PLAYER_COLORS,
|
||||
VALID_PLAYER_ICONS,
|
||||
} from "./player-character-types.js";
|
||||
import type { Combatant } from "./types.js";
|
||||
import { combatantId } from "./types.js";
|
||||
|
||||
function validateAc(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= 0
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function validateConditions(value: unknown): ConditionId[] | undefined {
|
||||
if (!Array.isArray(value)) return undefined;
|
||||
const valid = value.filter(
|
||||
(v): v is ConditionId =>
|
||||
typeof v === "string" && VALID_CONDITION_IDS.has(v),
|
||||
);
|
||||
return valid.length > 0 ? valid : undefined;
|
||||
}
|
||||
|
||||
function validateHp(
|
||||
rawMaxHp: unknown,
|
||||
rawCurrentHp: unknown,
|
||||
): { maxHp: number; currentHp: number } | undefined {
|
||||
if (
|
||||
typeof rawMaxHp !== "number" ||
|
||||
!Number.isInteger(rawMaxHp) ||
|
||||
rawMaxHp < 1
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const validCurrentHp =
|
||||
typeof rawCurrentHp === "number" &&
|
||||
Number.isInteger(rawCurrentHp) &&
|
||||
rawCurrentHp >= 0 &&
|
||||
rawCurrentHp <= rawMaxHp;
|
||||
return {
|
||||
maxHp: rawMaxHp,
|
||||
currentHp: validCurrentHp ? rawCurrentHp : rawMaxHp,
|
||||
};
|
||||
}
|
||||
|
||||
function validateTempHp(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= 0
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function validateInteger(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isInteger(value)
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function validateSetMember(
|
||||
value: unknown,
|
||||
valid: ReadonlySet<string>,
|
||||
): string | undefined {
|
||||
return typeof value === "string" && valid.has(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function validateNonEmptyString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.length > 0 ? value : undefined;
|
||||
}
|
||||
|
||||
function parseOptionalFields(entry: Record<string, unknown>) {
|
||||
return {
|
||||
initiative: validateInteger(entry.initiative),
|
||||
ac: validateAc(entry.ac),
|
||||
conditions: validateConditions(entry.conditions),
|
||||
isConcentrating: entry.isConcentrating === true ? true : undefined,
|
||||
creatureId: validateNonEmptyString(entry.creatureId)
|
||||
? creatureId(entry.creatureId as string)
|
||||
: undefined,
|
||||
color: validateSetMember(entry.color, VALID_PLAYER_COLORS),
|
||||
icon: validateSetMember(entry.icon, VALID_PLAYER_ICONS),
|
||||
playerCharacterId: validateNonEmptyString(entry.playerCharacterId)
|
||||
? playerCharacterId(entry.playerCharacterId as string)
|
||||
: undefined,
|
||||
tempHp: validateTempHp(entry.tempHp),
|
||||
};
|
||||
}
|
||||
|
||||
export function rehydrateCombatant(raw: unknown): Combatant | null {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw))
|
||||
return null;
|
||||
const entry = raw as Record<string, unknown>;
|
||||
|
||||
if (typeof entry.id !== "string" || entry.id.length === 0) return null;
|
||||
if (typeof entry.name !== "string") return null;
|
||||
|
||||
const shared: Combatant = {
|
||||
id: combatantId(entry.id),
|
||||
name: entry.name,
|
||||
...parseOptionalFields(entry),
|
||||
};
|
||||
|
||||
const hp = validateHp(entry.maxHp, entry.currentHp);
|
||||
return hp ? { ...shared, ...hp } : shared;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { PlayerCharacter } from "./player-character-types.js";
|
||||
import {
|
||||
playerCharacterId,
|
||||
VALID_PLAYER_COLORS,
|
||||
VALID_PLAYER_ICONS,
|
||||
} from "./player-character-types.js";
|
||||
|
||||
function isValidOptionalMember(
|
||||
value: unknown,
|
||||
valid: ReadonlySet<string>,
|
||||
): boolean {
|
||||
return value === undefined || (typeof value === "string" && valid.has(value));
|
||||
}
|
||||
|
||||
export function rehydratePlayerCharacter(raw: unknown): PlayerCharacter | null {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw))
|
||||
return null;
|
||||
const entry = raw as Record<string, unknown>;
|
||||
|
||||
if (typeof entry.id !== "string" || entry.id.length === 0) return null;
|
||||
if (typeof entry.name !== "string" || entry.name.trim().length === 0)
|
||||
return null;
|
||||
if (
|
||||
typeof entry.ac !== "number" ||
|
||||
!Number.isInteger(entry.ac) ||
|
||||
entry.ac < 0
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
typeof entry.maxHp !== "number" ||
|
||||
!Number.isInteger(entry.maxHp) ||
|
||||
entry.maxHp < 1
|
||||
)
|
||||
return null;
|
||||
if (!isValidOptionalMember(entry.color, VALID_PLAYER_COLORS)) return null;
|
||||
if (!isValidOptionalMember(entry.icon, VALID_PLAYER_ICONS)) return null;
|
||||
if (
|
||||
entry.level !== undefined &&
|
||||
(typeof entry.level !== "number" ||
|
||||
!Number.isInteger(entry.level) ||
|
||||
entry.level < 1 ||
|
||||
entry.level > 20)
|
||||
)
|
||||
return null;
|
||||
|
||||
return {
|
||||
id: playerCharacterId(entry.id),
|
||||
name: entry.name,
|
||||
ac: entry.ac,
|
||||
maxHp: entry.maxHp,
|
||||
color: entry.color as PlayerCharacter["color"],
|
||||
icon: entry.icon as PlayerCharacter["icon"],
|
||||
level: entry.level,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,11 @@
|
||||
import type { DomainEvent } from "./events.js";
|
||||
import type { CombatantId, DomainError, Encounter } from "./types.js";
|
||||
import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type Encounter,
|
||||
findCombatant,
|
||||
isDomainError,
|
||||
} from "./types.js";
|
||||
|
||||
export interface RemoveCombatantSuccess {
|
||||
readonly encounter: Encounter;
|
||||
@@ -22,17 +28,10 @@ export function removeCombatant(
|
||||
encounter: Encounter,
|
||||
id: CombatantId,
|
||||
): RemoveCombatantSuccess | DomainError {
|
||||
const removedIdx = encounter.combatants.findIndex((c) => c.id === id);
|
||||
const found = findCombatant(encounter, id);
|
||||
if (isDomainError(found)) return found;
|
||||
|
||||
if (removedIdx === -1) {
|
||||
return {
|
||||
kind: "domain-error",
|
||||
code: "combatant-not-found",
|
||||
message: `No combatant found with ID "${id}"`,
|
||||
};
|
||||
}
|
||||
|
||||
const removed = encounter.combatants[removedIdx];
|
||||
const { index: removedIdx, combatant: removed } = found;
|
||||
const newCombatants = encounter.combatants.filter((_, i) => i !== removedIdx);
|
||||
|
||||
let newActiveIndex: number;
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import type { DomainEvent } from "./events.js";
|
||||
import type { CombatantId, DomainError, Encounter } from "./types.js";
|
||||
import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type Encounter,
|
||||
findCombatant,
|
||||
isDomainError,
|
||||
} from "./types.js";
|
||||
|
||||
export interface SetAcSuccess {
|
||||
readonly encounter: Encounter;
|
||||
@@ -11,15 +17,8 @@ export function setAc(
|
||||
combatantId: CombatantId,
|
||||
value: number | undefined,
|
||||
): SetAcSuccess | DomainError {
|
||||
const targetIdx = encounter.combatants.findIndex((c) => c.id === combatantId);
|
||||
|
||||
if (targetIdx === -1) {
|
||||
return {
|
||||
kind: "domain-error",
|
||||
code: "combatant-not-found",
|
||||
message: `No combatant found with ID "${combatantId}"`,
|
||||
};
|
||||
}
|
||||
const found = findCombatant(encounter, combatantId);
|
||||
if (isDomainError(found)) return found;
|
||||
|
||||
if (value !== undefined && (!Number.isInteger(value) || value < 0)) {
|
||||
return {
|
||||
@@ -29,8 +28,7 @@ export function setAc(
|
||||
};
|
||||
}
|
||||
|
||||
const target = encounter.combatants[targetIdx];
|
||||
const previousAc = target.ac;
|
||||
const previousAc = found.combatant.ac;
|
||||
|
||||
const updatedCombatants = encounter.combatants.map((c) =>
|
||||
c.id === combatantId ? { ...c, ac: value } : c,
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import type { DomainEvent } from "./events.js";
|
||||
import type { CombatantId, DomainError, Encounter } from "./types.js";
|
||||
import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type Encounter,
|
||||
findCombatant,
|
||||
isDomainError,
|
||||
} from "./types.js";
|
||||
|
||||
export interface SetHpSuccess {
|
||||
readonly encounter: Encounter;
|
||||
@@ -18,15 +24,8 @@ export function setHp(
|
||||
combatantId: CombatantId,
|
||||
maxHp: number | undefined,
|
||||
): SetHpSuccess | DomainError {
|
||||
const targetIdx = encounter.combatants.findIndex((c) => c.id === combatantId);
|
||||
|
||||
if (targetIdx === -1) {
|
||||
return {
|
||||
kind: "domain-error",
|
||||
code: "combatant-not-found",
|
||||
message: `No combatant found with ID "${combatantId}"`,
|
||||
};
|
||||
}
|
||||
const found = findCombatant(encounter, combatantId);
|
||||
if (isDomainError(found)) return found;
|
||||
|
||||
if (maxHp !== undefined && (!Number.isInteger(maxHp) || maxHp < 1)) {
|
||||
return {
|
||||
@@ -36,9 +35,8 @@ export function setHp(
|
||||
};
|
||||
}
|
||||
|
||||
const target = encounter.combatants[targetIdx];
|
||||
const previousMaxHp = target.maxHp;
|
||||
const previousCurrentHp = target.currentHp;
|
||||
const previousMaxHp = found.combatant.maxHp;
|
||||
const previousCurrentHp = found.combatant.currentHp;
|
||||
|
||||
let newMaxHp: number | undefined;
|
||||
let newCurrentHp: number | undefined;
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import type { DomainEvent } from "./events.js";
|
||||
import { sortByInitiative } from "./initiative-sort.js";
|
||||
import type { CombatantId, DomainError, Encounter } from "./types.js";
|
||||
import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type Encounter,
|
||||
findCombatant,
|
||||
isDomainError,
|
||||
} from "./types.js";
|
||||
|
||||
export interface SetInitiativeSuccess {
|
||||
readonly encounter: Encounter;
|
||||
@@ -24,15 +30,8 @@ export function setInitiative(
|
||||
combatantId: CombatantId,
|
||||
value: number | undefined,
|
||||
): SetInitiativeSuccess | DomainError {
|
||||
const targetIdx = encounter.combatants.findIndex((c) => c.id === combatantId);
|
||||
|
||||
if (targetIdx === -1) {
|
||||
return {
|
||||
kind: "domain-error",
|
||||
code: "combatant-not-found",
|
||||
message: `No combatant found with ID "${combatantId}"`,
|
||||
};
|
||||
}
|
||||
const found = findCombatant(encounter, combatantId);
|
||||
if (isDomainError(found)) return found;
|
||||
|
||||
if (value !== undefined && !Number.isInteger(value)) {
|
||||
return {
|
||||
@@ -42,8 +41,7 @@ export function setInitiative(
|
||||
};
|
||||
}
|
||||
|
||||
const target = encounter.combatants[targetIdx];
|
||||
const previousValue = target.initiative;
|
||||
const previousValue = found.combatant.initiative;
|
||||
|
||||
// Create new combatants array with updated initiative
|
||||
const updated = encounter.combatants.map((c) =>
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import type { DomainEvent } from "./events.js";
|
||||
import type { CombatantId, DomainError, Encounter } from "./types.js";
|
||||
import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type Encounter,
|
||||
findCombatant,
|
||||
isDomainError,
|
||||
} from "./types.js";
|
||||
|
||||
export interface SetTempHpSuccess {
|
||||
readonly encounter: Encounter;
|
||||
@@ -18,17 +24,9 @@ export function setTempHp(
|
||||
combatantId: CombatantId,
|
||||
tempHp: number | undefined,
|
||||
): SetTempHpSuccess | DomainError {
|
||||
const targetIdx = encounter.combatants.findIndex((c) => c.id === combatantId);
|
||||
|
||||
if (targetIdx === -1) {
|
||||
return {
|
||||
kind: "domain-error",
|
||||
code: "combatant-not-found",
|
||||
message: `No combatant found with ID "${combatantId}"`,
|
||||
};
|
||||
}
|
||||
|
||||
const target = encounter.combatants[targetIdx];
|
||||
const found = findCombatant(encounter, combatantId);
|
||||
if (isDomainError(found)) return found;
|
||||
const { combatant: target } = found;
|
||||
|
||||
if (target.maxHp === undefined || target.currentHp === undefined) {
|
||||
return {
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import type { DomainEvent } from "./events.js";
|
||||
import type { CombatantId, DomainError, Encounter } from "./types.js";
|
||||
import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type Encounter,
|
||||
findCombatant,
|
||||
isDomainError,
|
||||
} from "./types.js";
|
||||
|
||||
export interface ToggleConcentrationSuccess {
|
||||
readonly encounter: Encounter;
|
||||
@@ -10,17 +16,9 @@ export function toggleConcentration(
|
||||
encounter: Encounter,
|
||||
combatantId: CombatantId,
|
||||
): ToggleConcentrationSuccess | DomainError {
|
||||
const targetIdx = encounter.combatants.findIndex((c) => c.id === combatantId);
|
||||
|
||||
if (targetIdx === -1) {
|
||||
return {
|
||||
kind: "domain-error",
|
||||
code: "combatant-not-found",
|
||||
message: `No combatant found with ID "${combatantId}"`,
|
||||
};
|
||||
}
|
||||
|
||||
const target = encounter.combatants[targetIdx];
|
||||
const found = findCombatant(encounter, combatantId);
|
||||
if (isDomainError(found)) return found;
|
||||
const { combatant: target } = found;
|
||||
const wasConcentrating = target.isConcentrating === true;
|
||||
|
||||
const event: DomainEvent = wasConcentrating
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import type { ConditionId } from "./conditions.js";
|
||||
import { CONDITION_DEFINITIONS, VALID_CONDITION_IDS } from "./conditions.js";
|
||||
import type { DomainEvent } from "./events.js";
|
||||
import type { CombatantId, DomainError, Encounter } from "./types.js";
|
||||
import {
|
||||
type CombatantId,
|
||||
type DomainError,
|
||||
type Encounter,
|
||||
findCombatant,
|
||||
isDomainError,
|
||||
} from "./types.js";
|
||||
|
||||
export interface ToggleConditionSuccess {
|
||||
readonly encounter: Encounter;
|
||||
@@ -21,17 +27,9 @@ export function toggleCondition(
|
||||
};
|
||||
}
|
||||
|
||||
const targetIdx = encounter.combatants.findIndex((c) => c.id === combatantId);
|
||||
|
||||
if (targetIdx === -1) {
|
||||
return {
|
||||
kind: "domain-error",
|
||||
code: "combatant-not-found",
|
||||
message: `No combatant found with ID "${combatantId}"`,
|
||||
};
|
||||
}
|
||||
|
||||
const target = encounter.combatants[targetIdx];
|
||||
const found = findCombatant(encounter, combatantId);
|
||||
if (isDomainError(found)) return found;
|
||||
const { combatant: target } = found;
|
||||
const current = target.conditions ?? [];
|
||||
const isActive = current.includes(conditionId);
|
||||
|
||||
|
||||
@@ -70,6 +70,20 @@ export function createEncounter(
|
||||
return { combatants, activeIndex, roundNumber };
|
||||
}
|
||||
|
||||
export function findCombatant(
|
||||
encounter: Encounter,
|
||||
id: CombatantId,
|
||||
): { index: number; combatant: Combatant } | DomainError {
|
||||
const index = encounter.combatants.findIndex((c) => c.id === id);
|
||||
if (index === -1) {
|
||||
return domainError(
|
||||
"combatant-not-found",
|
||||
`No combatant found with ID "${id}"`,
|
||||
);
|
||||
}
|
||||
return { index, combatant: encounter.combatants[index] };
|
||||
}
|
||||
|
||||
export function isDomainError(value: unknown): value is DomainError {
|
||||
return (
|
||||
typeof value === "object" &&
|
||||
|
||||
Generated
+119
@@ -21,6 +21,9 @@ importers:
|
||||
jscpd:
|
||||
specifier: ^4.0.8
|
||||
version: 4.0.8
|
||||
jsinspect-plus:
|
||||
specifier: ^3.1.3
|
||||
version: 3.1.3
|
||||
knip:
|
||||
specifier: ^5.88.1
|
||||
version: 5.88.1(@types/node@25.3.3)(typescript@5.9.3)
|
||||
@@ -133,15 +136,28 @@ packages:
|
||||
resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
|
||||
'@babel/helper-string-parser@8.0.0-rc.3':
|
||||
resolution: {integrity: sha512-AmwWFx1m8G/a5cXkxLxTiWl+YEoWuoFLUCwqMlNuWO1tqAYITQAbCRPUkyBHv1VOFgfjVOqEj6L3u15J5ZCzTA==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
|
||||
'@babel/helper-validator-identifier@7.28.5':
|
||||
resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
|
||||
'@babel/helper-validator-identifier@8.0.0-rc.3':
|
||||
resolution: {integrity: sha512-8AWCJ2VJJyDFlGBep5GpaaQ9AAaE/FjAcrqI7jyssYhtL7WGV0DOKpJsQqM037xDbpRLHXsY8TwU7zDma7coOw==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
|
||||
'@babel/parser@7.29.0':
|
||||
resolution: {integrity: sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==}
|
||||
engines: {node: '>=6.0.0'}
|
||||
hasBin: true
|
||||
|
||||
'@babel/parser@8.0.0-rc.3':
|
||||
resolution: {integrity: sha512-B20dvP3MfNc/XS5KKCHy/oyWl5IA6Cn9YjXRdDlCjNmUFrjvLXMNUfQq/QUy9fnG2gYkKKcrto2YaF9B32ToOQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
hasBin: true
|
||||
|
||||
'@babel/runtime@7.28.6':
|
||||
resolution: {integrity: sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
@@ -150,6 +166,10 @@ packages:
|
||||
resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
|
||||
'@babel/types@8.0.0-rc.3':
|
||||
resolution: {integrity: sha512-mOm5ZrYmphGfqVWoH5YYMTITb3cDXsFgmvFlvkvWDMsR9X8RFnt7a0Wb6yNIdoFsiMO9WjYLq+U/FMtqIYAF8Q==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
|
||||
'@bcoe/v8-coverage@1.0.2':
|
||||
resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -898,6 +918,10 @@ packages:
|
||||
resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
ansi-styles@3.2.1:
|
||||
resolution: {integrity: sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==}
|
||||
engines: {node: '>=4'}
|
||||
|
||||
ansi-styles@5.2.0:
|
||||
resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -956,6 +980,10 @@ packages:
|
||||
resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
chalk@2.4.2:
|
||||
resolution: {integrity: sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==}
|
||||
engines: {node: '>=4'}
|
||||
|
||||
character-parser@2.2.0:
|
||||
resolution: {integrity: sha512-+UqJQjFEFaTAs3bNsF2j2kEN1baG/zghZbdqoYEDxGZtJo9LBzl1A+m0D4n3qKx8N2FNv8/Xp6yV9mQmBuptaw==}
|
||||
|
||||
@@ -970,10 +998,19 @@ packages:
|
||||
resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
color-convert@1.9.3:
|
||||
resolution: {integrity: sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==}
|
||||
|
||||
color-name@1.1.3:
|
||||
resolution: {integrity: sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==}
|
||||
|
||||
colors@1.4.0:
|
||||
resolution: {integrity: sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==}
|
||||
engines: {node: '>=0.1.90'}
|
||||
|
||||
commander@2.20.3:
|
||||
resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==}
|
||||
|
||||
commander@5.1.0:
|
||||
resolution: {integrity: sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==}
|
||||
engines: {node: '>= 6'}
|
||||
@@ -1055,6 +1092,10 @@ packages:
|
||||
resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
escape-string-regexp@1.0.5:
|
||||
resolution: {integrity: sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==}
|
||||
engines: {node: '>=0.8.0'}
|
||||
|
||||
estree-walker@3.0.3:
|
||||
resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
|
||||
|
||||
@@ -1088,6 +1129,9 @@ packages:
|
||||
picomatch:
|
||||
optional: true
|
||||
|
||||
filepaths@0.3.0:
|
||||
resolution: {integrity: sha512-QFAYdzHZxWfBOHtHIlZySPAej+pxz6c2TGe8LGgHQNsgxHmcfbbQfNmsIh0kaangjL+6D6g8IoR6VDnOFrLEFw==}
|
||||
|
||||
fill-range@7.1.1:
|
||||
resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}
|
||||
engines: {node: '>=8'}
|
||||
@@ -1136,6 +1180,10 @@ packages:
|
||||
graceful-fs@4.2.11:
|
||||
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
|
||||
|
||||
has-flag@3.0.0:
|
||||
resolution: {integrity: sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==}
|
||||
engines: {node: '>=4'}
|
||||
|
||||
has-flag@4.0.0:
|
||||
resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}
|
||||
engines: {node: '>=8'}
|
||||
@@ -1251,6 +1299,10 @@ packages:
|
||||
canvas:
|
||||
optional: true
|
||||
|
||||
jsinspect-plus@3.1.3:
|
||||
resolution: {integrity: sha512-0GbLXDlfz9nPuybM/QunzEYKTwaETxGJ5+V7vZFS7+l8w426ePVU77dBH6k+KrxiJemIgVwY6Yxr3PCzFJwxgw==}
|
||||
hasBin: true
|
||||
|
||||
jsonfile@6.2.0:
|
||||
resolution: {integrity: sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==}
|
||||
|
||||
@@ -1650,6 +1702,10 @@ packages:
|
||||
spark-md5@3.0.2:
|
||||
resolution: {integrity: sha512-wcFzz9cDfbuqe0FZzfi2or1sgyIrsDwmPwfZC4hiNidPdPINjeUwNfv5kldczoEAcjl9Y1L3SM7Uz2PUEQzxQw==}
|
||||
|
||||
stable@0.1.8:
|
||||
resolution: {integrity: sha512-ji9qxRnOVfcuLDySj9qzhGSEFVobyt1kIOSkj1qZzYLzq7Tos/oUUWvotUPQLlrsidqsK6tBH89Bc9kL5zHA6w==}
|
||||
deprecated: 'Modern JS already guarantees Array#sort() is a stable sort, so this library is deprecated. See the compatibility table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#browser_compatibility'
|
||||
|
||||
stackback@0.0.2:
|
||||
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
|
||||
|
||||
@@ -1672,10 +1728,18 @@ packages:
|
||||
resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
strip-json-comments@3.1.1:
|
||||
resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
strip-json-comments@5.0.3:
|
||||
resolution: {integrity: sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==}
|
||||
engines: {node: '>=14.16'}
|
||||
|
||||
supports-color@5.5.0:
|
||||
resolution: {integrity: sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==}
|
||||
engines: {node: '>=4'}
|
||||
|
||||
supports-color@7.2.0:
|
||||
resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}
|
||||
engines: {node: '>=8'}
|
||||
@@ -1921,12 +1985,20 @@ snapshots:
|
||||
|
||||
'@babel/helper-string-parser@7.27.1': {}
|
||||
|
||||
'@babel/helper-string-parser@8.0.0-rc.3': {}
|
||||
|
||||
'@babel/helper-validator-identifier@7.28.5': {}
|
||||
|
||||
'@babel/helper-validator-identifier@8.0.0-rc.3': {}
|
||||
|
||||
'@babel/parser@7.29.0':
|
||||
dependencies:
|
||||
'@babel/types': 7.29.0
|
||||
|
||||
'@babel/parser@8.0.0-rc.3':
|
||||
dependencies:
|
||||
'@babel/types': 8.0.0-rc.3
|
||||
|
||||
'@babel/runtime@7.28.6': {}
|
||||
|
||||
'@babel/types@7.29.0':
|
||||
@@ -1934,6 +2006,11 @@ snapshots:
|
||||
'@babel/helper-string-parser': 7.27.1
|
||||
'@babel/helper-validator-identifier': 7.28.5
|
||||
|
||||
'@babel/types@8.0.0-rc.3':
|
||||
dependencies:
|
||||
'@babel/helper-string-parser': 8.0.0-rc.3
|
||||
'@babel/helper-validator-identifier': 8.0.0-rc.3
|
||||
|
||||
'@bcoe/v8-coverage@1.0.2': {}
|
||||
|
||||
'@biomejs/biome@2.4.8':
|
||||
@@ -2481,6 +2558,10 @@ snapshots:
|
||||
|
||||
ansi-regex@5.0.1: {}
|
||||
|
||||
ansi-styles@3.2.1:
|
||||
dependencies:
|
||||
color-convert: 1.9.3
|
||||
|
||||
ansi-styles@5.2.0: {}
|
||||
|
||||
aria-query@5.3.0:
|
||||
@@ -2534,6 +2615,12 @@ snapshots:
|
||||
|
||||
chai@6.2.2: {}
|
||||
|
||||
chalk@2.4.2:
|
||||
dependencies:
|
||||
ansi-styles: 3.2.1
|
||||
escape-string-regexp: 1.0.5
|
||||
supports-color: 5.5.0
|
||||
|
||||
character-parser@2.2.0:
|
||||
dependencies:
|
||||
is-regex: 1.2.1
|
||||
@@ -2550,8 +2637,16 @@ snapshots:
|
||||
|
||||
clsx@2.1.1: {}
|
||||
|
||||
color-convert@1.9.3:
|
||||
dependencies:
|
||||
color-name: 1.1.3
|
||||
|
||||
color-name@1.1.3: {}
|
||||
|
||||
colors@1.4.0: {}
|
||||
|
||||
commander@2.20.3: {}
|
||||
|
||||
commander@5.1.0: {}
|
||||
|
||||
constantinople@4.0.1:
|
||||
@@ -2624,6 +2719,8 @@ snapshots:
|
||||
dependencies:
|
||||
es-errors: 1.3.0
|
||||
|
||||
escape-string-regexp@1.0.5: {}
|
||||
|
||||
estree-walker@3.0.3:
|
||||
dependencies:
|
||||
'@types/estree': 1.0.8
|
||||
@@ -2664,6 +2761,8 @@ snapshots:
|
||||
optionalDependencies:
|
||||
picomatch: 4.0.4
|
||||
|
||||
filepaths@0.3.0: {}
|
||||
|
||||
fill-range@7.1.1:
|
||||
dependencies:
|
||||
to-regex-range: 5.0.1
|
||||
@@ -2715,6 +2814,8 @@ snapshots:
|
||||
|
||||
graceful-fs@4.2.11: {}
|
||||
|
||||
has-flag@3.0.0: {}
|
||||
|
||||
has-flag@4.0.0: {}
|
||||
|
||||
has-symbols@1.1.0: {}
|
||||
@@ -2841,6 +2942,16 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- '@noble/hashes'
|
||||
|
||||
jsinspect-plus@3.1.3:
|
||||
dependencies:
|
||||
'@babel/parser': 8.0.0-rc.3
|
||||
chalk: 2.4.2
|
||||
commander: 2.20.3
|
||||
filepaths: 0.3.0
|
||||
stable: 0.1.8
|
||||
strip-indent: 3.0.0
|
||||
strip-json-comments: 3.1.1
|
||||
|
||||
jsonfile@6.2.0:
|
||||
dependencies:
|
||||
universalify: 2.0.1
|
||||
@@ -3268,6 +3379,8 @@ snapshots:
|
||||
|
||||
spark-md5@3.0.2: {}
|
||||
|
||||
stable@0.1.8: {}
|
||||
|
||||
stackback@0.0.2: {}
|
||||
|
||||
std-env@4.0.0: {}
|
||||
@@ -3288,8 +3401,14 @@ snapshots:
|
||||
dependencies:
|
||||
min-indent: 1.0.1
|
||||
|
||||
strip-json-comments@3.1.1: {}
|
||||
|
||||
strip-json-comments@5.0.3: {}
|
||||
|
||||
supports-color@5.5.0:
|
||||
dependencies:
|
||||
has-flag: 3.0.0
|
||||
|
||||
supports-color@7.2.0:
|
||||
dependencies:
|
||||
has-flag: 4.0.0
|
||||
|
||||
@@ -226,7 +226,7 @@ Deleting a player character MUST NOT remove or modify any combatants currently i
|
||||
|
||||
### Key Entities
|
||||
|
||||
- **PlayerCharacter**: A persistent, reusable character template with a unique `PlayerCharacterId` (branded string), required `name`, `ac` (number), `maxHp` (number), `color` (string from predefined set), and `icon` (string identifier from preset icon set).
|
||||
- **PlayerCharacter**: A persistent, reusable character template with a unique `PlayerCharacterId` (branded string), required `name`, `ac` (number), `maxHp` (number), `color` (string from predefined set), `icon` (string identifier from preset icon set), and optional `level` (integer 1-20, added by spec 008 for encounter difficulty calculation).
|
||||
- **PlayerCharacterStore** (port): Interface for loading, saving, and deleting player characters. Implemented as a browser storage adapter.
|
||||
|
||||
---
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Data Model: Undo/Redo
|
||||
|
||||
**Feature**: 037-undo-redo
|
||||
**Feature**: 006-undo-redo
|
||||
**Date**: 2026-03-26
|
||||
|
||||
## Entities
|
||||
@@ -1,7 +1,7 @@
|
||||
# Implementation Plan: Undo/Redo
|
||||
|
||||
**Branch**: `037-undo-redo` | **Date**: 2026-03-26 | **Spec**: [spec.md](spec.md)
|
||||
**Input**: Feature specification from `/specs/037-undo-redo/spec.md`
|
||||
**Branch**: `006-undo-redo` | **Date**: 2026-03-26 | **Spec**: [spec.md](spec.md)
|
||||
**Input**: Feature specification from `/specs/006-undo-redo/spec.md`
|
||||
|
||||
## Summary
|
||||
|
||||
@@ -40,7 +40,7 @@ Add undo/redo capability for all encounter state changes using the memento patte
|
||||
### Documentation (this feature)
|
||||
|
||||
```text
|
||||
specs/037-undo-redo/
|
||||
specs/006-undo-redo/
|
||||
├── plan.md # This file
|
||||
├── research.md # Phase 0 output
|
||||
├── data-model.md # Phase 1 output
|
||||
@@ -1,6 +1,6 @@
|
||||
# Quickstart: Undo/Redo
|
||||
|
||||
**Feature**: 037-undo-redo
|
||||
**Feature**: 006-undo-redo
|
||||
**Date**: 2026-03-26
|
||||
|
||||
## Overview
|
||||
@@ -1,6 +1,6 @@
|
||||
# Research: Undo/Redo for Encounter Actions
|
||||
|
||||
**Feature**: 037-undo-redo
|
||||
**Feature**: 006-undo-redo
|
||||
**Date**: 2026-03-26
|
||||
|
||||
## Decision 1: Undo/Redo Strategy — Memento (Snapshots) vs Command (Events)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Feature Specification: Undo/Redo
|
||||
|
||||
**Feature Branch**: `037-undo-redo`
|
||||
**Feature Branch**: `006-undo-redo`
|
||||
**Created**: 2026-03-26
|
||||
**Status**: Draft
|
||||
**Input**: Gitea issue #16 — Undo/redo for encounter actions
|
||||
@@ -1,6 +1,6 @@
|
||||
# Tasks: Undo/Redo
|
||||
|
||||
**Input**: Design documents from `/specs/037-undo-redo/`
|
||||
**Input**: Design documents from `/specs/006-undo-redo/`
|
||||
**Prerequisites**: plan.md, spec.md, research.md, data-model.md, quickstart.md
|
||||
|
||||
**Tests**: Domain tests included (pure function testing is standard for this project per CLAUDE.md).
|
||||
@@ -0,0 +1,34 @@
|
||||
# Specification Quality Checklist: JSON Import/Export
|
||||
|
||||
**Purpose**: Validate specification completeness and quality before proceeding to planning
|
||||
**Created**: 2026-03-27
|
||||
**Feature**: [spec.md](../spec.md)
|
||||
|
||||
## Content Quality
|
||||
|
||||
- [x] No implementation details (languages, frameworks, APIs)
|
||||
- [x] Focused on user value and business needs
|
||||
- [x] Written for non-technical stakeholders
|
||||
- [x] All mandatory sections completed
|
||||
|
||||
## Requirement Completeness
|
||||
|
||||
- [x] No [NEEDS CLARIFICATION] markers remain
|
||||
- [x] Requirements are testable and unambiguous
|
||||
- [x] Success criteria are measurable
|
||||
- [x] Success criteria are technology-agnostic (no implementation details)
|
||||
- [x] All acceptance scenarios are defined
|
||||
- [x] Edge cases are identified
|
||||
- [x] Scope is clearly bounded
|
||||
- [x] Dependencies and assumptions identified
|
||||
|
||||
## Feature Readiness
|
||||
|
||||
- [x] All functional requirements have clear acceptance criteria
|
||||
- [x] User scenarios cover primary flows
|
||||
- [x] Feature meets measurable outcomes defined in Success Criteria
|
||||
- [x] No implementation details leak into specification
|
||||
|
||||
## Notes
|
||||
|
||||
- All items pass. Spec is ready for `/speckit.clarify` or `/speckit.plan`.
|
||||
@@ -0,0 +1,102 @@
|
||||
# Data Model: JSON Import/Export
|
||||
|
||||
**Feature**: 007-json-import-export
|
||||
**Date**: 2026-03-27
|
||||
|
||||
## Entities
|
||||
|
||||
### ExportBundle
|
||||
|
||||
The top-level structure written to and read from `.json` files. Contains all exportable application state.
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|--------------------|----------------------|----------|--------------------------------------------------|
|
||||
| version | number | Yes | Format version (starts at 1) |
|
||||
| exportedAt | string (ISO 8601) | Yes | Timestamp of when the export was created |
|
||||
| encounter | Encounter | Yes | Current encounter state (combatants + turn info) |
|
||||
| undoStack | Encounter[] | Yes | Undo history (encounter snapshots, max 50) |
|
||||
| redoStack | Encounter[] | Yes | Redo history (encounter snapshots) |
|
||||
| playerCharacters | PlayerCharacter[] | Yes | Player character templates |
|
||||
|
||||
### Encounter (existing)
|
||||
|
||||
Defined in `packages/domain/src/types.ts`. No changes needed — exported as-is via JSON serialization.
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|--------------|--------------|----------|--------------------------------------|
|
||||
| combatants | Combatant[] | Yes | Ordered list of combatants |
|
||||
| activeIndex | number | Yes | Index of current turn (0-based) |
|
||||
| roundNumber | number | Yes | Current round (starts at 1) |
|
||||
|
||||
### Combatant (existing)
|
||||
|
||||
Defined in `packages/domain/src/types.ts`. No changes needed.
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|--------------------|-------------------|----------|------------------------------------|
|
||||
| id | CombatantId | Yes | Unique identifier ("c-N") |
|
||||
| name | string | Yes | Display name |
|
||||
| initiative | number | No | Initiative roll result |
|
||||
| maxHp | number | No | Maximum hit points (>= 1) |
|
||||
| currentHp | number | No | Current HP (0 to maxHp) |
|
||||
| tempHp | number | No | Temporary hit points |
|
||||
| ac | number | No | Armor class (>= 0) |
|
||||
| conditions | ConditionId[] | No | Active status conditions |
|
||||
| isConcentrating | boolean | No | Concentration flag |
|
||||
| creatureId | CreatureId | No | Link to bestiary creature |
|
||||
| color | string | No | Visual color (from player char) |
|
||||
| icon | string | No | Visual icon (from player char) |
|
||||
| playerCharacterId | PlayerCharacterId | No | Link to player character template |
|
||||
|
||||
### PlayerCharacter (existing)
|
||||
|
||||
Defined in `packages/domain/src/player-character-types.ts`. No changes needed.
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|--------|-------------------|----------|-------------------------------------------|
|
||||
| id | PlayerCharacterId | Yes | Unique identifier ("pc-N") |
|
||||
| name | string | Yes | Character name |
|
||||
| ac | number | Yes | Armor class (>= 0) |
|
||||
| maxHp | number | Yes | Maximum hit points (>= 1) |
|
||||
| color | PlayerColor | No | Visual color (10 options) |
|
||||
| icon | PlayerIcon | No | Visual icon (15 options) |
|
||||
|
||||
## Validation Rules
|
||||
|
||||
### Import Validation
|
||||
|
||||
1. **Top-level structure**: Must be a JSON object with `version`, `encounter`, `undoStack`, `redoStack`, and `playerCharacters` fields.
|
||||
2. **Version check**: `version` must be a number. Unknown versions are rejected.
|
||||
3. **Encounter validation**: Delegated to existing `rehydrateEncounter()` — validates combatant structure, HP ranges, condition IDs, player colors/icons.
|
||||
4. **Undo/redo stack validation**: Each entry in both stacks is validated via `rehydrateEncounter()`. Invalid entries are silently dropped.
|
||||
5. **Player character validation**: Delegated to existing player character rehydration — validates types, ranges, color/icon enums.
|
||||
6. **Graceful degradation**: Invalid optional fields on combatants/characters are stripped (not rejected). Only structurally malformed data (missing required fields, wrong types) causes full rejection.
|
||||
|
||||
## State Transitions
|
||||
|
||||
### Export Flow
|
||||
|
||||
```
|
||||
User triggers export
|
||||
→ Read encounter from EncounterContext
|
||||
→ Read undoRedoState from EncounterContext
|
||||
→ Read playerCharacters from PlayerCharactersContext
|
||||
→ Assemble ExportBundle { version: 1, exportedAt, encounter, undoStack, redoStack, playerCharacters }
|
||||
→ Serialize to JSON
|
||||
→ Trigger browser file download
|
||||
```
|
||||
|
||||
### Import Flow
|
||||
|
||||
```
|
||||
User selects file
|
||||
→ Read file as text
|
||||
→ Parse JSON (reject on parse failure)
|
||||
→ Validate top-level structure (reject on missing fields)
|
||||
→ Validate encounter via rehydrateEncounter() (reject on null)
|
||||
→ Validate undo/redo stacks via rehydrateEncounter() per entry (filter invalid)
|
||||
→ Validate player characters via rehydration (filter invalid)
|
||||
→ If current encounter is non-empty: show confirmation dialog
|
||||
→ On confirm: replace encounter, undo/redo, and player characters in state
|
||||
→ State changes trigger existing useEffect auto-saves to localStorage
|
||||
```
|
||||
@@ -0,0 +1,111 @@
|
||||
# Implementation Plan: JSON Import/Export
|
||||
|
||||
**Branch**: `007-json-import-export` | **Date**: 2026-03-27 | **Spec**: [spec.md](spec.md)
|
||||
**Input**: Feature specification from `/specs/007-json-import-export/spec.md`
|
||||
|
||||
## Summary
|
||||
|
||||
Add JSON import/export for the full application state (encounter, undo/redo history, player characters). Export creates a downloadable `.json` file; import reads a file, validates it using existing rehydration functions, and replaces the current state after user confirmation. UI is integrated via the action bar overflow menu.
|
||||
|
||||
## Technical Context
|
||||
|
||||
**Language/Version**: TypeScript 5.8 (strict mode, `verbatimModuleSyntax`)
|
||||
**Primary Dependencies**: React 19, Vite 6, Tailwind CSS v4, Lucide React
|
||||
**Storage**: localStorage (encounter, undo/redo, player characters)
|
||||
**Testing**: Vitest (v8 coverage)
|
||||
**Target Platform**: Browser (desktop + mobile)
|
||||
**Project Type**: Web application (SPA)
|
||||
**Performance Goals**: Export/import completes in under 1 second for typical encounters
|
||||
**Constraints**: No server-side component; browser-only file operations
|
||||
**Scale/Scope**: Encounters with up to ~50 combatants, undo stacks of up to 50 snapshots
|
||||
|
||||
## Constitution Check
|
||||
|
||||
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
|
||||
|
||||
| Principle | Status | Notes |
|
||||
|-----------|--------|-------|
|
||||
| I. Deterministic Domain Core | PASS | No new domain logic needed. ExportBundle type is pure data. Validation reuses existing pure functions. |
|
||||
| II. Layered Architecture | PASS | Type in domain, validation in adapter layer (co-located with existing rehydration functions), file I/O and UI in adapter layer. No reverse dependencies. |
|
||||
| II-A. Context-Based State Flow | PASS | Import reads/writes state via existing contexts. No new props beyond per-instance config. |
|
||||
| III. Clarification-First | PASS | All decisions documented in research.md. No ambiguities remain. |
|
||||
| IV. Escalation Gates | PASS | Feature scope matches spec exactly. No out-of-scope additions. |
|
||||
| V. MVP Baseline Language | PASS | Format versioning and selective import noted as "not included in MVP baseline." |
|
||||
| VI. No Gameplay Rules | PASS | No gameplay mechanics involved. |
|
||||
|
||||
**Post-Phase 1 re-check**: All gates still pass. The ExportBundle type is a pure data structure in the domain layer. The validation logic lives in the adapter layer alongside existing rehydration functions (it depends on adapter-layer `rehydrateEncounter` and `rehydrateCharacter`). File I/O and UI live in the adapter layer.
|
||||
|
||||
## Project Structure
|
||||
|
||||
### Documentation (this feature)
|
||||
|
||||
```text
|
||||
specs/007-json-import-export/
|
||||
├── plan.md # This file
|
||||
├── research.md # Phase 0 output
|
||||
├── data-model.md # Phase 1 output
|
||||
├── quickstart.md # Phase 1 output
|
||||
└── tasks.md # Phase 2 output (/speckit.tasks)
|
||||
```
|
||||
|
||||
### Source Code (repository root)
|
||||
|
||||
```text
|
||||
packages/domain/src/
|
||||
├── export-bundle.ts # ExportBundle type definition
|
||||
|
||||
apps/web/src/
|
||||
├── persistence/
|
||||
│ └── export-import.ts # Export assembly + import validation + file handling
|
||||
├── hooks/
|
||||
│ └── use-encounter.ts # Existing — needs import/export state setters exposed
|
||||
├── components/
|
||||
│ ├── action-bar.tsx # Existing — add overflow menu items
|
||||
│ └── import-confirm-prompt.tsx # Confirmation dialog for import
|
||||
```
|
||||
|
||||
**Structure Decision**: Follows existing project structure. New files are minimal — one domain type, one persistence module (validation + export assembly + file handling), one UI component. Most work integrates into existing files.
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### Phase 1: ExportBundle Type + Validation Use Case
|
||||
|
||||
**Goal**: Define the export format and validation logic with full test coverage.
|
||||
|
||||
1. Create `ExportBundle` type in `packages/domain/src/export-bundle.ts`
|
||||
2. Export from domain package index
|
||||
3. Create `validateImportBundle()` in `apps/web/src/persistence/export-import.ts` — accepts `unknown`, returns validated `ExportBundle | DomainError`
|
||||
4. Import `rehydrateEncounter()` from `./encounter-storage.ts` for encounter and undo/redo stack validation
|
||||
5. Export `rehydrateCharacter()` from `player-character-storage.ts` and import it for player character validation
|
||||
6. Write tests covering: valid bundles, missing fields, invalid encounter, invalid player characters, empty stacks, unknown version
|
||||
|
||||
### Phase 2: Export Functionality
|
||||
|
||||
**Goal**: Users can download the current state as a `.json` file.
|
||||
|
||||
1. Create `export-import.ts` in `apps/web/src/persistence/`
|
||||
2. Implement `assembleExportBundle(encounter, undoRedoState, playerCharacters)` — pure function returning `ExportBundle`
|
||||
3. Implement `triggerDownload(bundle: ExportBundle)` — creates JSON blob, generates filename with date, triggers browser download
|
||||
4. Add "Export Encounter" item to action bar overflow menu
|
||||
5. Wire button to read from contexts and call export functions
|
||||
|
||||
### Phase 3: Import Functionality + Confirmation
|
||||
|
||||
**Goal**: Users can import a `.json` file with confirmation and error handling.
|
||||
|
||||
1. Add "Import Encounter" item to action bar overflow menu
|
||||
2. Implement file picker trigger (hidden `<input type="file">`)
|
||||
3. On file selected: read text, parse JSON, validate via use case
|
||||
4. If validation fails: show error toast
|
||||
5. If encounter is non-empty: show confirmation dialog
|
||||
6. On confirm (or if encounter is empty): replace encounter, undo/redo, and player characters via context setters
|
||||
7. Write integration test: export → import round-trip produces identical state
|
||||
|
||||
## Notes
|
||||
|
||||
- Import `rehydrateEncounter()` from `apps/web/src/persistence/encounter-storage.ts` for encounter validation — do not duplicate
|
||||
- Export `rehydrateCharacter()` from `apps/web/src/persistence/player-character-storage.ts` so it can be imported for player character validation
|
||||
- Follow existing file picker pattern from `apps/web/src/components/source-fetch-prompt.tsx`
|
||||
- Follow existing overflow menu pattern in `apps/web/src/components/action-bar.tsx`
|
||||
- Follow existing `<dialog>` pattern from `apps/web/src/components/settings-modal.tsx`
|
||||
- Commit after each phase checkpoint
|
||||
@@ -0,0 +1,52 @@
|
||||
# Quickstart: JSON Import/Export
|
||||
|
||||
**Feature**: 007-json-import-export
|
||||
**Date**: 2026-03-27
|
||||
|
||||
## Overview
|
||||
|
||||
Export and import the full application state (encounter, undo/redo history, player characters) as a JSON file. Enables backup/restore and sharing encounters between DMs.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- **ExportBundle**: A JSON object containing `version`, `exportedAt`, `encounter`, `undoStack`, `redoStack`, and `playerCharacters`. This is the file format.
|
||||
- **Full replacement**: Import replaces all existing state — encounter, undo/redo, and player characters. It's not a merge.
|
||||
- **Validation reuse**: Import validation uses the same `rehydrateEncounter()` and player character validation functions that localStorage loading uses.
|
||||
|
||||
## Implementation Layers
|
||||
|
||||
### Domain Layer
|
||||
|
||||
No new domain functions are needed. The existing types (`Encounter`, `PlayerCharacter`, `UndoRedoState`) and validation functions are reused as-is.
|
||||
|
||||
A new `ExportBundle` type is defined in the domain layer as a pure data structure.
|
||||
|
||||
### Application Layer
|
||||
|
||||
A new use case for import validation and bundle assembly:
|
||||
- `validateImportBundle(data: unknown)` — validates and rehydrates an export bundle, returning the validated bundle or an error.
|
||||
|
||||
Export assembly is straightforward enough to live in the adapter layer (it's just reading and packaging existing state).
|
||||
|
||||
### Adapter Layer (Web)
|
||||
|
||||
- **Export**: Read state from contexts, assemble bundle, trigger browser download via `URL.createObjectURL()` + anchor element.
|
||||
- **Import**: File picker input, parse JSON, delegate to application-layer validation, show confirmation dialog if encounter is non-empty, replace state via context setters.
|
||||
- **UI**: Two new overflow menu items in the action bar — "Export Encounter" and "Import Encounter".
|
||||
|
||||
## File Locations
|
||||
|
||||
| Artifact | Path |
|
||||
|----------|------|
|
||||
| ExportBundle type | `packages/domain/src/types.ts` or new file |
|
||||
| Import validation use case | `packages/application/src/` |
|
||||
| Export/import adapter functions | `apps/web/src/persistence/` |
|
||||
| UI integration | `apps/web/src/components/action-bar.tsx` |
|
||||
| Confirmation dialog | `apps/web/src/components/` (new or reuse existing confirm pattern) |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Domain**: No new domain tests needed (existing types unchanged).
|
||||
- **Application**: Test `validateImportBundle()` with valid bundles, invalid bundles, missing fields, wrong types, and edge cases (empty encounter, empty stacks).
|
||||
- **Adapter**: Test export bundle assembly and import file handling.
|
||||
- **Integration**: Round-trip test — export then import should produce identical state.
|
||||
@@ -0,0 +1,79 @@
|
||||
# Research: JSON Import/Export
|
||||
|
||||
**Feature**: 007-json-import-export
|
||||
**Date**: 2026-03-27
|
||||
|
||||
## Decision 1: Export Bundle Contents
|
||||
|
||||
**Decision**: Export includes encounter, undo/redo stacks, and player characters. Excludes bestiary cache, theme, and rules edition.
|
||||
|
||||
**Rationale**: The spec explicitly includes undo/redo history and player characters. Theme and rules edition are user preferences that should not transfer between DMs. Bestiary cache is large and can be rebuilt from sources.
|
||||
|
||||
**Alternatives considered**:
|
||||
- Include theme/edition settings — rejected because these are personal preferences, not encounter data.
|
||||
- Exclude undo/redo — rejected because the spec explicitly requires it and it enables full session restore.
|
||||
- Include bestiary cache — rejected because it's large, device-specific, and reconstructable from source URLs.
|
||||
|
||||
## Decision 2: Import Strategy — Full Replacement vs Merge
|
||||
|
||||
**Decision**: Full state replacement. Import replaces encounter, undo/redo, and player characters entirely.
|
||||
|
||||
**Rationale**: The spec states "Import replaces all existing state." Merging would require conflict resolution (duplicate IDs, name collisions) which adds significant complexity for unclear benefit.
|
||||
|
||||
**Alternatives considered**:
|
||||
- Merge player characters — rejected because ID conflicts between different sessions would be complex to resolve and the spec doesn't call for it.
|
||||
- Selective import (pick which parts to load) — rejected as out of MVP scope.
|
||||
|
||||
## Decision 3: Validation Approach
|
||||
|
||||
**Decision**: Reuse existing `rehydrateEncounter()` and player character validation from the persistence layer. These functions already handle all field validation, type checking, and graceful degradation for invalid fields.
|
||||
|
||||
**Rationale**: The spec explicitly states "validated using the same rules as localStorage loading." The existing `rehydrateEncounter()` function already validates every combatant field, filters invalid conditions, clamps HP values, and rejects structurally malformed data. Reusing it ensures consistency and avoids duplication.
|
||||
|
||||
**Alternatives considered**:
|
||||
- Write separate import validation — rejected because it would duplicate existing validation logic and risk divergence.
|
||||
- Stricter validation (reject files with any invalid field) — rejected because the existing approach gracefully degrades (strips invalid optional fields) which is more user-friendly.
|
||||
|
||||
## Decision 4: File Download Mechanism
|
||||
|
||||
**Decision**: Use `URL.createObjectURL()` with an anchor element's `download` attribute for triggering the file download.
|
||||
|
||||
**Rationale**: This is the standard browser-native approach that works across all modern browsers without popup blockers interfering. No server-side component needed.
|
||||
|
||||
**Alternatives considered**:
|
||||
- `window.open()` with data URI — rejected because popup blockers can interfere.
|
||||
- FileSaver.js library — rejected because the native approach is sufficient and avoids an additional dependency.
|
||||
|
||||
## Decision 5: File Upload Mechanism
|
||||
|
||||
**Decision**: Use an `<input type="file" accept=".json">` element, consistent with the existing pattern in `source-fetch-prompt.tsx` which uses `file.text()` + `JSON.parse()`.
|
||||
|
||||
**Rationale**: The codebase already has this pattern for bestiary source uploads. Reusing the same approach keeps the UX consistent.
|
||||
|
||||
## Decision 6: UI Placement
|
||||
|
||||
**Decision**: Place export and import actions in the action bar's overflow menu, alongside existing items like "Players", "Manage Sources", and "Settings".
|
||||
|
||||
**Rationale**: The overflow menu already groups secondary actions. Import/export are infrequent operations that don't need primary button placement. The action bar's `buildOverflowItems()` function makes this straightforward to add.
|
||||
|
||||
**Alternatives considered**:
|
||||
- Settings modal — rejected because import/export are actions, not settings.
|
||||
- Dedicated toolbar buttons — rejected because import/export are infrequent and would clutter the primary UI.
|
||||
|
||||
## Decision 7: Export File Naming
|
||||
|
||||
**Decision**: Use a filename pattern like `initiative-export-YYYY-MM-DD.json` with the current date.
|
||||
|
||||
**Rationale**: The date provides context for when the export was created. Including "initiative" in the name makes the file's purpose clear when browsing a downloads folder.
|
||||
|
||||
## Decision 8: State Restoration After Import
|
||||
|
||||
**Decision**: Import must update both React state and localStorage in one operation. The encounter hook's `setEncounter()` triggers a `useEffect` that auto-saves to localStorage, and `setUndoRedoState()` similarly auto-saves. For player characters, the same auto-save pattern applies.
|
||||
|
||||
**Rationale**: Following the existing state flow ensures consistency. Setting React state triggers the existing persistence effects, so no manual localStorage writes are needed for the import path.
|
||||
|
||||
## Decision 9: Export Format Versioning
|
||||
|
||||
**Decision**: Include a `version` field in the export format (e.g., `1`) but do not implement migration logic in MVP.
|
||||
|
||||
**Rationale**: The spec's assumptions state "Future format versioning is not included in MVP baseline." Including the version field costs nothing and enables future migration logic without breaking existing exports.
|
||||
@@ -0,0 +1,106 @@
|
||||
# Feature Specification: JSON Import/Export
|
||||
|
||||
**Feature Branch**: `007-json-import-export`
|
||||
**Created**: 2026-03-27
|
||||
**Status**: Draft
|
||||
**Input**: Gitea issue #17 — JSON import/export for full encounter state
|
||||
|
||||
## User Scenarios & Testing *(mandatory)*
|
||||
|
||||
### Story IE-1 — Export encounter to file (Priority: P1)
|
||||
|
||||
A DM has set up an encounter (combatants, HP, initiative, conditions) and wants to save or share it. They click an export button, choose whether to include undo/redo history, and either download a `.json` file or copy the JSON to their clipboard.
|
||||
|
||||
**Why this priority**: Export is the foundation — without it, import has nothing to work with. It also delivers standalone value as a backup mechanism.
|
||||
|
||||
**Independent Test**: Can be fully tested by creating an encounter, exporting (via download or clipboard), and verifying the output contains all encounter data and player character templates.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** the user clicks the export action, **Then** a dialog appears with an option to include undo/redo history (off by default) and two export methods: download file and copy to clipboard.
|
||||
2. **Given** an encounter with combatants (some with HP, AC, conditions, initiative), **When** the user exports, **Then** the output contains the encounter state, player character templates, and optionally undo/redo stacks.
|
||||
3. **Given** an empty encounter with no combatants, **When** the user exports, **Then** the output contains the empty encounter state and any existing player character templates.
|
||||
4. **Given** an encounter with player character combatants (color, icon, linked template), **When** the user exports, **Then** the exported data preserves all player character visual properties and template links.
|
||||
5. **Given** the user chooses "Copy to clipboard", **When** the export completes, **Then** the JSON is copied and a visual confirmation is shown.
|
||||
|
||||
---
|
||||
|
||||
### Story IE-2 — Import encounter from file (Priority: P1)
|
||||
|
||||
A DM receives a `.json` file from another DM (or from their own earlier export) and wants to load it. They click an import button, choose an import method (file upload or clipboard paste), and the application replaces the current state with the imported data.
|
||||
|
||||
**Why this priority**: Import completes the core value proposition — without it, export is just a read-only backup. Both are needed for the feature to be useful.
|
||||
|
||||
**Independent Test**: Can be tested by importing a valid `.json` file (or pasting valid JSON from the clipboard) and verifying the encounter, undo/redo history, and player characters are replaced with the imported data.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** the user clicks the import action, **Then** a dialog appears offering two import methods: file upload and clipboard paste.
|
||||
2. **Given** the current encounter is empty, **When** the user imports valid encounter data (via file or clipboard), **Then** the application loads the imported encounter, undo/redo history, and player characters without any confirmation prompt.
|
||||
3. **Given** the current encounter has combatants, **When** the user imports valid encounter data, **Then** a confirmation dialog appears warning that the current encounter will be replaced.
|
||||
4. **Given** the confirmation dialog is shown, **When** the user confirms, **Then** the current encounter, undo/redo history, and player characters are replaced with the imported data.
|
||||
5. **Given** the confirmation dialog is shown, **When** the user cancels, **Then** the current state remains unchanged.
|
||||
|
||||
---
|
||||
|
||||
### Story IE-3 — Reject invalid import files (Priority: P2)
|
||||
|
||||
A DM accidentally selects a wrong file (a non-JSON file, a corrupted export, or a JSON file with the wrong structure). The application rejects it and shows a clear error message without losing the current state.
|
||||
|
||||
**Why this priority**: Error handling is essential for a good user experience but secondary to the core import/export flow.
|
||||
|
||||
**Independent Test**: Can be tested by attempting to import various invalid files and verifying appropriate error messages appear while the current state is preserved.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** the user selects a non-JSON file (e.g., an image), **When** the import attempts to parse it, **Then** a user-facing error message is shown and the current state is unchanged.
|
||||
2. **Given** the user selects a JSON file with missing required fields, **When** the import validates it, **Then** a user-facing error message is shown and the current state is unchanged.
|
||||
3. **Given** the user selects a JSON file with a valid top-level structure but individual combatants with invalid fields (e.g., negative HP, unknown condition IDs), **When** the import validates it, **Then** invalid fields on otherwise valid combatants are dropped/defaulted (same as localStorage rehydration), but if the top-level structure is malformed (missing `encounter` key, wrong types), the file is rejected with an error message.
|
||||
4. **Given** the user chooses clipboard import but the clipboard is empty or contains non-JSON text, **Then** a user-facing error message is shown and the current state is unchanged.
|
||||
|
||||
---
|
||||
|
||||
### Edge Cases
|
||||
|
||||
- What happens when the exported file is from a newer version of the application with unknown fields? The import ignores unknown fields and loads what it can validate.
|
||||
- What happens when the user imports a file with player characters that conflict with existing player character IDs? The imported player characters replace the existing ones entirely (full state replacement, not merge).
|
||||
- What happens when the undo/redo stacks in the imported file are empty or missing? The system loads with empty undo/redo stacks (same as a fresh session).
|
||||
- What happens when the browser blocks the file download (e.g., popup blocker)? The export uses a direct download mechanism (anchor element with download attribute) that is not subject to popup blocking.
|
||||
|
||||
## Requirements *(mandatory)*
|
||||
|
||||
### Functional Requirements
|
||||
|
||||
- **FR-001**: The system MUST provide an export action accessible from the UI that lets the user download the application state as a `.json` file or copy it to the clipboard.
|
||||
- **FR-002**: The exported data MUST contain the current encounter (combatants and turn/round state) and player character templates. Undo/redo stacks MUST be includable via a user option (default: excluded).
|
||||
- **FR-003**: The exported file MUST use a human-readable default filename that includes the date. The user MAY optionally specify a custom filename; the `.json` extension is appended automatically if not provided.
|
||||
- **FR-004**: The system MUST provide an import action accessible from the UI that lets the user choose between uploading a `.json` file or pasting from the clipboard.
|
||||
- **FR-005**: On import, the system MUST replace the current encounter, undo/redo history, and player characters with the imported data.
|
||||
- **FR-006**: The system MUST show a confirmation dialog before importing if the current encounter is non-empty (has at least one combatant).
|
||||
- **FR-007**: The system MUST validate imported data using the same rules applied when loading from localStorage — invalid fields are cleaned or dropped, structurally malformed files are rejected entirely.
|
||||
- **FR-008**: The system MUST show a user-facing error message when an imported file is rejected as invalid.
|
||||
- **FR-009**: A failed or cancelled import MUST NOT alter the current application state.
|
||||
- **FR-010**: Export and import actions MUST be accessible from the same location in the UI.
|
||||
|
||||
### Key Entities
|
||||
|
||||
- **Export Bundle**: A single JSON structure containing the encounter snapshot, undo stack, redo stack, and player character list. Represents the full application state at the time of export.
|
||||
|
||||
## Success Criteria *(mandatory)*
|
||||
|
||||
### Measurable Outcomes
|
||||
|
||||
- **SC-001**: Users can export the current state to a downloadable file in one click.
|
||||
- **SC-002**: Users can import a previously exported file and see the full encounter restored, including combatant stats, turn tracking, and player characters.
|
||||
- **SC-003**: Importing an invalid file shows an error message within 1 second without affecting the current state.
|
||||
- **SC-004**: A round-trip (export then import) produces an encounter identical to the original.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The export format does not need to be backwards-compatible across application versions at this stage. Future format versioning is not included in MVP baseline.
|
||||
- Export/import covers the three main state stores: encounter, undo/redo, and player characters. Bestiary cache and user settings (theme, rules edition) are excluded.
|
||||
- The import is a full state replacement, not a merge. There is no selective import of individual pieces.
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Undo/redo system (spec 006) must be implemented so that undo/redo stacks can be included in the export.
|
||||
@@ -0,0 +1,142 @@
|
||||
# Tasks: JSON Import/Export
|
||||
|
||||
**Input**: Design documents from `/specs/007-json-import-export/`
|
||||
**Prerequisites**: plan.md, spec.md, research.md, data-model.md, quickstart.md
|
||||
|
||||
**Tests**: Domain tests included (pure function testing is standard for this project per CLAUDE.md).
|
||||
|
||||
**Organization**: Tasks are grouped by user story to enable independent implementation and testing of each story.
|
||||
|
||||
## Format: `[ID] [P?] [Story] Description`
|
||||
|
||||
- **[P]**: Can run in parallel (different files, no dependencies)
|
||||
- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3)
|
||||
- Include exact file paths in descriptions
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Foundational (ExportBundle Type + Validation)
|
||||
|
||||
**Purpose**: Define the export format and validation logic that all stories depend on.
|
||||
|
||||
**⚠️ CRITICAL**: Export and import both depend on the ExportBundle type and validation.
|
||||
|
||||
- [x] T001 [P] Create `ExportBundle` type in `packages/domain/src/export-bundle.ts` with fields: `version` (number), `exportedAt` (string), `encounter` (Encounter), `undoStack` (Encounter[]), `redoStack` (Encounter[]), `playerCharacters` (PlayerCharacter[]). Export from `packages/domain/src/index.ts`.
|
||||
- [x] T002 [P] Create `validateImportBundle()` in `apps/web/src/persistence/export-import.ts` — accepts `unknown`, validates top-level structure (version, encounter, undoStack, redoStack, playerCharacters), delegates encounter validation to `rehydrateEncounter()` (imported from `./encounter-storage.ts`) and player character validation to `rehydrateCharacter()` (exported from `./player-character-storage.ts`). Returns validated `ExportBundle` or `DomainError`.
|
||||
- [x] T003 Write tests for `validateImportBundle()` in `apps/web/src/__tests__/validate-import-bundle.test.ts` — valid bundle, missing fields, invalid encounter, invalid player characters, empty stacks, unknown version, non-object input, invalid JSON types for each field.
|
||||
|
||||
**Checkpoint**: ExportBundle type and validation are tested and ready for use by export and import stories.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: User Story 1 — Export Encounter to File (Priority: P1) 🎯 MVP
|
||||
|
||||
**Goal**: Users can download the current state as a `.json` file in one click.
|
||||
|
||||
**Independent Test**: Create an encounter with combatants, HP, conditions, and player characters. Click export. Verify the downloaded file contains all state and is valid JSON matching the ExportBundle schema.
|
||||
|
||||
### Implementation for User Story 1
|
||||
|
||||
- [x] T004 [P] [US1] Create `assembleExportBundle()` function in `apps/web/src/persistence/export-import.ts` — takes encounter, undoRedoState, and playerCharacters, returns an `ExportBundle` with version 1 and current ISO timestamp.
|
||||
- [x] T005 [P] [US1] Create `triggerDownload(bundle: ExportBundle)` function in `apps/web/src/persistence/export-import.ts` — serializes bundle to JSON, creates a Blob, generates filename `initiative-export-YYYY-MM-DD.json`, triggers download via anchor element with `download` attribute.
|
||||
- [x] T006 [US1] Add "Export Encounter" item to the overflow menu in `apps/web/src/components/action-bar.tsx` — wire it to read encounter, undoRedoState, and playerCharacters from contexts, call `assembleExportBundle()`, then `triggerDownload()`. Use a `Download` icon from Lucide.
|
||||
- [x] T007 [US1] Write test for `assembleExportBundle()` in `apps/web/src/__tests__/export-import.test.ts` — verify output shape, version field, timestamp format, and that encounter/stacks/characters are included.
|
||||
|
||||
**Checkpoint**: Export is fully functional. Users can download state as JSON.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: User Story 2 — Import Encounter from File (Priority: P1)
|
||||
|
||||
**Goal**: Users can import a `.json` file and replace the current state.
|
||||
|
||||
**Independent Test**: Export a file, clear the encounter, import the file. Verify the encounter is restored with all combatants, HP, conditions, undo/redo history, and player characters.
|
||||
|
||||
### Implementation for User Story 2
|
||||
|
||||
- [x] T008 [US2] Expose `setEncounter` and `setUndoRedoState` from `useEncounter` hook via `EncounterContext` in `apps/web/src/hooks/use-encounter.ts` and `apps/web/src/contexts/encounter-context.tsx` — these are needed for import to replace state directly (bypassing individual use cases). Also expose a `replacePlayerCharacters` setter from `usePlayerCharacters` hook via `PlayerCharactersContext` in `apps/web/src/hooks/use-player-characters.ts` and `apps/web/src/contexts/player-characters-context.tsx`.
|
||||
- [x] T009 [US2] Create `readImportFile(file: File)` function in `apps/web/src/persistence/export-import.ts` — reads file as text, parses JSON, calls `validateImportUseCase()`, returns validated `ExportBundle` or error string.
|
||||
- [x] T010 [US2] Create `ImportConfirmPrompt` component in `apps/web/src/components/import-confirm-prompt.tsx` — confirmation dialog (using native `<dialog>` element consistent with existing patterns) warning that the current encounter will be replaced. Props: `open`, `onConfirm`, `onCancel`.
|
||||
- [x] T011 [US2] Add "Import Encounter" item to the overflow menu in `apps/web/src/components/action-bar.tsx` — renders a hidden `<input type="file" accept=".json">`, triggers it on menu item click. On file selected: validate via `readImportFile()`, show error toast on failure, show `ImportConfirmPrompt` if encounter is non-empty, replace state on confirm (or directly if encounter is empty). Use an `Upload` icon from Lucide.
|
||||
- [x] T012 [US2] Write round-trip test in `apps/web/src/__tests__/export-import.test.ts` — assemble an export bundle, validate it via the import use case, verify the result matches the original state.
|
||||
|
||||
**Checkpoint**: Import is fully functional. Users can load exported files and restore state.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: User Story 3 — Reject Invalid Import Files (Priority: P2)
|
||||
|
||||
**Goal**: Invalid files are rejected with clear error messages while preserving current state.
|
||||
|
||||
**Independent Test**: Attempt to import various invalid files (non-JSON, wrong structure, malformed combatants). Verify error messages appear and current state is unchanged.
|
||||
|
||||
### Implementation for User Story 3
|
||||
|
||||
- [x] T013 [US3] Add user-facing error toast for import failures in `apps/web/src/components/action-bar.tsx` — use the existing toast/alert pattern in the app. Show specific messages: "Invalid file format" for non-JSON, "Invalid encounter data" for validation failures.
|
||||
- [x] T014 [US3] Write validation edge case tests in `apps/web/src/__tests__/validate-import-bundle.test.ts` — non-JSON text file content, JSON array instead of object, missing version field, version 0 or negative, encounter that fails rehydration, undo stack with mix of valid and invalid entries (valid ones kept, invalid dropped), player characters with invalid color/icon (stripped but character kept). Include a state-preservation test: set up an encounter, attempt import of an invalid file, verify encounter is unchanged after error (FR-009).
|
||||
|
||||
**Checkpoint**: All three stories are complete. Invalid files are handled gracefully.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Polish & Cross-Cutting Concerns
|
||||
|
||||
**Purpose**: Final cleanup and documentation.
|
||||
|
||||
- [x] T015 Update CLAUDE.md spec listing to describe the feature in `CLAUDE.md`
|
||||
- [x] T016 N/A — no project-level README.md exists
|
||||
|
||||
---
|
||||
|
||||
## Dependencies & Execution Order
|
||||
|
||||
### Phase Dependencies
|
||||
|
||||
- **Foundational (Phase 1)**: No dependencies — can start immediately
|
||||
- **US1 Export (Phase 2)**: Depends on Phase 1 (needs ExportBundle type)
|
||||
- **US2 Import (Phase 3)**: Depends on Phase 1 (needs validation use case) and Phase 2 (needs export for round-trip testing)
|
||||
- **US3 Error Handling (Phase 4)**: Depends on Phase 3 (builds on import flow)
|
||||
- **Polish (Phase 5)**: Depends on all stories being complete
|
||||
|
||||
### Within Each Phase
|
||||
|
||||
- Tasks marked [P] can run in parallel
|
||||
- T001 and T002 are parallel (different files)
|
||||
- T004 and T005 are parallel (different functions, same file but independent)
|
||||
- T008 must complete before T011 (setters must exist before import wiring)
|
||||
|
||||
### Parallel Opportunities
|
||||
|
||||
- Phase 1: T001 and T002 can run in parallel (type definition + validation use case)
|
||||
- Phase 2: T004 and T005 can run in parallel (assemble + download functions)
|
||||
- Phase 2: T007 can run in parallel with T006 (test + UI wiring)
|
||||
|
||||
---
|
||||
|
||||
## Implementation Strategy
|
||||
|
||||
### MVP First (Export Only)
|
||||
|
||||
1. Complete Phase 1: ExportBundle type + validation
|
||||
2. Complete Phase 2: Export functionality
|
||||
3. **STOP and VALIDATE**: User can download encounter state as JSON
|
||||
4. Continue to Phase 3: Import functionality
|
||||
5. Continue to Phase 4: Error handling polish
|
||||
|
||||
### Incremental Delivery
|
||||
|
||||
1. Phase 1 → Foundation ready
|
||||
2. Phase 2 → Export works → Delivers backup value
|
||||
3. Phase 3 → Import works → Delivers full round-trip + sharing value
|
||||
4. Phase 4 → Error handling → Production-ready robustness
|
||||
5. Phase 5 → Documentation updated
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- Reuse `rehydrateEncounter()` from `apps/web/src/persistence/encounter-storage.ts` for all encounter validation — do not duplicate
|
||||
- Follow existing file picker pattern from `apps/web/src/components/source-fetch-prompt.tsx`
|
||||
- Follow existing overflow menu pattern in `apps/web/src/components/action-bar.tsx`
|
||||
- Follow existing `<dialog>` pattern from `apps/web/src/components/settings-modal.tsx`
|
||||
- Commit after each phase checkpoint
|
||||
@@ -0,0 +1,36 @@
|
||||
# Specification Quality Checklist: Encounter Difficulty Indicator
|
||||
|
||||
**Purpose**: Validate specification completeness and quality before proceeding to planning
|
||||
**Created**: 2026-03-27
|
||||
**Feature**: [spec.md](../spec.md)
|
||||
|
||||
## Content Quality
|
||||
|
||||
- [x] No implementation details (languages, frameworks, APIs)
|
||||
- [x] Focused on user value and business needs
|
||||
- [x] Written for non-technical stakeholders
|
||||
- [x] All mandatory sections completed
|
||||
|
||||
## Requirement Completeness
|
||||
|
||||
- [x] No [NEEDS CLARIFICATION] markers remain
|
||||
- [x] Requirements are testable and unambiguous
|
||||
- [x] Success criteria are measurable
|
||||
- [x] Success criteria are technology-agnostic (no implementation details)
|
||||
- [x] All acceptance scenarios are defined
|
||||
- [x] Edge cases are identified
|
||||
- [x] Scope is clearly bounded
|
||||
- [x] Dependencies and assumptions identified
|
||||
|
||||
## Feature Readiness
|
||||
|
||||
- [x] All functional requirements have clear acceptance criteria
|
||||
- [x] User scenarios cover primary flows
|
||||
- [x] Feature meets measurable outcomes defined in Success Criteria
|
||||
- [x] No implementation details leak into specification
|
||||
|
||||
## Notes
|
||||
|
||||
- All items pass. Spec is ready for `/speckit.clarify` or `/speckit.plan`.
|
||||
- The spec references `creatureId` and `playerCharacterId` field names — these are domain entity attributes, not implementation details.
|
||||
- Cross-dependency with spec 005 (PlayerCharacter) is documented in FR-011 and Assumptions.
|
||||
@@ -0,0 +1,145 @@
|
||||
# Data Model: Encounter Difficulty Indicator
|
||||
|
||||
**Date**: 2026-03-27 | **Feature**: 008-encounter-difficulty
|
||||
|
||||
## Entities
|
||||
|
||||
### PlayerCharacter (modified)
|
||||
|
||||
Existing entity from spec 005. Adding one optional field.
|
||||
|
||||
| Field | Type | Required | Notes |
|
||||
|-------|------|----------|-------|
|
||||
| id | PlayerCharacterId | yes | Existing — branded string |
|
||||
| name | string | yes | Existing |
|
||||
| ac | number | yes | Existing |
|
||||
| maxHp | number | yes | Existing |
|
||||
| color | PlayerColor | no | Existing |
|
||||
| icon | PlayerIcon | no | Existing |
|
||||
| **level** | **number** | **no** | **NEW — integer 1-20. Used for XP budget calculation. PCs without level are excluded from difficulty calc.** |
|
||||
|
||||
**Validation rules for `level`**:
|
||||
- If provided, must be an integer
|
||||
- If provided, must be >= 1 and <= 20
|
||||
- If omitted/undefined, PC is excluded from difficulty budget
|
||||
|
||||
### DifficultyTier (new)
|
||||
|
||||
Enumeration of encounter difficulty categories.
|
||||
|
||||
| Value | Display Label | Visual |
|
||||
|-------|---------------|--------|
|
||||
| `"trivial"` | Trivial | 3 empty bars |
|
||||
| `"low"` | Low | 1 green bar |
|
||||
| `"moderate"` | Moderate | 2 yellow bars |
|
||||
| `"high"` | High | 3 red bars |
|
||||
|
||||
### DifficultyResult (new)
|
||||
|
||||
Output of the difficulty calculation. Pure data object.
|
||||
|
||||
| Field | Type | Notes |
|
||||
|-------|------|-------|
|
||||
| tier | DifficultyTier | The determined difficulty category |
|
||||
| totalMonsterXp | number | Sum of XP for all bestiary-linked combatants |
|
||||
| partyBudget | { low: number; moderate: number; high: number } | XP thresholds for the party |
|
||||
|
||||
### XP Budget per Character (static lookup)
|
||||
|
||||
Maps character level to XP thresholds. Data from 2024 5.5e DMG.
|
||||
|
||||
| Level | Low | Moderate | High |
|
||||
|-------|-----|----------|------|
|
||||
| 1 | 50 | 75 | 100 |
|
||||
| 2 | 100 | 150 | 200 |
|
||||
| 3 | 150 | 225 | 400 |
|
||||
| 4 | 250 | 375 | 500 |
|
||||
| 5 | 500 | 750 | 1,100 |
|
||||
| 6 | 600 | 1,000 | 1,400 |
|
||||
| 7 | 750 | 1,300 | 1,700 |
|
||||
| 8 | 1,000 | 1,700 | 2,100 |
|
||||
| 9 | 1,300 | 2,000 | 2,600 |
|
||||
| 10 | 1,600 | 2,300 | 3,100 |
|
||||
| 11 | 1,900 | 2,900 | 4,100 |
|
||||
| 12 | 2,200 | 3,700 | 4,700 |
|
||||
| 13 | 2,600 | 4,200 | 5,400 |
|
||||
| 14 | 2,900 | 4,900 | 6,200 |
|
||||
| 15 | 3,300 | 5,400 | 7,800 |
|
||||
| 16 | 3,800 | 6,100 | 9,800 |
|
||||
| 17 | 4,500 | 7,200 | 11,700 |
|
||||
| 18 | 5,000 | 8,700 | 14,200 |
|
||||
| 19 | 5,500 | 10,700 | 17,200 |
|
||||
| 20 | 6,400 | 13,200 | 22,000 |
|
||||
|
||||
### CR-to-XP (static lookup)
|
||||
|
||||
Maps challenge rating strings to XP values. Standard 5e values.
|
||||
|
||||
| CR | XP |
|
||||
|----|-----|
|
||||
| 0 | 0 |
|
||||
| 1/8 | 25 |
|
||||
| 1/4 | 50 |
|
||||
| 1/2 | 100 |
|
||||
| 1 | 200 |
|
||||
| 2 | 450 |
|
||||
| 3 | 700 |
|
||||
| 4 | 1,100 |
|
||||
| 5 | 1,800 |
|
||||
| 6 | 2,300 |
|
||||
| 7 | 2,900 |
|
||||
| 8 | 3,900 |
|
||||
| 9 | 5,000 |
|
||||
| 10 | 5,900 |
|
||||
| 11 | 7,200 |
|
||||
| 12 | 8,400 |
|
||||
| 13 | 10,000 |
|
||||
| 14 | 11,500 |
|
||||
| 15 | 13,000 |
|
||||
| 16 | 15,000 |
|
||||
| 17 | 18,000 |
|
||||
| 18 | 20,000 |
|
||||
| 19 | 22,000 |
|
||||
| 20 | 25,000 |
|
||||
| 21 | 33,000 |
|
||||
| 22 | 41,000 |
|
||||
| 23 | 50,000 |
|
||||
| 24 | 62,000 |
|
||||
| 25 | 75,000 |
|
||||
| 26 | 90,000 |
|
||||
| 27 | 105,000 |
|
||||
| 28 | 120,000 |
|
||||
| 29 | 135,000 |
|
||||
| 30 | 155,000 |
|
||||
|
||||
## Relationships
|
||||
|
||||
```
|
||||
PlayerCharacter (has optional level)
|
||||
│
|
||||
▼ linked via playerCharacterId
|
||||
Combatant (in Encounter)
|
||||
│
|
||||
▼ linked via creatureId
|
||||
Creature (has cr string)
|
||||
│
|
||||
▼ lookup via CR_TO_XP table
|
||||
XP value (number)
|
||||
|
||||
Party levels ──► XP_BUDGET_TABLE ──► { low, moderate, high } thresholds
|
||||
Monster XP total ──► compare against thresholds ──► DifficultyTier
|
||||
```
|
||||
|
||||
## State Transitions
|
||||
|
||||
The difficulty calculation is stateless — it's a pure derivation from current encounter state. No state machine or transitions to model.
|
||||
|
||||
**Input derivation** (at adapter layer):
|
||||
1. For each combatant with `playerCharacterId` → look up `PlayerCharacter.level` → collect non-undefined levels
|
||||
2. For each combatant with `creatureId` → look up `Creature.cr` → collect CR strings
|
||||
3. Pass `(levels[], crs[])` to domain function
|
||||
|
||||
**Pure calculation** (domain layer):
|
||||
1. Sum XP budget per level → `partyBudget.{low, moderate, high}`
|
||||
2. Convert each CR to XP → sum → `totalMonsterXp`
|
||||
3. Compare `totalMonsterXp` against thresholds → `DifficultyTier`
|
||||
@@ -0,0 +1,81 @@
|
||||
# Implementation Plan: Encounter Difficulty Indicator
|
||||
|
||||
**Branch**: `008-encounter-difficulty` | **Date**: 2026-03-27 | **Spec**: [spec.md](spec.md)
|
||||
**Input**: Feature specification from `/specs/008-encounter-difficulty/spec.md`
|
||||
|
||||
## Summary
|
||||
|
||||
Add a live 3-bar encounter difficulty indicator to the top bar, based on the 2024 5.5e XP budget system. The domain layer gains pure lookup tables (CR-to-XP, XP Budget per Character) and a difficulty calculation function. The `PlayerCharacter` type gains an optional `level` field (1-20). The UI renders a compact bar indicator that derives difficulty from encounter combatants, player character levels, and bestiary creature CRs.
|
||||
|
||||
## Technical Context
|
||||
|
||||
**Language/Version**: TypeScript 5.8 (strict mode, `verbatimModuleSyntax`)
|
||||
**Primary Dependencies**: React 19, Vite 6, Tailwind CSS v4, Lucide React (icons)
|
||||
**Storage**: localStorage (encounter + player characters), IndexedDB (bestiary cache)
|
||||
**Testing**: Vitest (v8 coverage)
|
||||
**Target Platform**: Web (mobile-first responsive, desktop side panels)
|
||||
**Project Type**: Web application (monorepo: domain → application → web adapter)
|
||||
**Performance Goals**: Indicator updates within the same render cycle as combatant changes
|
||||
**Constraints**: Offline-capable, local-first, single-user. Max 8 props per component.
|
||||
**Scale/Scope**: Single-page app, ~15 components, 3-layer architecture
|
||||
|
||||
## Constitution Check
|
||||
|
||||
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
|
||||
|
||||
| Principle | Status | Notes |
|
||||
|-----------|--------|-------|
|
||||
| I. Deterministic Domain Core | PASS | Difficulty calculation is a pure function: `(partyLevels, monsterCRs) → DifficultyResult`. No I/O, no randomness, no clocks. Lookup tables are static data. |
|
||||
| II. Layered Architecture | PASS | New domain module (`encounter-difficulty.ts`) has zero imports from application/adapter. UI component composes data from existing contexts. |
|
||||
| II-A. Context-Based State Flow | PASS | Difficulty indicator reads from existing contexts (encounter, player characters, bestiary). No new props beyond what's needed for the component itself. |
|
||||
| III. Clarification-First | PASS | All design decisions resolved in spec: optional level, 3 tiers, 5.5e rules only, no multipliers, hidden when insufficient data. |
|
||||
| IV. Escalation Gates | PASS | Feature scoped to spec. MVP exclusions documented (no custom CR, no 2014 rules, no XP numbers in UI). |
|
||||
| V. MVP Baseline Language | PASS | Exclusions use "MVP baseline does not include" language. |
|
||||
| VI. No Gameplay Rules in Constitution | PASS | XP tables and difficulty rules live in the feature spec, not the constitution. |
|
||||
|
||||
No violations. Complexity Tracking section not needed.
|
||||
|
||||
## Project Structure
|
||||
|
||||
### Documentation (this feature)
|
||||
|
||||
```text
|
||||
specs/008-encounter-difficulty/
|
||||
├── plan.md # This file
|
||||
├── research.md # Phase 0 output
|
||||
├── data-model.md # Phase 1 output
|
||||
├── quickstart.md # Phase 1 output
|
||||
└── tasks.md # Phase 2 output (/speckit.tasks)
|
||||
```
|
||||
|
||||
### Source Code (repository root)
|
||||
|
||||
```text
|
||||
packages/domain/src/
|
||||
├── encounter-difficulty.ts # NEW: CR-to-XP, XP budget tables, difficulty calc
|
||||
├── player-character-types.ts # MODIFY: add optional level field
|
||||
├── create-player-character.ts # MODIFY: add level validation
|
||||
├── edit-player-character.ts # MODIFY: add level validation + apply
|
||||
├── __tests__/
|
||||
│ ├── encounter-difficulty.test.ts # NEW: unit tests for difficulty calc
|
||||
│ ├── create-player-character.test.ts # MODIFY: add level tests
|
||||
│ └── edit-player-character.test.ts # MODIFY: add level tests
|
||||
└── index.ts # MODIFY: export new functions/types
|
||||
|
||||
packages/application/src/
|
||||
├── create-player-character-use-case.ts # MODIFY: pass level through
|
||||
└── edit-player-character-use-case.ts # MODIFY: pass level through
|
||||
|
||||
apps/web/src/
|
||||
├── components/
|
||||
│ ├── difficulty-indicator.tsx # NEW: 3-bar indicator component
|
||||
│ ├── turn-navigation.tsx # MODIFY: add indicator to top bar
|
||||
│ ├── create-player-modal.tsx # MODIFY: add level field
|
||||
│ └── player-character-manager.tsx # MODIFY: show level, pass to edit
|
||||
├── hooks/
|
||||
│ └── use-difficulty.ts # NEW: hook composing contexts → difficulty result
|
||||
└── contexts/
|
||||
└── player-characters-context.tsx # MODIFY: pass level to create/edit
|
||||
```
|
||||
|
||||
**Structure Decision**: Follows existing layered architecture. New domain module for difficulty calculation. New UI component + hook at adapter layer. No new contexts needed — the difficulty hook composes existing contexts.
|
||||
@@ -0,0 +1,67 @@
|
||||
# Quickstart: Encounter Difficulty Indicator
|
||||
|
||||
**Date**: 2026-03-27 | **Feature**: 008-encounter-difficulty
|
||||
|
||||
## Implementation Order
|
||||
|
||||
### Phase 1: Domain — Level field + validation
|
||||
|
||||
1. Add `level?: number` to `PlayerCharacter` in `player-character-types.ts`
|
||||
2. Add level validation to `createPlayerCharacter()` — validate if provided: integer, 1-20
|
||||
3. Add level validation to `editPlayerCharacter()` — same rules in `validateFields()`, apply in `applyFields()`
|
||||
4. Add tests for level validation in existing test files
|
||||
5. Export updated types from `index.ts`
|
||||
|
||||
### Phase 2: Domain — Difficulty calculation
|
||||
|
||||
1. Create `encounter-difficulty.ts` with:
|
||||
- `CR_TO_XP` lookup (Record<string, number>)
|
||||
- `XP_BUDGET_PER_CHARACTER` lookup (Record<number, { low, moderate, high }>)
|
||||
- `crToXp(cr: string): number` — returns 0 for unknown CRs
|
||||
- `calculateEncounterDifficulty(partyLevels: number[], monsterCrs: string[]): DifficultyResult`
|
||||
- `DifficultyTier` type and `DifficultyResult` type
|
||||
2. Add comprehensive unit tests covering:
|
||||
- All CR string formats (0, 1/8, 1/4, 1/2, integers)
|
||||
- All difficulty tiers including trivial
|
||||
- DMG example encounters (from issue comments)
|
||||
- Edge cases: empty arrays, unknown CRs, mixed levels
|
||||
3. Export from `index.ts`
|
||||
|
||||
### Phase 3: Application — Pass level through use cases
|
||||
|
||||
1. Update `CreatePlayerCharacterUseCase` to accept and pass `level`
|
||||
2. Update `EditPlayerCharacterUseCase` to accept and pass `level`
|
||||
|
||||
### Phase 4: Web — Level field in PC forms
|
||||
|
||||
1. Update player characters context to pass `level` in create/edit calls
|
||||
2. Add level input field to create player modal (optional number, 1-20)
|
||||
3. Add level display + edit in player character manager
|
||||
4. Test: create PC with level, edit level, verify persistence
|
||||
|
||||
### Phase 5: Web — Difficulty indicator
|
||||
|
||||
1. Create `useDifficulty()` hook:
|
||||
- Consume encounter context, player characters context, bestiary hook
|
||||
- Map combatants → party levels + monster CRs
|
||||
- Call domain `calculateEncounterDifficulty()`
|
||||
- Return `DifficultyResult | null` (null when insufficient data)
|
||||
2. Create `DifficultyIndicator` component:
|
||||
- Render 3 bars with conditional fill colors
|
||||
- Add `title` attribute for tooltip
|
||||
- Hidden when hook returns null
|
||||
3. Add indicator to `TurnNavigation` component, right of active combatant name
|
||||
4. Test: manual verification with various encounter compositions
|
||||
|
||||
## Key Patterns to Follow
|
||||
|
||||
- **Domain purity**: `calculateEncounterDifficulty` takes `number[]` and `string[]`, not domain types
|
||||
- **Validation pattern**: Follow `color`/`icon` optional field pattern in create/edit
|
||||
- **Hook composition**: `useDifficulty` composes multiple contexts like `useInitiativeRolls`
|
||||
- **Component size**: DifficultyIndicator should be <8 props (likely 0-1, just the result)
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Domain tests** (unit): Exhaustive coverage of `calculateEncounterDifficulty` and `crToXp` with table-driven tests. Cover all 34 CR values, all 20 levels, and the DMG example encounters.
|
||||
- **Domain tests** (level validation): Test create/edit with valid levels, invalid levels, and undefined level.
|
||||
- **Integration**: Verify indicator appears/hides correctly through component rendering (if existing test patterns support this).
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user