All files / client/src/hooks use-ui-feedback-adapter.ts

98.78% Statements 81/82
91.66% Branches 33/36
100% Functions 30/30
98.78% Lines 81/82

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 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311                                                                                                                                                                                          213x 70x           213x 100x             213x 8x 3x   5x 1x   4x 1x   3x 1x   2x 2x 2x 2x                         213x 18x     213x 8x     213x 5x     213x 3x     213x 19x     213x 4x     213x 2x     213x 2x     213x 2x     213x 5x     213x 2x             213x 26x     213x 18x     213x 8x 8x     213x 8x     213x 4x     213x 4x     213x 22x       22x 10x     22x     213x 2x             213x 9x             213x 19x     213x 9x   9x 2x   3x 3x 3x 3x     7x 6x     9x     213x 6x 16x     6x 6x       6x     213x                                                                        
import type { CompilerError } from "@/types/websocket";
 
export type DebugMessageParams = {
  source: "frontend" | "server";
  type: string;
  data: string;
  protocol?: "websocket" | "http";
};
 
export type SetState<T> = (value: T | ((prev: T) => T)) => void;
 
/**
 * Compilation errors for CLI output - can be array of errors, string, or undefined
 */
export type CompilationErrors = CompilerError[] | string | undefined;
 
export interface UseUiFeedbackAdapterParams {
  // Toast callback
  toast: (args: {
    title: string;
    description?: string;
    variant?: "destructive";
  }) => void;
 
  // Debug message callback
  addDebugMessage: (params: DebugMessageParams) => void;
 
  // Error glitch trigger
  triggerErrorGlitch: () => void;
 
  // CLI Output setter (for pin conflict warnings)
  setCliOutput: SetState<string>;
 
  // Pin conflict state setter
  setPendingPinConflicts: SetState<number[]>;
}
 
export interface UseUiFeedbackAdapterResult {
  // Toast notifications
  showCompileSuccessToast: () => void;
  showCompileErrorToast: () => void;
  showCompilationFailedWithErrorsToast: () => void;
  showNoCodeToast: () => void;
  showSimulationStartedToast: () => void;
  showStartFailedToast: (message: string) => void;
  showCodeModifiedToast: () => void;
  showPauseFailedToast: () => void;
  showResumeFailedToast: () => void;
  showResettingToast: () => void;
  showBackendUnreachableToast: () => void;
 
  // Debug messages
  logCompileRequest: (codeLength: number) => void;
  logCompilationSuccess: () => void;
  logCompilationError: (errors: CompilationErrors) => void;
  logStopSimulation: () => void;
  logPauseSimulation: () => void;
  logResumeSimulation: () => void;
  logStartSimulation: (timeout: number, hasCode: boolean) => void;
  logStartSimulationFallback: () => void;
 
  // Error handling
  triggerCompileErrorGlitch: () => void;
 
  // CLI Output updates
  setCompileSuccessOutput: (output: string | undefined) => void;
  setCompileErrorOutput: (errors: CompilationErrors) => void;
  showPinConflictWarning: (pins: number[]) => void;
 
  // Error message extraction
  extractErrorMessage: (error: unknown) => string;
}
 
/**
 * UI Feedback Adapter - kapselt alle UI-Seiteneffekte
 *
 * Verantwortlichkeiten:
 * ✅ Toast-Benachrichtigungen erzeugen
 * ✅ Debug-Meldungen formatieren und senden
 * ✅ CLI-Output aktualisieren
 * ✅ Error-Glitch auslösen
 * ✅ Pin-Conflict-Warnings anzeigen
 *
 * Keine Verantwortlichkeiten:
 * ❌ Compile-/Simulation-State
 * ❌ WebSocket-Steuerung
 * ❌ Fachliche Entscheidungen
 * ❌ Lifecycle-Management
 */
export function useUiFeedbackAdapter(params: UseUiFeedbackAdapterParams): UseUiFeedbackAdapterResult {
  /**
   * Helper: Toast erzeugen
   */
  const showToast = (title: string, description: string, variant?: "destructive") => {
    params.toast({ title, description, variant: variant ?? undefined });
  };
 
  /**
   * Helper: Debug-Message erzeugen
   */
  const logDebug = (source: "frontend" | "server", type: string, data: string, protocol?: "websocket" | "http") => {
    params.addDebugMessage({ source, type, data, protocol: protocol ?? "http" });
  };
 
  /**
   * Extract error message from unknown error type
   * Safely formats any value without producing [object Object]
   */
  const extractErrorMessage = (error: unknown): string => {
    if (error instanceof Error) {
      return error.message;
    }
    if (typeof error === "string") {
      return error;
    }
    if (error === undefined) {
      return "undefined";
    }
    if (error === null) {
      return "null";
    }
    try {
      const json = JSON.stringify(error, null, 2);
      Eif (json) {
        return json;
      }
    } catch {
      // Ignore JSON stringify errors
    }
    // Fallback: use toString() for primitives, describe for objects
    return Object.prototype.toString.call(error);
  };
 
  // ============================================================
  // Toast notifications (12 Varianten)
  // ============================================================
 
  const showCompileSuccessToast = () => {
    showToast("Arduino-CLI Compilation succeeded", "Your sketch has been compiled successfully");
  };
 
  const showCompileErrorToast = () => {
    showToast("Arduino-CLI Compilation failed", "There were errors in your sketch", "destructive");
  };
 
  const showCompilationFailedWithErrorsToast = () => {
    showToast("Compilation Completed with Errors", "Simulation will not start due to compilation errors.", "destructive");
  };
 
  const showNoCodeToast = () => {
    showToast("No Code", "Please write some code before compiling", "destructive");
  };
 
  const showSimulationStartedToast = () => {
    showToast("Simulation Started", "Arduino simulation is now running");
  };
 
  const showStartFailedToast = (message: string) => {
    showToast("Start Failed", message || "Could not start simulation", "destructive");
  };
 
  const showCodeModifiedToast = () => {
    showToast("Code Modified", "Compile to apply your latest changes");
  };
 
  const showPauseFailedToast = () => {
    showToast("Pause failed", "Could not pause simulation", "destructive");
  };
 
  const showResumeFailedToast = () => {
    showToast("Resume failed", "Could not resume simulation", "destructive");
  };
 
  const showResettingToast = () => {
    showToast("Resetting...", "Recompiling and restarting simulation");
  };
 
  const showBackendUnreachableToast = () => {
    showToast("Backend unreachable", "API server unreachable. Please check the backend or reload.", "destructive");
  };
 
  // ============================================================
  // Debug messages (8 Varianten)
  // ============================================================
 
  const logCompileRequest = (codeLength: number) => {
    logDebug("frontend", "compile_request", JSON.stringify({ endpoint: "POST /api/compile", codeLength }, null, 2));
  };
 
  const logCompilationSuccess = () => {
    logDebug("server", "compile_response", JSON.stringify({ success: true }, null, 2));
  };
 
  const logCompilationError = (errors: CompilerError[] | string | undefined) => {
    logDebug("server", "compilation_error", JSON.stringify({ type: "compilation_error", data: errors }, null, 2));
    logDebug("server", "compile_response", JSON.stringify({ success: false }, null, 2));
  };
 
  const logStopSimulation = () => {
    logDebug("frontend", "stop_simulation", JSON.stringify({ type: "stop_simulation" }, null, 2), "websocket");
  };
 
  const logPauseSimulation = () => {
    logDebug("frontend", "pause_simulation", JSON.stringify({ type: "pause_simulation" }, null, 2), "websocket");
  };
 
  const logResumeSimulation = () => {
    logDebug("frontend", "resume_simulation", JSON.stringify({ type: "resume_simulation" }, null, 2), "websocket");
  };
 
  const logStartSimulation = (timeout: number, hasCode: boolean) => {
    const startMsg: { type: "start_simulation"; timeout: number; code?: string } = {
      type: "start_simulation",
      timeout,
    };
    if (hasCode) {
      startMsg.code = "<code present>";
    }
 
    logDebug("frontend", "start_simulation", JSON.stringify(startMsg, null, 2), "websocket");
  };
 
  const logStartSimulationFallback = () => {
    logDebug("frontend", "start_simulation", "Immediate send failed, falling back to buffered send", "websocket");
  };
 
  // ============================================================
  // Error handling
  // ============================================================
 
  const triggerCompileErrorGlitch = () => {
    params.triggerErrorGlitch();
  };
 
  // ============================================================
  // CLI Output updates
  // ============================================================
 
  const setCompileSuccessOutput = (output: string | undefined) => {
    params.setCliOutput(output || "✓ Arduino-CLI Compilation succeeded.");
  };
 
  const setCompileErrorOutput = (errors: CompilerError[] | string | undefined) => {
    let errText = "";
 
    if (Array.isArray(errors)) {
      errText = errors
        .map((e) => {
          const lineStr = e.line ? `:${e.line}` : "";
          const columnStr = e.column ? `:${e.column}` : "";
          const location = `${e.file}${lineStr}${columnStr}`;
          return `${location} ${e.type}: ${e.message}`;
        })
        .join("\n");
    } else if (typeof errors === "string") {
      errText = errors;
    }
 
    params.setCliOutput(errText || "✗ Arduino-CLI Compilation failed.");
  };
 
  const showPinConflictWarning = (pins: number[]) => {
    const names = pins
      .map((p) => (p >= 14 && p <= 19 ? `A${p - 14}` : `${p}`))
      .join(", ");
 
    params.setCliOutput(
      (prev) =>
        (prev ? prev + "\n\n" : "") +
        `⚠️ Pin usage conflict: Pins used as digital via pinMode(...) and also read with analogRead(): ${names}. This may be unintended.`,
    );
    params.setPendingPinConflicts([]);
  };
 
  return {
    // Toast notifications
    showCompileSuccessToast,
    showCompileErrorToast,
    showCompilationFailedWithErrorsToast,
    showNoCodeToast,
    showSimulationStartedToast,
    showStartFailedToast,
    showCodeModifiedToast,
    showPauseFailedToast,
    showResumeFailedToast,
    showResettingToast,
    showBackendUnreachableToast,
 
    // Debug messages
    logCompileRequest,
    logCompilationSuccess,
    logCompilationError,
    logStopSimulation,
    logPauseSimulation,
    logResumeSimulation,
    logStartSimulation,
    logStartSimulationFallback,
 
    // Error handling
    triggerCompileErrorGlitch,
 
    // CLI Output updates
    setCompileSuccessOutput,
    setCompileErrorOutput,
    showPinConflictWarning,
 
    // Error message extraction
    extractErrorMessage,
  };
}