Open History to see the last commit
1import {
2 commandHighlightLanguage,
3 withVisibleControlCharacters,
4} from "@t3tools/client-runtime/work-log/command-label";
5import { Suspense, use, useMemo } 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;
18}
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 );
33}
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 = useMemo(
40 () => (language === "shellscript" ? embeddedScripts(code) : []),
41 [code, embeddedScripts, language],
42 );
43 return (
44 <HighlightedTokens
45 code={code}
46 language={language}
47 embedded={embedded}
48 theme={theme}
49 wordClassName={WORD_CLASS_NAME}
50 />
51 );
52}
53
54export function ShellCommandBlock({ command }: { command: string }) {
55 const { resolvedTheme } = useTheme();
56 const code = withVisibleControlCharacters(command.trim());
57 if (!code) return null;
58 const plain = <PlainWords code={code} />;
59 return (
60 <div className="text-foreground/85">
61 <RenderErrorBoundary fallback={plain} resetKeys={[code]}>
62 <Suspense fallback={plain}>
63 <HighlightedCommand code={code} theme={resolvedTheme} />
64 </Suspense>
65 </RenderErrorBoundary>
66 </div>
67 );
68}