// Solutions.tsx import React, { useState, useEffect, useRef } from "react" import { useQuery, useQueryClient } from "@tanstack/react-query" import { Prism as SyntaxHighlighter } from "react-syntax-highlighter" import { dracula } from "react-syntax-highlighter/dist/esm/styles/prism" import ScreenshotQueue from "../components/Queue/ScreenshotQueue" import { ProblemStatementData } from "../types/solutions" import SolutionCommands from "../components/Solutions/SolutionCommands" import Debug from "./Debug" import { useToast } from "../contexts/toast" import { COMMAND_KEY } from "../utils/platform" export const ContentSection = ({ title, content, isLoading }: { title: string content: React.ReactNode isLoading: boolean }) => (

{title}

{isLoading ? (

Extracting problem statement...

) : (
{content}
)}
) const SolutionSection = ({ title, content, isLoading, currentLanguage }: { title: string content: React.ReactNode isLoading: boolean currentLanguage: string }) => (

{title}

{isLoading ? (

Loading solutions...

) : (
{content as string}
)}
) export const ComplexitySection = ({ timeComplexity, spaceComplexity, isLoading }: { timeComplexity: string | null spaceComplexity: string | null isLoading: boolean }) => { // Helper to ensure we have proper complexity values const formatComplexity = (complexity: string | null): string => { if (!complexity) return "O(n) - Linear time/space complexity"; // Return the complexity as is if it already has Big O notation if (complexity.match(/O\([^)]+\)/i)) { return complexity; } // Otherwise, add a default Big O return `O(n) - ${complexity}`; }; const formattedTimeComplexity = formatComplexity(timeComplexity); const formattedSpaceComplexity = formatComplexity(spaceComplexity); return (

Complexity

{isLoading ? (

Calculating complexity...

) : (
Time: {formattedTimeComplexity}
Space: {formattedSpaceComplexity}
)}
); } export interface SolutionsProps { setView: (view: "queue" | "solutions" | "debug") => void credits: number currentLanguage: string setLanguage: (language: string) => void } const Solutions: React.FC = ({ setView, credits, currentLanguage, setLanguage }) => { const queryClient = useQueryClient() const contentRef = useRef(null) const [debugProcessing, setDebugProcessing] = useState(false) const [problemStatementData, setProblemStatementData] = useState(null) const [solutionData, setSolutionData] = useState(null) const [thoughtsData, setThoughtsData] = useState(null) const [timeComplexityData, setTimeComplexityData] = useState( null ) const [spaceComplexityData, setSpaceComplexityData] = useState( null ) const [isTooltipVisible, setIsTooltipVisible] = useState(false) const [tooltipHeight, setTooltipHeight] = useState(0) const [isResetting, setIsResetting] = useState(false) interface Screenshot { id: string path: string preview: string timestamp: number } const [extraScreenshots, setExtraScreenshots] = useState([]) useEffect(() => { const fetchScreenshots = async () => { try { const existing = await window.electronAPI.getScreenshots() console.log("Raw screenshot data:", existing) const screenshots = (Array.isArray(existing) ? existing : []).map( (p) => ({ id: p.path, path: p.path, preview: p.preview, timestamp: Date.now() }) ) console.log("Processed screenshots:", screenshots) setExtraScreenshots(screenshots) } catch (error) { console.error("Error loading extra screenshots:", error) setExtraScreenshots([]) } } fetchScreenshots() }, [solutionData]) const { showToast } = useToast() useEffect(() => { // Height update logic const updateDimensions = () => { if (contentRef.current) { let contentHeight = contentRef.current.scrollHeight const contentWidth = contentRef.current.scrollWidth if (isTooltipVisible) { contentHeight += tooltipHeight } window.electronAPI.updateContentDimensions({ width: contentWidth, height: contentHeight }) } } // Initialize resize observer const resizeObserver = new ResizeObserver(updateDimensions) if (contentRef.current) { resizeObserver.observe(contentRef.current) } updateDimensions() // Set up event listeners const cleanupFunctions = [ window.electronAPI.onScreenshotTaken(async () => { try { const existing = await window.electronAPI.getScreenshots() const screenshots = (Array.isArray(existing) ? existing : []).map( (p) => ({ id: p.path, path: p.path, preview: p.preview, timestamp: Date.now() }) ) setExtraScreenshots(screenshots) } catch (error) { console.error("Error loading extra screenshots:", error) } }), window.electronAPI.onResetView(() => { // Set resetting state first setIsResetting(true) // Remove queries queryClient.removeQueries({ queryKey: ["solution"] }) queryClient.removeQueries({ queryKey: ["new_solution"] }) // Reset screenshots setExtraScreenshots([]) // After a small delay, clear the resetting state setTimeout(() => { setIsResetting(false) }, 0) }), window.electronAPI.onSolutionStart(() => { // Every time processing starts, reset relevant states setSolutionData(null) setThoughtsData(null) setTimeComplexityData(null) setSpaceComplexityData(null) }), window.electronAPI.onProblemExtracted((data) => { queryClient.setQueryData(["problem_statement"], data) }), //if there was an error processing the initial solution window.electronAPI.onSolutionError((error: string) => { showToast("Processing Failed", error, "error") // Reset solutions in the cache (even though this shouldn't ever happen) and complexities to previous states const solution = queryClient.getQueryData(["solution"]) as { code: string thoughts: string[] time_complexity: string space_complexity: string } | null if (!solution) { setView("queue") } setSolutionData(solution?.code || null) setThoughtsData(solution?.thoughts || null) setTimeComplexityData(solution?.time_complexity || null) setSpaceComplexityData(solution?.space_complexity || null) console.error("Processing error:", error) }), //when the initial solution is generated, we'll set the solution data to that window.electronAPI.onSolutionSuccess((data) => { if (!data) { console.warn("Received empty or invalid solution data") return } console.log({ data }) const solutionData = { code: data.code, thoughts: data.thoughts, time_complexity: data.time_complexity, space_complexity: data.space_complexity } queryClient.setQueryData(["solution"], solutionData) setSolutionData(solutionData.code || null) setThoughtsData(solutionData.thoughts || null) setTimeComplexityData(solutionData.time_complexity || null) setSpaceComplexityData(solutionData.space_complexity || null) // Fetch latest screenshots when solution is successful const fetchScreenshots = async () => { try { const existing = await window.electronAPI.getScreenshots() const screenshots = existing.previews?.map((p) => ({ id: p.path, path: p.path, preview: p.preview, timestamp: Date.now() })) || [] setExtraScreenshots(screenshots) } catch (error) { console.error("Error loading extra screenshots:", error) setExtraScreenshots([]) } } fetchScreenshots() }), //######################################################## //DEBUG EVENTS //######################################################## window.electronAPI.onDebugStart(() => { //we'll set the debug processing state to true and use that to render a little loader setDebugProcessing(true) }), //the first time debugging works, we'll set the view to debug and populate the cache with the data window.electronAPI.onDebugSuccess((data) => { queryClient.setQueryData(["new_solution"], data) setDebugProcessing(false) }), //when there was an error in the initial debugging, we'll show a toast and stop the little generating pulsing thing. window.electronAPI.onDebugError(() => { showToast( "Processing Failed", "There was an error debugging your code.", "error" ) setDebugProcessing(false) }), window.electronAPI.onProcessingNoScreenshots(() => { showToast( "No Screenshots", "There are no extra screenshots to process.", "neutral" ) }), // Removed out of credits handler - unlimited credits in this version ] return () => { resizeObserver.disconnect() cleanupFunctions.forEach((cleanup) => cleanup()) } }, [isTooltipVisible, tooltipHeight]) useEffect(() => { setProblemStatementData( queryClient.getQueryData(["problem_statement"]) || null ) setSolutionData(queryClient.getQueryData(["solution"]) || null) const unsubscribe = queryClient.getQueryCache().subscribe((event) => { if (event?.query.queryKey[0] === "problem_statement") { setProblemStatementData( queryClient.getQueryData(["problem_statement"]) || null ) } if (event?.query.queryKey[0] === "solution") { const solution = queryClient.getQueryData(["solution"]) as { code: string thoughts: string[] time_complexity: string space_complexity: string } | null setSolutionData(solution?.code ?? null) setThoughtsData(solution?.thoughts ?? null) setTimeComplexityData(solution?.time_complexity ?? null) setSpaceComplexityData(solution?.space_complexity ?? null) } }) return () => unsubscribe() }, [queryClient]) const handleTooltipVisibilityChange = (visible: boolean, height: number) => { setIsTooltipVisible(visible) setTooltipHeight(height) } const handleDeleteExtraScreenshot = async (index: number) => { const screenshotToDelete = extraScreenshots[index] try { const response = await window.electronAPI.deleteScreenshot( screenshotToDelete.path ) if (response.success) { // Fetch and update screenshots after successful deletion const existing = await window.electronAPI.getScreenshots() const screenshots = (Array.isArray(existing) ? existing : []).map( (p) => ({ id: p.path, path: p.path, preview: p.preview, timestamp: Date.now() }) ) setExtraScreenshots(screenshots) } else { console.error("Failed to delete extra screenshot:", response.error) showToast("Error", "Failed to delete the screenshot", "error") } } catch (error) { console.error("Error deleting extra screenshot:", error) showToast("Error", "Failed to delete the screenshot", "error") } } return ( <> {!isResetting && queryClient.getQueryData(["new_solution"]) ? ( ) : (
{/* Conditionally render the screenshot queue if solutionData is available */} {solutionData && (
)} {/* Navbar of commands with the SolutionsHelper */} {/* Main Content - Modified width constraints */}
{!solutionData && ( <> {problemStatementData && (

Generating solutions...

)} )} {solutionData && ( <>
{thoughtsData.map((thought, index) => (
{thought}
))}
) } isLoading={!thoughtsData} /> )}
)} ) } export default Solutions