All files / client/src/hooks use-simulation-store.ts

77.89% Statements 74/95
75% Branches 33/44
76.19% Functions 16/21
78.16% Lines 68/87

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259                                                          2x           2x                 2x 2x 2x 2x   2x 51x     2x 17x   14x 14x 14x   14x 14x 14x 14x   14x 14x                 14x     14x 14x           2x 14x 14x 14x   14x 16x     14x       13x 12x       13x               2x         16x 16x   16x 3x 3x   3x 1x         2x 1x       1x 1x           3x     13x 13x     2x   4x 4x                 4x     2x 17x                 17x     2x 17x 17x 17x     315x   2x 33x 33x     2x                                                                 2x 2x                                               2x 90x   90x                
import { useSyncExternalStore } from "react";
 
type PinMode = "INPUT" | "OUTPUT" | "INPUT_PULLUP";
export type PinStateType = "mode" | "value" | "pwm";
 
export interface PinState {
  pin: number;
  mode: PinMode;
  value: number; // analog: 0-1023, pwm: 0-255, digital: 0 or 1
  type: "digital" | "analog" | "pwm";
}
 
export interface BatchStats {
  lastBatchMs: number;
  lastBatchSize: number;
  lastFrameAt: number;
}
 
interface SimulationStateSnapshot {
  pinStates: PinState[];
  batchStats: BatchStats;
}
 
interface PinEvent {
  pin: number;
  stateType: PinStateType;
  value: number;
}
 
const modeMap: Record<number, PinMode> = {
  0: "INPUT",
  1: "OUTPUT",
  2: "INPUT_PULLUP",
};
 
const initialSnapshot: SimulationStateSnapshot = {
  pinStates: [],
  batchStats: {
    lastBatchMs: 0,
    lastBatchSize: 0,
    lastFrameAt: 0,
  },
};
 
const subscribers = new Set<() => void>();
const pendingEvents = new Map<string, PinEvent>();
let snapshot: SimulationStateSnapshot = initialSnapshot;
let rafId: number | null = null;
 
const notify = () => {
  subscribers.forEach((fn) => fn());
};
 
const scheduleFlush = () => {
  if (rafId !== null) return;
 
  const flush = () => {
    rafId = null;
    Iif (pendingEvents.size === 0) return;
 
    const events = Array.from(pendingEvents.values());
    const start = performance.now();
    const nextStates = applyEvents(snapshot.pinStates, events);
    pendingEvents.clear();
 
    const end = performance.now();
    snapshot = {
      pinStates: nextStates,
      batchStats: {
        lastBatchMs: Math.max(0, end - start),
        lastBatchSize: events.length,
        lastFrameAt: Date.now(),
      },
    };
 
    notify();
  };
 
  if (globalThis.window !== undefined && typeof globalThis.requestAnimationFrame === "function") {
    rafId = globalThis.requestAnimationFrame(flush);
  } else E{
    rafId = globalThis.setTimeout(flush, 16) as unknown as number;
  }
};
 
const applyEvents = (current: PinState[], events: PinEvent[]): PinState[] => {
  const nextStates = current.slice();
  const indexByPin = new Map<number, number>();
  nextStates.forEach((state, index) => indexByPin.set(state.pin, index));
 
  for (const event of events) {
    applyEventToState(nextStates, indexByPin, event);
  }
 
  return nextStates;
};
 
function getPinType(pin: number, stateType: PinStateType): "digital" | "analog" | "pwm" {
  if (stateType === "pwm") return "pwm";
  return pin >= 14 && pin <= 19 ? "analog" : "digital";
}
 
function buildNewPinState(pin: number, stateType: PinStateType, value: number): PinState {
  return {
    pin,
    mode: stateType === "mode" ? modeMap[value] || "INPUT" : "OUTPUT",
    value: stateType === "value" || stateType === "pwm" ? value : 0,
    type: getPinType(pin, stateType),
  };
}
 
const applyEventToState = (
  states: PinState[],
  indexByPin: Map<number, number>,
  event: PinEvent,
) => {
  const { pin, stateType, value } = event;
  const existingIndex = indexByPin.get(pin);
 
  if (existingIndex !== undefined) {
    const existing = states[existingIndex];
    Iif (!existing) return;
 
    if (stateType === "mode") {
      states[existingIndex] = {
        ...existing,
        mode: modeMap[value] || "INPUT",
        type: existing.type === "analog" ? "digital" : existing.type,
      };
    } else if (stateType === "value") {
      states[existingIndex] = {
        ...existing,
        value,
      };
    E} else if (stateType === "pwm") {
      states[existingIndex] = {
        ...existing,
        value,
        type: "pwm",
      };
    }
    return;
  }
 
  states.push(buildNewPinState(pin, stateType, value));
  indexByPin.set(pin, states.length - 1);
};
 
const setPinStates = (updater: PinState[] | ((prev: PinState[]) => PinState[])) => {
  const nextStates =
    typeof updater === "function" ? updater(snapshot.pinStates) : updater;
  snapshot = {
    pinStates: nextStates,
    batchStats: {
      ...snapshot.batchStats,
      lastBatchMs: 0,
      lastBatchSize: 0,
      lastFrameAt: Date.now(),
    },
  };
  notify();
};
 
const resetPinStates = () => {
  snapshot = {
    pinStates: [],
    batchStats: {
      ...snapshot.batchStats,
      lastBatchMs: 0,
      lastBatchSize: 0,
      lastFrameAt: Date.now(),
    },
  };
  notify();
};
 
const enqueuePinEvent = (pin: number, stateType: PinStateType, value: number) => {
  const key = `${pin}:${stateType}`;
  pendingEvents.set(key, { pin, stateType, value });
  scheduleFlush();
};
 
const getSnapshot = (): SimulationStateSnapshot => snapshot;
 
const subscribe = (callback: () => void) => {
  subscribers.add(callback);
  return () => subscribers.delete(callback);
};
 
const simulationStore = {
  subscribe,
  getSnapshot,
  setPinStates,
  resetPinStates,
  enqueuePinEvent,
  resetToInitial: () => {
    // IMPORTANT: Only clear pending events and RAF, preserve loaded pin states
    // Pin states from WebSocket should persist between tests
    // Only pending/unprocessed events should be cleared
    pendingEvents.clear();
    if (rafId !== null) {
      cancelAnimationFrame(rafId);
      rafId = null;
    }
    // DONT reset snapshot - preserve loaded pin states from WebSocket
    notify();
  },
  /**
   * Hard reset for complete state wipe (rarely needed)
   */
  resetToEmpty: () => {
    snapshot = structuredClone(initialSnapshot);
    pendingEvents.clear();
    if (rafId !== null) {
      cancelAnimationFrame(rafId);
      rafId = null;
    }
    notify();
  },
};
 
// DEBUG: Export for E2E tests to inspect and reset store state
Eif (globalThis.window !== undefined) {
  (globalThis as any).__SIM_DEBUG__ = {
    getState: () => snapshot,
    resetToInitial: () => {
      simulationStore.resetToInitial();
    },
    /**
     * Reset all stores to initial state (for test isolation)
     * Call this from E2E tests before each test to ensure clean state
     */
    resetAllStores: async () => {
      // Reset simulation store
      simulationStore.resetToInitial();
      
      // Reset telemetry store (lazy import to avoid circular dependencies)
      try {
        const { telemetryStore } = await import('./use-telemetry-store');
        telemetryStore.resetToInitial();
      } catch (err) {
        console.warn('[SIM_DEBUG] Could not reset telemetry store:', err);
      }
    },
  };
}
 
export const useSimulationStore = () => {
  const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
 
  return {
    pinStates: state.pinStates,
    batchStats: state.batchStats,
    setPinStates,
    resetPinStates,
    enqueuePinEvent,
  };
};