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

98.93% Statements 93/94
97.56% Branches 40/41
100% Functions 35/35
98.9% Lines 90/91

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 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336                                  4x 7x 6x 7x 4x 7x     4x 3x     1x                                                                                                                                                                                 322x 71x           322x 174x             322x 8x 3x   5x 1x   4x 1x   3x 1x   2x 2x 2x 2x                         322x 34x     322x 8x     322x 5x     322x 4x     322x 1x     322x 4x     322x 2x     322x 2x     322x 2x     322x 7x     322x 2x             322x 57x     322x 34x     322x 8x 8x     322x 19x     322x 4x     322x 4x     322x 38x       38x 24x     38x     322x 2x             322x 9x             322x 35x     322x 10x   10x 3x   4x 4x 4x 4x     7x 6x     10x     322x 6x 16x     6x 6x       6x     322x                                                                        
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;
 
function formatCompilerDiagnosticMessage(message: string): string {
  const memoryLinePattern = /(?=data section exceeds available space|Sketch uses\b|Der Sketch verwendet\b|Global variables use\b|Globale Variablen verwenden\b)/gi;
  const lines = message.split(memoryLinePattern).map((line) => line.trim()).filter(Boolean);
  const flashLine = lines.find((line) => /^(?:Sketch uses|Der Sketch verwendet)\b/i.test(line));
  const sramLine = lines.find((line) => /^(?:Global variables use|Globale Variablen verwenden)\b/i.test(line));
  const memoryLines = lines.filter((line) =>
    /^(?:Not enough memory|data section exceeds available space|Memory usage exceeds)/i.test(line),
  );
 
  if (!flashLine || !sramLine || memoryLines.length === 0) {
    return message;
  }
 
  return [
    "Memory error:",
    memoryLines.join("\n"),
    "",
    "Flash usage:",
    flashLine,
    "",
    "SRAM usage:",
    sramLine,
  ].join("\n");
}
 
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}: ${formatCompilerDiagnosticMessage(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,
  };
}