Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ShellCommandBlock.tsx

65 lines2.2 KB

1import {
2 commandHighlightLanguage,
3 withVisibleControlCharacters,
4} from "@t3tools/client-runtime/work-log/command-label";
5import { Suspense, use } from "react";
6​
7import { useTheme } from "../../hooks/useTheme";
8import { RenderErrorBoundary } from "../RenderErrorBoundary";
9import { HighlightedTokens } from "./HighlightedTokens";
10​
11const WORD_CLASS_NAME = "inline-block max-w-full [overflow-wrap:anywhere]";
12​
13// The shell parser loads with the first expanded command, not with the timeline.
14let embeddedScriptsModule: Promise<typeof import("../../lib/embeddedScripts")> | undefined;
15function loadEmbeddedScripts() {
16 embeddedScriptsModule ??= import("../../lib/embeddedScripts");
17 return embeddedScriptsModule;
19​
20/** Same layout as the highlighted version, so the grammar arriving never reflows the block. */
21function PlainWords({ code }: { code: string }) {
22 return code.split(/(\s+)/u).map((part, index) =>
23 index % 2 === 1 || part === "" ? (
24 part
25 ) : (
26 // Positions are stable for a given string, which is all this renders.
27 // oxlint-disable-next-line react/no-array-index-key
28 <span key={index} className={WORD_CLASS_NAME}>
29 {part}
30 </span>
31 ),
32 );
34​
35function HighlightedCommand({ code, theme }: { code: string; theme: "light" | "dark" }) {
36 const { embeddedScripts } = use(loadEmbeddedScripts());
37 const language = commandHighlightLanguage(code);
38 // Only shell syntax nests scripts; PowerShell's own grammar colors its strings.
39 const embedded = language === "shellscript" ? embeddedScripts(code) : [];
40 return (
41 <HighlightedTokens
42 code={code}
43 language={language}
44 embedded={embedded}
45 theme={theme}
46 wordClassName={WORD_CLASS_NAME}
47 />
48 );
50​
51export function ShellCommandBlock({ command }: { command: string }) {
52 const { resolvedTheme } = useTheme();
53 const code = withVisibleControlCharacters(command.trim());
54 if (!code) return null;
55 const plain = <PlainWords code={code} />;
56 return (
57 <div className="text-foreground/85">
58 <RenderErrorBoundary fallback={plain} resetKeys={[code]}>
59 <Suspense fallback={plain}>
60 <HighlightedCommand code={code} theme={resolvedTheme} />
61 </Suspense>
62 </RenderErrorBoundary>
63 </div>
64 );