File size: 10,975 Bytes
9176e00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import { useEffect, useMemo, useRef } from "react";

import { Badge } from "@/components/ui/badge";

export type CodeFileName = "index.html" | "styles.css" | "script.js";

interface CodeStreamPanelProps {
  streamedHtml: string;
  activeFile: CodeFileName;
  onActiveFileChange: (next: CodeFileName) => void;
  generationLoading: boolean;
  generationStatus?: string | null;
  generationLogs: string[];
  generationError?: string | null;
}

const FILE_ORDER: CodeFileName[] = ["index.html", "styles.css", "script.js"];

type HighlightTokenType =
  | "plain"
  | "comment"
  | "keyword"
  | "string"
  | "number"
  | "property"
  | "tag";

interface HighlightSegment {
  text: string;
  type: HighlightTokenType;
}

const TOKEN_CLASS: Record<HighlightTokenType, string> = {
  plain: "text-[#c9d1d9]",
  comment: "text-[#8b949e]",
  keyword: "text-[#ff7b72]",
  string: "text-[#a5d6ff]",
  number: "text-[#79c0ff]",
  property: "text-[#d2a8ff]",
  tag: "text-[#7ee787]",
};

function tokenizeCode(
  code: string,
  pattern: RegExp,
  classify: (token: string) => HighlightSegment[],
): HighlightSegment[] {
  const segments: HighlightSegment[] = [];
  let lastIndex = 0;

  for (const match of code.matchAll(pattern)) {
    const matchIndex = match.index ?? 0;
    const token = match[0] ?? "";

    if (matchIndex > lastIndex) {
      segments.push({
        text: code.slice(lastIndex, matchIndex),
        type: "plain",
      });
    }

    segments.push(...classify(token));
    lastIndex = matchIndex + token.length;
  }

  if (lastIndex < code.length) {
    segments.push({
      text: code.slice(lastIndex),
      type: "plain",
    });
  }

  return segments;
}

function highlightHtmlTag(tagToken: string): HighlightSegment[] {
  const segments: HighlightSegment[] = [];
  let lastIndex = 0;

  for (const match of tagToken.matchAll(/"[^"]*"|'[^']*'/g)) {
    const matchIndex = match.index ?? 0;
    const token = match[0] ?? "";

    if (matchIndex > lastIndex) {
      segments.push({
        text: tagToken.slice(lastIndex, matchIndex),
        type: "tag",
      });
    }

    segments.push({
      text: token,
      type: "string",
    });
    lastIndex = matchIndex + token.length;
  }

  if (lastIndex < tagToken.length) {
    segments.push({
      text: tagToken.slice(lastIndex),
      type: "tag",
    });
  }

  return segments;
}

function highlightHtml(code: string): HighlightSegment[] {
  return tokenizeCode(
    code,
    /<!--[\s\S]*?-->|<\/?[a-zA-Z!][^>]*>/g,
    (token): HighlightSegment[] => {
      if (token.startsWith("<!--")) {
        return [{ text: token, type: "comment" }];
      }

      return highlightHtmlTag(token);
    },
  );
}

function highlightCss(code: string): HighlightSegment[] {
  return tokenizeCode(
    code,
    /\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|#[\da-fA-F]{3,8}\b|\b(?:@media|@keyframes|@supports|from|to)\b|[a-zA-Z-]+(?=\s*:)|\b\d+(?:\.\d+)?(?:px|rem|em|vh|vw|%|s|ms)?\b/g,
    (token): HighlightSegment[] => {
      if (token.startsWith("/*")) {
        return [{ text: token, type: "comment" }];
      }

      if (token.startsWith('"') || token.startsWith("'")) {
        return [{ text: token, type: "string" }];
      }

      if (token.startsWith("@")) {
        return [{ text: token, type: "keyword" }];
      }

      if (/^[a-zA-Z-]+$/.test(token)) {
        return [{ text: token, type: "property" }];
      }

      if (/^#/.test(token) || /^\d/.test(token)) {
        return [{ text: token, type: "number" }];
      }

      return [{ text: token, type: "plain" }];
    },
  );
}

function highlightJavaScript(code: string): HighlightSegment[] {
  const jsKeywordPattern =
    /^(?:const|let|var|function|return|if|else|for|while|switch|case|break|continue|class|new|try|catch|finally|throw|await|async|import|from|export|default|typeof|instanceof)$/;

  return tokenizeCode(
    code,
    /\/\/.*|\/\*[\s\S]*?\*\/|`(?:\\.|[^`\\])*`|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\b(?:const|let|var|function|return|if|else|for|while|switch|case|break|continue|class|new|try|catch|finally|throw|await|async|import|from|export|default|typeof|instanceof)\b|\b\d+(?:\.\d+)?\b/g,
    (token): HighlightSegment[] => {
      if (token.startsWith("//") || token.startsWith("/*")) {
        return [{ text: token, type: "comment" }];
      }

      if (token.startsWith('"') || token.startsWith("'") || token.startsWith("`")) {
        return [{ text: token, type: "string" }];
      }

      if (jsKeywordPattern.test(token)) {
        return [{ text: token, type: "keyword" }];
      }

      if (/^\d/.test(token)) {
        return [{ text: token, type: "number" }];
      }

      return [{ text: token, type: "plain" }];
    },
  );
}

function highlightCode(file: CodeFileName, code: string): HighlightSegment[] {
  if (file === "styles.css") {
    return highlightCss(code);
  }

  if (file === "script.js") {
    return highlightJavaScript(code);
  }

  return highlightHtml(code);
}

function splitSegmentsByLine(segments: HighlightSegment[]): HighlightSegment[][] {
  const lines: HighlightSegment[][] = [[]];

  for (const segment of segments) {
    const rawText = segment.text;
    if (!rawText) {
      continue;
    }

    const parts = rawText.split("\n");
    parts.forEach((part, index) => {
      if (part.length > 0) {
        lines[lines.length - 1]?.push({
          text: part,
          type: segment.type,
        });
      }

      if (index < parts.length - 1) {
        lines.push([]);
      }
    });
  }

  return lines;
}

function extractStyleCode(html: string): string {
  const blocks = [...html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)];
  return blocks.map((block) => block[1]?.trim() ?? "").filter(Boolean).join("\n\n");
}

function extractInlineScriptCode(html: string): string {
  const blocks = [
    ...html.matchAll(/<script\b(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi),
  ];
  return blocks.map((block) => block[1]?.trim() ?? "").filter(Boolean).join("\n\n");
}

function getDisplayCode(file: CodeFileName, html: string): string {
  if (file === "styles.css") {
    return extractStyleCode(html);
  }

  if (file === "script.js") {
    return extractInlineScriptCode(html);
  }

  return html;
}

function getEmptyState(file: CodeFileName): string {
  if (file === "styles.css") {
    return "No closed <style> blocks streamed yet.";
  }

  if (file === "script.js") {
    return "No closed inline <script> blocks streamed yet.";
  }

  return "Streaming output will appear here.";
}

export function CodeStreamPanel({
  streamedHtml,
  activeFile,
  onActiveFileChange,
  generationLoading,
  generationStatus,
  generationLogs,
  generationError,
}: CodeStreamPanelProps) {
  const scrollContainerRef = useRef<HTMLDivElement | null>(null);
  const displayCode = getDisplayCode(activeFile, streamedHtml).trim();
  const showPlaceholder = displayCode.length === 0;
  const highlightedCode = useMemo(
    () => highlightCode(activeFile, displayCode),
    [activeFile, displayCode],
  );
  const highlightedLines = useMemo(
    () => splitSegmentsByLine(highlightedCode),
    [highlightedCode],
  );
  const lineNumberWidth = useMemo(
    () => Math.max(2, String(highlightedLines.length).length),
    [highlightedLines.length],
  );

  useEffect(() => {
    if (!generationLoading || showPlaceholder) {
      return;
    }

    const container = scrollContainerRef.current;
    if (!container) {
      return;
    }

    container.scrollTop = container.scrollHeight;
  }, [displayCode, generationLoading, showPlaceholder]);

  return (
    <div className="flex h-full min-h-[62vh] flex-col lg:min-h-0">
      <div className="flex flex-wrap items-center justify-between gap-3 border-b border-border bg-sidebar px-4 py-2">
        <div className="inline-flex rounded-lg bg-muted p-0.5">
          {FILE_ORDER.map((file) => {
            const isActive = activeFile === file;
            return (
              <button
                key={file}
                type="button"
                onClick={() => onActiveFileChange(file)}
                className={`rounded-md px-3 py-1 text-xs font-medium transition-colors ${
                  isActive
                    ? "bg-background text-foreground shadow-sm"
                    : "text-muted-foreground hover:text-foreground"
                }`}
              >
                {file}
              </button>
            );
          })}
        </div>

        <div className="flex items-center gap-2">
          {generationLoading ? <Badge variant="default">streaming</Badge> : null}
          {generationError ? <Badge variant="destructive">error</Badge> : null}
          {generationStatus ? (
            <p className="text-xs text-muted-foreground">{generationStatus}</p>
          ) : null}
        </div>
      </div>

      <div
        ref={scrollContainerRef}
        data-testid="code-stream-scroll"
        className="min-h-0 flex-1 overflow-auto bg-[#0d1117] dark:bg-[#0d1117]"
      >
        <div className="min-h-full px-4 py-4 font-mono text-xs leading-6 text-[#c9d1d9]">
          {showPlaceholder ? (
            <span className="text-[#484f58]">{getEmptyState(activeFile)}</span>
          ) : (
            <div className="min-w-full whitespace-pre-wrap">
              {highlightedLines.map((lineSegments, lineIndex) => (
                <div
                  key={`line-${lineIndex + 1}`}
                  className="grid grid-cols-[auto_1fr] gap-4"
                >
                  <span
                    data-testid="code-line-number"
                    className="select-none text-right text-[#6e7681]"
                    style={{ minWidth: `${lineNumberWidth}ch` }}
                  >
                    {lineIndex + 1}
                  </span>
                  <span className="whitespace-pre-wrap">
                    {lineSegments.length === 0 ? "\u00A0" : null}
                    {lineSegments.map((segment, segmentIndex) => (
                      <span
                        key={`${lineIndex + 1}-${segment.type}-${segmentIndex}`}
                        className={TOKEN_CLASS[segment.type]}
                      >
                        {segment.text}
                      </span>
                    ))}
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="border-t border-border bg-sidebar px-4 py-2.5">
        <p className="mb-1.5 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
          Activity
        </p>
        {generationLogs.length === 0 ? (
          <p className="text-xs text-muted-foreground/50">No events yet.</p>
        ) : (
          <ul className="space-y-0.5 font-mono text-[11px] text-muted-foreground">
            {generationLogs.map((entry, index) => (
              <li key={`${entry}-${index}`}>{entry}</li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}