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

ShellCommandBlock.tsx

64 lines2.1 KB

1import {
2 commandHighlightLanguage,
3 withVisibleControlCharacters,
4} from "@t3tools/client-runtime/work-log/command-label";
5import { Suspense, use } from "react";
6​
7import { useRenderedAppearance } 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​
13let embeddedScriptsModule:
14 | Promise<typeof import("@t3tools/client-runtime/work-log/embedded-scripts")>
15 | undefined;
16function loadEmbeddedScripts() {
17 embeddedScriptsModule ??= import("@t3tools/client-runtime/work-log/embedded-scripts");
18 return embeddedScriptsModule;
20​
21// Match highlighted layout to prevent reflow when the grammar arrives.
22function PlainWords({ code }: { code: string }) {
23 return code.split(/(\s+)/u).map((part, index) =>
24 index % 2 === 1 || part === "" ? (
25 part
26 ) : (
27 // oxlint-disable-next-line react/no-array-index-key -- positions are stable for one string
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 const embedded = language === "shellscript" ? embeddedScripts(code) : [];
39 return (
40 <HighlightedTokens
41 code={code}
42 language={language}
43 embedded={embedded}
44 theme={theme}
45 wordClassName={WORD_CLASS_NAME}
46 />
47 );
49​
50export function ShellCommandBlock({ command }: { command: string }) {
51 const resolvedTheme = useRenderedAppearance();
52 const code = withVisibleControlCharacters(command.trim());
53 if (!code) return null;
54 const plain = <PlainWords code={code} />;
55 return (
56 <div className="text-foreground/85">
57 <RenderErrorBoundary fallback={plain} resetKeys={[code]}>
58 <Suspense fallback={plain}>
59 <HighlightedCommand code={code} theme={resolvedTheme} />
60 </Suspense>
61 </RenderErrorBoundary>
62 </div>
63 );