Guest User

store.ts

a guest
Mar 8th, 2026
75
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { persist } from "zustand/middleware";
  2. import { immer } from "zustand/middleware/immer";
  3. import { EncounterStored, EntityInstance, EntityStored } from "./types";
  4. import { StatblockType } from "./schema";
  5. import { create } from "zustand";
  6.  
  7. type storeDataType = {
  8.   current_encounter: EncounterStored;
  9. };
  10.  
  11. type storeActions = {
  12.   add_monster: (entity_id: string, statblock: StatblockType) => void;
  13.   remove_monster: (entity_id: string, instance_id: string) => void;
  14. };
  15.  
  16. export type storeType = storeDataType & storeActions;
  17.  
  18. export const UseEncounterStore = create<storeType>()(
  19.   persist(
  20.     immer((set) => ({
  21.       current_encounter: {
  22.         entities: [],
  23.       },
  24.  
  25.       add_monster: (entity_id, statblock) =>
  26.         set((state) => {
  27.           const existingEntity = state.current_encounter.entities.find(
  28.             (e) => e.entity_id === entity_id,
  29.           );
  30.  
  31.           const newInstance: EntityInstance = {
  32.             instance_id: crypto.randomUUID(),
  33.             current_hp: statblock.hit_points,
  34.             initiative: 0,
  35.             entity_id: entity_id,
  36.           };
  37.  
  38.           if (existingEntity) {
  39.             existingEntity.instances.push(newInstance);
  40.           } else {
  41.             state.current_encounter.entities.push({
  42.               entity_id,
  43.               statblock,
  44.               instances: [newInstance],
  45.             });
  46.           }
  47.         }),
  48.  
  49.       remove_monster: (entity_id, instance_id) =>
  50.         set((state) => {
  51.           const entityIndex = state.current_encounter.entities.findIndex(
  52.             (e) => e.entity_id === entity_id,
  53.           );
  54.  
  55.           if (entityIndex === -1) return;
  56.  
  57.           const entity = state.current_encounter.entities[entityIndex];
  58.           entity.instances = entity.instances.filter(
  59.             (i) => i.instance_id !== instance_id,
  60.           );
  61.  
  62.           if (entity.instances.length === 0) {
  63.             state.current_encounter.entities.splice(entityIndex, 1);
  64.           }
  65.         }),
  66.     })),
  67.     { name: "encounterData" },
  68.   ),
  69. );
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment