Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { persist } from "zustand/middleware";
- import { immer } from "zustand/middleware/immer";
- import { EncounterStored, EntityInstance, EntityStored } from "./types";
- import { StatblockType } from "./schema";
- import { create } from "zustand";
- type storeDataType = {
- current_encounter: EncounterStored;
- };
- type storeActions = {
- add_monster: (entity_id: string, statblock: StatblockType) => void;
- remove_monster: (entity_id: string, instance_id: string) => void;
- };
- export type storeType = storeDataType & storeActions;
- export const UseEncounterStore = create<storeType>()(
- persist(
- immer((set) => ({
- current_encounter: {
- entities: [],
- },
- add_monster: (entity_id, statblock) =>
- set((state) => {
- const existingEntity = state.current_encounter.entities.find(
- (e) => e.entity_id === entity_id,
- );
- const newInstance: EntityInstance = {
- instance_id: crypto.randomUUID(),
- current_hp: statblock.hit_points,
- initiative: 0,
- entity_id: entity_id,
- };
- if (existingEntity) {
- existingEntity.instances.push(newInstance);
- } else {
- state.current_encounter.entities.push({
- entity_id,
- statblock,
- instances: [newInstance],
- });
- }
- }),
- remove_monster: (entity_id, instance_id) =>
- set((state) => {
- const entityIndex = state.current_encounter.entities.findIndex(
- (e) => e.entity_id === entity_id,
- );
- if (entityIndex === -1) return;
- const entity = state.current_encounter.entities[entityIndex];
- entity.instances = entity.instances.filter(
- (i) => i.instance_id !== instance_id,
- );
- if (entity.instances.length === 0) {
- state.current_encounter.entities.splice(entityIndex, 1);
- }
- }),
- })),
- { name: "encounterData" },
- ),
- );
Advertisement