All files / client/src/hooks useSimulatorSerialPanel.ts

94.11% Statements 16/17
100% Branches 10/10
80% Functions 4/5
100% Lines 15/15

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                                                  14x   14x   5x   4x 2x                     2x       2x   2x 2x         14x   2x 1x           14x 1x     14x            
import { useCallback, type Dispatch, type KeyboardEvent, type SetStateAction } from "react";
 
import type { ToastFn } from "@/hooks/use-toast";
import type { IncomingArduinoMessage } from "@/types/websocket";
import type { SimulationStatus } from "@/hooks/use-simulation-controls";
 
export function useSimulatorSerialPanel(params: {
  sendMessage: (message: IncomingArduinoMessage) => void;
  simulationStatus: SimulationStatus;
  toast: ToastFn;
  setTxActivity: Dispatch<SetStateAction<number>>;
  serialInputValue: string;
  setSerialInputValue: Dispatch<SetStateAction<string>>;
  clearSerialOutput: () => void;
  ensureBackendConnected: (actionLabel: string) => boolean;
}) {
  const {
    sendMessage,
    simulationStatus,
    toast,
    setTxActivity,
    serialInputValue,
    setSerialInputValue,
    clearSerialOutput,
    ensureBackendConnected,
  } = params;
 
  const handleSerialSend = useCallback(
    (message: string) => {
      if (!ensureBackendConnected("Serial senden")) return;
 
      if (simulationStatus !== "running") {
        toast({
          title:
            simulationStatus === "paused"
              ? "Simulation paused"
              : "Simulation not running",
          description:
            simulationStatus === "paused"
              ? "Resume the simulation to send serial input."
              : "Start the simulation to send serial input.",
          variant: "destructive",
        });
        return;
      }
 
      // Trigger TX LED blink when client sends data
      setTxActivity((prev) => prev + 1);
 
      sendMessage({ type: "serial_input", data: message });
      setSerialInputValue("");
    },
    [ensureBackendConnected, simulationStatus, toast, setTxActivity, sendMessage, setSerialInputValue],
  );
 
  const handleSerialInputKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (e.key === "Enter") {
        handleSerialSend(serialInputValue);
      }
    },
    [handleSerialSend, serialInputValue],
  );
 
  const handleClearOutput = useCallback(() => {
    clearSerialOutput();
  }, [clearSerialOutput]);
 
  return {
    handleSerialSend,
    handleSerialInputKeyDown,
    handleClearSerialOutput: handleClearOutput,
  };
}