# All files / src/components/features/python-runner PythonOutput.tsx

0% Statements 0/252
0% Branches 0/1
0% Functions 0/1
0% Lines 0/252

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

     'use client'

    import { useState, useEffect, useCallback } from 'react'
    import { motion } from 'framer-motion'
    import { Play, CircleNotch, ArrowClockwise, Warning } from '@phosphor-icons/react'
    import { Button } from '@/components/ui/button'
    import { Card } from '@/components/ui/card'
    import { runPythonCode, getPyodide, isPyodideReady, getPyodideError, resetPyodide } from '@/lib/pyodide-runner'
    import { PythonTerminal } from '@/components/features/python-runner/PythonTerminal'
    import { toast } from 'sonner'

    interface PythonOutputProps {
      code: string
    }

    export function PythonOutput({ code }: PythonOutputProps) {
      const [output, setOutput] = useState<string>('')
      const [error, setError] = useState<string>('')
      const [isRunning, setIsRunning] = useState(false)
      const [isInitializing, setIsInitializing] = useState(!isPyodideReady())
      const [initError, setInitError] = useState<string | null>(null)
      const [hasInput, setHasInput] = useState(false)

      const initializePyodide = useCallback(async () => {
        setIsInitializing(true)
        setInitError(null)

        try {
          await getPyodide()
          setIsInitializing(false)
          toast.success('Python environment ready!')
        } catch (err) {
          setIsInitializing(false)
          const errorMsg = err instanceof Error ? err.message : String(err)
          setInitError(errorMsg)
          toast.error('Failed to load Python environment')
          console.error(err)
        }
      }, [])

      const handleRetry = useCallback(() => {
        resetPyodide()
        setOutput('')
        setError('')
        setInitError(null)
        initializePyodide()
      }, [initializePyodide])

      useEffect(() => {
        // Check for existing initialization error
        const existingError = getPyodideError()
        if (existingError) {
          setInitError(existingError.message)
          setIsInitializing(false)
          return
        }

        if (!isPyodideReady()) {
          initializePyodide()
        }
      }, [initializePyodide])

      useEffect(() => {
        const hasInputCall = /\binput\s*\(/i.test(code)
        setHasInput(hasInputCall)
      }, [code])

      const statusTone = initError
        ? 'border-destructive/30 bg-destructive/10 text-destructive'
        : isInitializing
          ? 'border-border bg-primary/5 text-primary'
          : 'border-primary/30 bg-primary/10 text-primary'

      const statusLabel = initError
        ? 'Init failed'
        : isInitializing
          ? 'Loading'
          : 'Ready'

      const handleRun = async () => {
        if (initError) {
          toast.error('Python environment failed to start. Retry to load it again.')
          return
        }

        if (isInitializing) {
          toast.info('Python environment is still loading...')
          return
        }

        setIsRunning(true)
        setOutput('')
        setError('')

        try {
          const result = await runPythonCode(code)
          setOutput(result.output || '')
          if (result.error) {
            setError(result.error)
          }
        } catch (err) {
          setError(err instanceof Error ? err.message : String(err))
        } finally {
          setIsRunning(false)
        }
      }

      if (hasInput) {
        return <PythonTerminal code={code} />
      }

      return (
        <div className="flex flex-col h-full bg-card">
          <div className="flex items-center justify-between p-4 border-b border-border bg-muted/30">
            <div className="flex items-center gap-2">
              <h3 className="text-sm font-semibold text-foreground">Python Output</h3>
              <span
                className={`flex items-center gap-2 rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-wide ${statusTone}`}
              >
                <span
                  className={`size-2.5 rounded-full ${initError ? 'bg-destructive' : 'bg-primary'}`}
                />
                {statusLabel}
              </span>
            </div>
            <div className="flex items-center gap-2">
              {initError && (
                <Button
                  onClick={handleRetry}
                  size="sm"
                  variant="tonal"
                  className="gap-2"
                >
                  <ArrowClockwise size={16} />
                  Retry
                </Button>
              )}
              <Button
                onClick={handleRun}
                disabled={isRunning || isInitializing || Boolean(initError)}
                size="sm"
                className="gap-2"
              >
                {isRunning || isInitializing ? (
                  <>
                    <CircleNotch className="animate-spin" size={16} />
                    {isInitializing ? 'Loading...' : 'Running...'}
                  </>
                ) : (
                  <>
                    <Play size={16} weight="fill" />
                    Run
                  </>
                )}
              </Button>
            </div>
          </div>

          <div className="flex-1 overflow-auto p-4 space-y-4">
            {isInitializing && (
              <Card className="p-4 border border-border/60">
                <div className="flex items-start gap-3 text-sm text-foreground">
                  <div className="mt-1 rounded-full bg-primary/10 p-2 text-primary">
                    <CircleNotch className="animate-spin" size={18} />
                  </div>
                  <div className="space-y-1">
                    <p className="font-semibold">Preparing Python environment</p>
                    <p className="text-muted-foreground">
                      This takes a few seconds the first time while Pyodide downloads.
                    </p>
                  </div>
                </div>
              </Card>
            )}

            {initError && (
              <Card
                className="p-4 border-destructive/40 bg-destructive/5"
              >
                <div className="flex items-start gap-3">
                  <div className="mt-1 rounded-full bg-destructive/10 p-2 text-destructive">
                    <Warning size={18} weight="fill" />
                  </div>
                  <div className="space-y-3">
                    <div className="space-y-1">
                      <p className="text-sm font-semibold text-destructive">Python environment failed to start</p>
                      <p className="text-sm text-muted-foreground">{initError}</p>
                    </div>
                    <div className="flex flex-wrap gap-2">
                      <Button
                        size="sm"
                        variant="tonal"
                        className="gap-2"
                        onClick={handleRetry}
                      >
                        <ArrowClockwise size={16} />
                        Retry loading
                      </Button>
                      <Button
                        size="sm"
                        variant="text"
                        onClick={() => toast.info('Check your network connection or disable blockers that may block Pyodide.')}
                      >
                        Troubleshoot
                      </Button>
                    </div>
                  </div>
                </div>
              </Card>
            )}

            {!isInitializing && !initError && !output && !error && (
              <div className="flex items-center justify-center h-full text-muted-foreground text-sm">
                Click "Run" to execute the Python code
              </div>
            )}

            {!isInitializing && !initError && output && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.2 }}
              >
                <Card className="p-4 bg-background">
                  <pre className="text-sm font-mono whitespace-pre-wrap text-foreground">
                    {output}
                  </pre>
                </Card>
              </motion.div>
            )}

            {error && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.2 }}
                className="mt-4"
              >
                <Card className="p-4 bg-destructive/10 border-destructive/20">
                  <div className="flex items-start gap-2">
                    <div className="text-destructive font-semibold text-sm">Error:</div>
                    <pre className="text-sm font-mono whitespace-pre-wrap text-destructive flex-1">
                      {error}
                    </pre>
                  </div>
                </Card>
              </motion.div>
            )}
          </div>
        </div>
      )
    }