All files / client/src/hooks use-editor-commands.ts

82.75% Statements 72/87
76.74% Branches 33/43
100% Functions 13/13
86.74% Lines 72/83

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                                                                                                    15x   15x   5x 5x 1x 1x   4x 4x 4x                     15x 2x 2x 1x 1x   1x 1x           15x 1x 1x       1x 1x           15x 1x 1x       1x 1x           15x 3x 3x 1x 1x   2x 2x 2x 2x       2x 2x   1x       15x   3x 3x 1x 1x   2x 3x 3x 3x   1x           15x 1x   1x     1x     1x     1x 1x 1x 1x 1x 1x 1x 1x   1x     1x     1x 1x     1x 1x     15x 2x 1x 1x 1x                  
import { useCallback } from "react";
import type { RefObject } from "react";
import type { ToastFn } from "@/hooks/use-toast";
 
/**
 * Monaco Editor imperative API surface exposed via ref forwarding.
 * Provides direct access to editor commands and state operations.
 * Methods are optional since the actual ref implementation may only expose a subset.
 */
interface EditorAPI {
  undo?: () => void;
  redo?: () => void;
  find?: () => void;
  selectAll?: () => void;
  copy?: () => void;
  cut?: () => void;
  paste?: () => void;
  goToLine?: (lineNumber: number) => void;
  getValue?: () => string;
  insertSuggestionSmartly?: (suggestion: string, line?: number) => void;
}
 
interface EditorCommandsOptions {
  toast?: ToastFn;
  suppressAutoStopOnce?: () => void;
  code?: string;
  setCode?: React.Dispatch<React.SetStateAction<string>>;
}
 
interface EditorCommandsAPI {
  undo: () => void;
  redo: () => void;
  find: () => void;
  selectAll: () => void;
 
  copy: () => void;
  cut: () => void;
  paste: () => void;
  goToLine: () => void;
 
  insertSuggestion: (suggestion: string, line?: number) => void;
 
  // always provided (may no-op if formatting not possible)
  formatCode: () => void;
}
 
export function useEditorCommands(
  editorRef: RefObject<EditorAPI>,
  opts: EditorCommandsOptions = {},
): EditorCommandsAPI {
  const { toast, suppressAutoStopOnce, code, setCode } = opts;
 
  const runCmd = useCallback(
    (cmd: "undo" | "redo" | "find" | "selectAll") => {
      const ed = editorRef.current;
      if (!ed) {
        toast?.({ title: "No active editor", description: "Open the main editor first." });
        return;
      }
      if (typeof ed[cmd] === "function") {
        try {
          ed[cmd]();
        } catch (err) {
          console.error("Editor command failed", err);
        }
      } else E{
        toast?.({ title: "Command not available", description: `Editor does not support ${cmd}.` });
      }
    },
    [editorRef, toast],
  );
 
  const copy = useCallback(() => {
    const ed = editorRef.current;
    if (!ed || typeof ed.copy !== "function") {
      toast?.({ title: "Command not available", description: "Copy not supported." });
      return;
    }
    try {
      ed.copy();
    } catch (err) {
      console.error("Copy failed", err);
    }
  }, [editorRef, toast]);
 
  const cut = useCallback(() => {
    const ed = editorRef.current;
    Iif (!ed || typeof ed.cut !== "function") {
      toast?.({ title: "Command not available", description: "Cut not supported." });
      return;
    }
    try {
      ed.cut();
    } catch (err) {
      console.error("Cut failed", err);
    }
  }, [editorRef, toast]);
 
  const paste = useCallback(() => {
    const ed = editorRef.current;
    Iif (!ed || typeof ed.paste !== "function") {
      toast?.({ title: "Command not available", description: "Paste not supported." });
      return;
    }
    try {
      ed.paste();
    } catch (err) {
      console.error("Paste failed", err);
    }
  }, [editorRef, toast]);
 
  const goToLine = useCallback(() => {
    const ed = editorRef.current;
    if (!ed || typeof ed.goToLine !== "function") {
      toast?.({ title: "Command not available", description: "Go to line not supported." });
      return;
    }
    const input = prompt("Go to line number:");
    Iif (!input) return;
    const num = Number(input);
    Iif (!Number.isFinite(num) || num <= 0) {
      toast?.({ title: "Invalid line number", description: "Please enter a positive number." });
      return;
    }
    try {
      ed.goToLine(num);
    } catch (err) {
      console.error("Go to line failed", err);
    }
  }, [editorRef, toast]);
 
  const insertSuggestion = useCallback(
    (suggestion: string, line?: number) => {
      const ed = editorRef.current;
      if (!ed || typeof ed.insertSuggestionSmartly !== "function") {
        console.error("insertSuggestionSmartly method not available on editor");
        return;
      }
      suppressAutoStopOnce?.();
      try {
        ed.insertSuggestionSmartly(suggestion, line);
        toast?.({ title: "Suggestion inserted", description: "Code added" });
      } catch (err) {
        console.error(err);
      }
    },
    [editorRef, toast, suppressAutoStopOnce],
  );
 
  const formatCode = useCallback(() => {
    Iif (typeof code !== "string" || !setCode) return;
    // original formatting logic copied verbatim
    let formatted = code;
 
    // 1. replace tabs with spaces
    formatted = formatted.replaceAll("\t", "  ");
 
    // 2. collapse multiple spaces into two
    formatted = formatted.replaceAll(/ {2,}/g, "  ");
 
    // 3. indent blocks (very naive)
    const lines = formatted.split("\n");
    let indentLevel = 0;
    const indentedLines = lines.map((ln) => {
      const trimmed = ln.trim();
      Iif (trimmed.endsWith("}") && indentLevel > 0) indentLevel--;
      const result = "  ".repeat(indentLevel) + trimmed;
      Iif (trimmed.endsWith("{")) indentLevel++;
      return result;
    });
    formatted = indentedLines.join("\n");
 
    // 5. Remove multiple consecutive blank lines
    formatted = formatted.replaceAll(/\n{3,}/g, "\n\n");
 
    // 6. Ensure newline at end of file
    Eif (!formatted.endsWith("\n")) {
      formatted += "\n";
    }
 
    setCode(formatted);
    toast?.({ title: "Code Formatted", description: "Code has been automatically formatted" });
  }, [code, setCode, toast]);
 
  return {
    undo: () => runCmd("undo"),
    redo: () => runCmd("redo"),
    find: () => runCmd("find"),
    selectAll: () => runCmd("selectAll"),
    copy,
    cut,
    paste,
    goToLine,
    insertSuggestion,
    formatCode,
  };
}