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

32.96% Statements 30/91
4.54% Branches 2/44
36.84% Functions 7/19
32.14% Lines 27/84

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                                                          1x           1x                 1x 1x 1x 1x   1x 1x     1x                                                               1x                       1x                                                                                             1x   1x 1x                 1x     1x                         1x           15x   1x 1x 1x     1x                                                                 1x 1x                                               1x 6x   6x                
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;
    if (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 (typeof window !== "undefined" && typeof window.requestAnimationFrame === "function") {
    rafId = window.requestAnimationFrame(flush);
  } else {
    rafId = window.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;
};
 
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];
    if (!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,
      };
    } else if (stateType === "pwm") {
      states[existingIndex] = {
        ...existing,
        value,
        type: "pwm",
      };
    }
    return;
  }
 
  states.push({
    pin,
    mode: stateType === "mode" ? modeMap[value] || "INPUT" : "OUTPUT",
    value: stateType === "value" || stateType === "pwm" ? value : 0,
    type:
      stateType === "pwm"
        ? "pwm"
        : pin >= 14 && pin <= 19
          ? "analog"
          : "digital",
  });
  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);
};
 
export 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 = JSON.parse(JSON.stringify(initialSnapshot));
    pendingEvents.clear();
    if (rafId !== null) {
      cancelAnimationFrame(rafId);
      rafId = null;
    }
    notify();
  },
};
 
// DEBUG: Export for E2E tests to inspect and reset store state
Eif (typeof window !== "undefined") {
  (window 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,
  };
};