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

ShellCommandBlock.tsx

62 lines2.0 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: Promise<typeof import("../../lib/embeddedScripts")> | undefined;
14function loadEmbeddedScripts() {
15 embeddedScriptsModule ??= import("../../lib/embeddedScripts");
16 return embeddedScriptsModule;
18​
19// Match highlighted layout to prevent reflow when the grammar arrives.
20function PlainWords({ code }: { code: string }) {
21 return code.split(/(\s+)/u).map((part, index) =>
22 index % 2 === 1 || part === "" ? (
23 part
24 ) : (
25 // oxlint-disable-next-line react/no-array-index-key -- positions are stable for one string
26 <span key={index} className={WORD_CLASS_NAME}>
27 {part}
28 </span>
29 ),
30 );
32​
33function HighlightedCommand({ code, theme }: { code: string; theme: "light" | "dark" }) {
34 const { embeddedScripts } = use(loadEmbeddedScripts());
35 const language = commandHighlightLanguage(code);
36 const embedded = language === "shellscript" ? embeddedScripts(code) : [];
37 return (
38 <HighlightedTokens
39 code={code}
40 language={language}
41 embedded={embedded}
42 theme={theme}
43 wordClassName={WORD_CLASS_NAME}
44 />
45 );
47​
48export function ShellCommandBlock({ command }: { command: string }) {
49 const resolvedTheme = useRenderedAppearance();
50 const code = withVisibleControlCharacters(command.trim());
51 if (!code) return null;
52 const plain = <PlainWords code={code} />;
53 return (
54 <div className="text-foreground/85">
55 <RenderErrorBoundary fallback={plain} resetKeys={[code]}>
56 <Suspense fallback={plain}>
57 <HighlightedCommand code={code} theme={resolvedTheme} />
58 </Suspense>
59 </RenderErrorBoundary>
60 </div>
61 );