@devries-cameron20 / t3code Mirror · read-only / commits / 5f0a0d1c2f
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 20:45 UTC

refactor(web): chat markdown code blocks live in their own module (#22690)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 21, 2026 at 01:32 UTC 5f0a0d1c2f84271714f6bdf7919703b62e3325fe
5 files changed +537 -504
apps/web/src/components/ChatMarkdown.tsx
+12 -503
@@ -3,7 +3,6 @@ import { MarkdownFindContext, findRevealRef } from "./chat/markdownFindContext";
3 import {
4 buildFileLinkParentSuffixByPath,
5 fileLinkLabel,
6 - resolvePathLinkTarget,
6 splitFilePathPosition,
7 } from "@t3tools/shared/fileLinks";
8 import {
@@ -39,12 +38,10 @@ import {
38 MessageSquareIcon,
39 MessageSquareWarningIcon,
40 OctagonAlertIcon,
42 - PlayIcon,
41 PresentationIcon,
42 SparklesIcon,
43 TriangleAlertIcon,
44 WorkflowIcon,
47 - WrapTextIcon,
45 type LucideIcon,
46 } from "lucide-react";
47 import { Check, Copy, Maximize2, Minimize2 } from "lucide";
@@ -105,7 +102,6 @@ import type {
102 Options as ReactMarkdownOptions,
103 } from "react-markdown";
104 import ReactMarkdown from "react-markdown";
108 -import { toHtml } from "hast-util-to-html";
105 import { createIncrementalMarkdownPlugin } from "../markdown-incremental";
106 import { defaultUrlTransform } from "react-markdown";
107 import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations";
@@ -132,7 +128,6 @@ import { MediaActions, type MediaActionSource } from "./media/MediaActions";
128 import { resolveProtocolRelativeMediaUrl } from "./media/mediaContent";
129 import { WorkspaceEntryTooltip } from "./chat/WorkspaceEntryIcon";
130 import { FileTagChipContent } from "./chat/FileTagChip";
135 -import { PierreEntryIcon } from "./chat/PierreEntryIcon";
131 import {
132 revealInFileExplorerLabelForKind,
133 revealInFileExplorerLabelForOs,
@@ -141,7 +136,6 @@ import {
136 resolveExternalWebLinkHost,
137 showExternalLinkContextMenu,
138 } from "./chat/externalLinkContextMenu";
144 -import { hasSpecificPierreIconForFileName, syntheticFileNameForLanguageId } from "../pierre-icons";
139 import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
140 import { Button } from "./ui/button";
141 import { MorphIcon } from "~/components/MorphIcon";
@@ -157,13 +151,8 @@ import {
151 usePreferredEditor,
152 } from "../editorPreferences";
153 import { openInEditorMenuLabel } from "../editorLabels";
160 -import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
161 -import { fnv1a32 } from "../lib/diffRendering";
162 -import { LRUCache } from "../lib/lruCache";
163 -import { getSyntaxHighlighterPromise } from "../lib/syntaxHighlighting";
154 +import { resolveDiffThemeName } from "../lib/diffRendering";
155 import { GitHubIcon } from "./Icons";
165 -import { createIncrementalHighlightedDocument } from "../lib/incrementalHighlighting";
166 -import { HighlightedCodeLines } from "./chat/HighlightedCodeLines";
156 import { RenderErrorBoundary } from "./RenderErrorBoundary";
157 import { MermaidDiagram } from "./chat/MermaidDiagram";
158 import { useRenderedAppearance } from "../hooks/useTheme";
@@ -239,6 +228,16 @@ import {
228 } from "../browser/openFileInPreview";
229 import { resolveLinkTarget } from "../browser/browserLinkTarget";
230 import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview";
231 +import { MarkdownCodeBlock, SuspenseShikiCodeBlock } from "./chat/MarkdownCodeBlock";
232 +import {
233 + extractCodeBlock,
234 + extractFenceLanguage,
235 + extractFenceTitle,
236 + extractPreCodeMeta,
237 + isClosedCodeFence,
238 + nodeToPlainText,
239 +} from "./chat/MarkdownCodeBlock.logic";
240 +import { reportMarkdownActionFailure } from "./chat/markdownActionFailure";
241
242 const isAssetNotFoundError = Schema.is(AssetWorkspaceAssetNotFoundError);
243
@@ -392,28 +391,7 @@ function CodexArtifactTemplateCard(props: {
391 );
392 }
393
395 -const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
394 const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
397 -const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
398 -const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
399 -
400 -interface MarkdownActionFailureContext {
401 - readonly operation: string;
402 - readonly target?: string;
403 - readonly format?: "markdown" | "csv";
404 - readonly language?: string;
405 - readonly fenceTitle?: string;
406 - readonly copyTarget?: string;
407 -}
408 -
409 -function reportMarkdownActionFailure(context: MarkdownActionFailureContext, cause: unknown): void {
410 - console.error("[chat-markdown] action failed", context, cause);
411 -}
412 -
413 -const highlightedCodeCache = new LRUCache<string>(
414 - MAX_HIGHLIGHT_CACHE_ENTRIES,
415 - MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
416 -);
395
396 function findTaskListMarkerOffset(markdown: string, listItemStart: number): number | null {
397 const firstLineEnd = markdown.indexOf("\n", listItemStart);
@@ -474,119 +452,6 @@ const GITHUB_ALERT_PRESENTATIONS: Record<
452 },
453 };
454
477 -function extractFenceLanguage(className: string | undefined): string {
478 - const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
479 - const raw = match?.[1] ?? "text";
480 - // Shiki doesn't bundle a gitignore grammar; ini is a close match (#685)
481 - return raw === "gitignore" ? "ini" : raw;
482 -}
483 -
484 -const FENCE_TITLE_ATTR_REGEX = /(?:^|\s)(?:title|file(?:name)?)=(?:"([^"]+)"|'([^']+)'|(\S+))/i;
485 -const FENCE_FILENAME_TOKEN_REGEX = /^[\w@][\w@./-]*\.[A-Za-z0-9]+$/;
486 -
487 -function extractFenceTitle(meta: string | undefined): string | null {
488 - if (!meta) return null;
489 - const attrMatch = FENCE_TITLE_ATTR_REGEX.exec(meta);
490 - const attrTitle = attrMatch?.[1] ?? attrMatch?.[2] ?? attrMatch?.[3];
491 - if (attrTitle) return attrTitle;
492 - return meta.split(/\s+/).find((candidate) => FENCE_FILENAME_TOKEN_REGEX.test(candidate)) ?? null;
493 -}
494 -
495 -function extractPreCodeMeta(node: unknown): string | undefined {
496 - const children = (
497 - node as
498 - | {
499 - children?: Array<{
500 - type?: string;
501 - tagName?: string;
502 - data?: { meta?: unknown };
503 - properties?: { dataCodeMeta?: unknown };
504 - }>;
505 - }
506 - | undefined
507 - )?.children;
508 - const codeNode = children?.find((child) => child?.type === "element" && child.tagName === "code");
509 - const meta = codeNode?.properties?.dataCodeMeta ?? codeNode?.data?.meta;
510 - return typeof meta === "string" && meta.trim().length > 0 ? meta.trim() : undefined;
511 -}
512 -
513 -function isClosedCodeFence(
514 - node: ReactMarkdownExtraProps["node"],
515 - text: string,
516 - code: string,
517 -): boolean {
518 - const start = node?.position?.start.offset;
519 - const end = node?.position?.end.offset;
520 - if (start === undefined || end === undefined) return false;
521 - const source = text.slice(start, end);
522 - const opening = /^(?:`{3,}|~{3,})/.exec(source)?.[0];
523 - // One class for the blockquote prefix: nested quantifiers here backtrack
524 - // exponentially on code lines that start with many `> ` markers.
525 - const closing = /(?:^|\n)[ \t>]*(`{3,}|~{3,})[ \t\r]*$/.exec(source)?.[1];
526 - return (
527 - opening !== undefined &&
528 - closing !== undefined &&
529 - opening[0] === closing[0] &&
530 - closing.length >= opening.length &&
531 - // Only a real closer is omitted from parsed code. A CRLF stream cut after
532 - // CR must not count as an extra source line.
533 - source.replace(/\r$/, "").split(/\r\n|\r|\n/).length > code.split(/\r\n|\r|\n/).length
534 - );
535 -}
536 -
537 -function nodeToPlainText(node: ReactNode): string {
538 - if (typeof node === "string" || typeof node === "number") {
539 - return String(node);
540 - }
541 - if (Array.isArray(node)) {
542 - return node.map((child) => nodeToPlainText(child)).join("");
543 - }
544 - if (isValidElement<{ children?: ReactNode }>(node)) {
545 - return nodeToPlainText(node.props.children);
546 - }
547 - return "";
548 -}
549 -
550 -function extractCodeBlock(
551 - children: ReactNode,
552 -): { className: string | undefined; code: string } | null {
553 - const childNodes = Children.toArray(children);
554 - if (childNodes.length !== 1) {
555 - return null;
556 - }
557 -
558 - const onlyChild = childNodes[0];
559 - if (
560 - !isValidElement<{ className?: string; children?: ReactNode; node?: { tagName?: string } }>(
561 - onlyChild,
562 - )
563 - ) {
564 - return null;
565 - }
566 - // With a custom `code` component the child's type is that component, not
567 - // the "code" tag — the hast node react-markdown attaches still names it.
568 - if (onlyChild.type !== "code" && onlyChild.props.node?.tagName !== "code") {
569 - return null;
570 - }
571 -
572 - return {
573 - className: onlyChild.props.className,
574 - code: nodeToPlainText(onlyChild.props.children),
575 - };
576 -}
577 -
578 -function createHighlightCacheKey(code: string, language: string, themeName: DiffThemeName): string {
579 - return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
580 -}
581 -
582 -function estimateHighlightedSize(html: string, code: string): number {
583 - return Math.max(html.length * 2, code.length * 3);
584 -}
585 -
586 -function readInitialWordWrapSetting(): boolean {
587 - return getClientSettings().wordWrap;
588 -}
589 -
455 /**
456 * Whether any cell is clipped in the unwrapped layout. Only then does the wrap
457 * toggle change anything, so short tables hide it. Measures with the container
@@ -615,7 +480,7 @@ function tableHasClippedCells(container: HTMLElement, table: HTMLTableElement):
480 function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {
481 const containerRef = useRef<HTMLDivElement | null>(null);
482 const tableRef = useRef<HTMLTableElement | null>(null);
618 - const [expanded, setExpanded] = useState(readInitialWordWrapSetting);
483 + const [expanded, setExpanded] = useState(() => getClientSettings().wordWrap);
484 const [hasClippedCells, setHasClippedCells] = useState(false);
485 const [copied, setCopied] = useState(false);
486 const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -792,261 +657,6 @@ function MarkdownDetails({
657 );
658 }
659
795 -const THREAD_FIND_IGNORE_PROPS = {
796 - "data-thread-find-ignore": "",
797 -} as React.HTMLAttributes<HTMLDivElement>;
798 -
799 -export function MarkdownCodeBlockFrame({
800 - as: Wrapper = "div",
801 - language,
802 - fenceTitle,
803 - theme,
804 - wrapped = true,
805 - title,
806 - actions,
807 - headerProps,
808 - children,
809 -}: {
810 - as?: React.ElementType;
811 - language: string;
812 - fenceTitle: string | null;
813 - theme: "light" | "dark";
814 - wrapped?: boolean;
815 - title?: React.ReactNode;
816 - actions?: React.ReactNode;
817 - headerProps?: React.HTMLAttributes<HTMLDivElement>;
818 - children: React.ReactNode;
819 -}) {
820 - return (
821 - <Wrapper
822 - className="chat-markdown-codeblock my-[0.65rem] overflow-hidden rounded-lg border border-border/70 bg-secondary leading-snug dark:border-transparent dark:bg-input/32"
823 - data-language={language}
824 - data-wrap={wrapped ? "true" : "false"}
825 - >
826 - <div
827 - {...headerProps}
828 - className={cn(
829 - "chat-markdown-codeblock-header flex items-center justify-between gap-2 pt-1.5 pr-1.5 pb-0 pl-3 select-none",
830 - headerProps?.className,
831 - )}
832 - >
833 - {title ?? (
834 - <span className="inline-flex min-w-0 items-center gap-1.5 font-mono text-2xs">
835 - <MarkdownCodeBlockTitleContent
836 - fenceTitle={fenceTitle}
837 - language={language}
838 - theme={theme}
839 - />
840 - </span>
841 - )}
842 - {actions}
843 - </div>
844 - {children}
845 - </Wrapper>
846 - );
847 -}
848 -
849 -function MarkdownCodeBlockTitleContent({
850 - fenceTitle,
851 - language,
852 - theme,
853 -}: {
854 - fenceTitle: string | null;
855 - language: string;
856 - theme: "light" | "dark";
857 -}) {
858 - if (fenceTitle) {
859 - return (
860 - <>
861 - <PierreEntryIcon pathValue={fenceTitle} kind="file" theme={theme} className="size-3.5" />
862 - <span className="truncate">{fenceTitle}</span>
863 - </>
864 - );
865 - }
866 -
867 - const fileName = syntheticFileNameForLanguageId(language);
868 - if (!hasSpecificPierreIconForFileName(fileName)) {
869 - return <span className="truncate">{language}</span>;
870 - }
871 - return (
872 - <Tooltip>
873 - <TooltipTrigger
874 - render={
875 - <span className="inline-flex shrink-0 rounded-sm" aria-label={`Language: ${language}`} />
876 - }
877 - >
878 - <PierreEntryIcon pathValue={fileName} kind="file" theme={theme} className="size-3.5" />
879 - </TooltipTrigger>
880 - <TooltipPopup side="top">{language}</TooltipPopup>
881 - </Tooltip>
882 - );
883 -}
884 -
885 -function MarkdownCodeBlock({
886 - code,
887 - language,
888 - fenceTitle,
889 - theme,
890 - onRunShellCommand,
891 - isStreaming,
892 - viewToggle,
893 - canWrap = true,
894 - diagram = false,
895 - children,
896 -}: {
897 - code: string;
898 - language: string;
899 - fenceTitle: string | null;
900 - theme: "light" | "dark";
901 - onRunShellCommand?: ((command: string) => void) | undefined;
902 - isStreaming: boolean;
903 - viewToggle?: ReactNode;
904 - canWrap?: boolean;
905 - diagram?: boolean;
906 - children: ReactNode;
907 -}) {
908 - const [copied, setCopied] = useState(false);
909 - const [wrapped, setWrapped] = useState(readInitialWordWrapSetting);
910 - const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
911 - const wrapLabel = wrapped ? "Disable line wrap" : "Wrap lines";
912 - const copyLabel = copied ? "Copied" : "Copy code";
913 - const command = code.trim();
914 - const canRun =
915 - onRunShellCommand !== undefined &&
916 - !isStreaming &&
917 - /^(?:sh|bash|zsh|fish|shell|powershell|pwsh)$/.test(language) &&
918 - code.endsWith("\n") &&
919 - command.length > 0 &&
920 - !command.endsWith("\\") &&
921 - // Control and invisible format characters (bidi overrides, zero-width) can
922 - // make the rendered command differ from what the terminal would receive.
923 - !/[\p{Cc}\p{Cf}]/u.test(code.slice(0, -1));
924 -
925 - const handleCopy = () => {
926 - if (typeof navigator === "undefined" || navigator.clipboard == null) {
927 - return;
928 - }
929 - void navigator.clipboard
930 - .writeText(code)
931 - .then(() => {
932 - if (copiedTimerRef.current != null) {
933 - clearTimeout(copiedTimerRef.current);
934 - }
935 - setCopied(true);
936 - copiedTimerRef.current = setTimeout(() => {
937 - setCopied(false);
938 - copiedTimerRef.current = null;
939 - }, 1200);
940 - })
941 - .catch((cause) => {
942 - reportMarkdownActionFailure(
943 - {
944 - operation: "copy-code-block",
945 - language,
946 - ...(fenceTitle ? { fenceTitle } : {}),
947 - },
948 - cause,
949 - );
950 - });
951 - };
952 -
953 - useEffect(
954 - () => () => {
955 - if (copiedTimerRef.current != null) {
956 - clearTimeout(copiedTimerRef.current);
957 - copiedTimerRef.current = null;
958 - }
959 - },
960 - [],
961 - );
962 -
963 - const copyButton = (
964 - <Tooltip>
965 - <TooltipTrigger
966 - render={
967 - <Button
968 - type="button"
969 - variant="ghost-muted"
970 - size="icon-xs"
971 - onClick={handleCopy}
972 - aria-label={copyLabel}
973 - />
974 - }
975 - >
976 - <MorphIcon className="size-3" icon={copied ? Check : Copy} />
977 - </TooltipTrigger>
978 - <TooltipPopup side="top">{copyLabel}</TooltipPopup>
979 - </Tooltip>
980 - );
981 -
982 - if (diagram) {
983 - return (
984 - <div className="my-[0.65rem] border border-transparent" data-language={language}>
985 - <div className="flex items-center justify-end gap-0.5 pt-1.5 pr-1.5 select-none">
986 - {viewToggle}
987 - {copyButton}
988 - </div>
989 - {children}
990 - </div>
991 - );
992 - }
993 -
994 - return (
995 - <MarkdownCodeBlockFrame
996 - language={language}
997 - fenceTitle={fenceTitle}
998 - theme={theme}
999 - wrapped={wrapped}
1000 - headerProps={THREAD_FIND_IGNORE_PROPS}
1001 - actions={
1002 - <span className="flex items-center gap-0.5" role="toolbar" aria-label="Code block actions">
1003 - {canWrap ? (
1004 - <Tooltip>
1005 - <TooltipTrigger
1006 - render={
1007 - <Button
1008 - type="button"
1009 - variant={wrapped ? "secondary" : "ghost-muted"}
1010 - size="icon-xs"
1011 - aria-pressed={wrapped}
1012 - onClick={() => setWrapped((value) => !value)}
1013 - aria-label={wrapLabel}
1014 - />
1015 - }
1016 - >
1017 - <WrapTextIcon className="size-3" />
1018 - </TooltipTrigger>
1019 - <TooltipPopup side="top">{wrapLabel}</TooltipPopup>
1020 - </Tooltip>
1021 - ) : null}
1022 - {canRun ? (
1023 - <Tooltip>
1024 - <TooltipTrigger
1025 - render={
1026 - <Button
1027 - type="button"
1028 - variant="ghost-muted"
1029 - size="icon-xs"
1030 - onClick={() => onRunShellCommand(command)}
1031 - aria-label="Run in terminal"
1032 - />
1033 - }
1034 - >
1035 - <PlayIcon className="size-3" />
1036 - </TooltipTrigger>
1037 - <TooltipPopup side="top">Run in terminal</TooltipPopup>
1038 - </Tooltip>
1039 - ) : null}
1040 - {viewToggle}
1041 - {copyButton}
1042 - </span>
1043 - }
1044 - >
1045 - {children}
1046 - </MarkdownCodeBlockFrame>
1047 - );
1048 -}
1049 -
660 function MarkdownMermaidCodeBlock({
661 code,
662 fenceTitle,
@@ -1122,107 +732,6 @@ function MarkdownMermaidCodeBlock({
732 );
733 }
734
1125 -interface SuspenseShikiCodeBlockProps {
1126 - className: string | undefined;
1127 - code: string;
1128 - themeName: DiffThemeName;
1129 - isStreaming: boolean;
1130 -}
1131 -
1132 -function SuspenseShikiCodeBlock({
1133 - className,
1134 - code,
1135 - themeName,
1136 - isStreaming,
1137 -}: SuspenseShikiCodeBlockProps) {
1138 - const [hasStreamed, setHasStreamed] = useState(isStreaming);
1139 - if (isStreaming && !hasStreamed) setHasStreamed(true);
1140 - const language = extractFenceLanguage(className);
1141 - const cacheKey = createHighlightCacheKey(code, language, themeName);
1142 - // Once lines are mounted individually, keep that renderer when streaming
1143 - // finishes so switching to cached HTML cannot clear an existing selection.
1144 - const cachedHighlightedHtml =
1145 - !isStreaming && !hasStreamed ? highlightedCodeCache.get(cacheKey) : null;
1146 -
1147 - if (cachedHighlightedHtml != null) {
1148 - return (
1149 - <div
1150 - className="chat-markdown-shiki"
1151 - dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
1152 - />
1153 - );
1154 - }
1155 -
1156 - return (
1157 - <UncachedShikiCodeBlock
1158 - code={code}
1159 - language={language}
1160 - themeName={themeName}
1161 - cacheKey={cacheKey}
1162 - isStreaming={isStreaming}
1163 - preserveLines={isStreaming || hasStreamed}
1164 - />
1165 - );
1166 -}
1167 -
1168 -interface UncachedShikiCodeBlockProps {
1169 - code: string;
1170 - language: string;
1171 - themeName: DiffThemeName;
1172 - cacheKey: string;
1173 - isStreaming: boolean;
1174 - preserveLines: boolean;
1175 -}
1176 -
1177 -function UncachedShikiCodeBlock({
1178 - code,
1179 - language,
1180 - themeName,
1181 - cacheKey,
1182 - isStreaming,
1183 - preserveLines,
1184 -}: UncachedShikiCodeBlockProps) {
1185 - const highlighter = use(getSyntaxHighlighterPromise(language));
1186 - const incrementalHighlight = preserveLines
1187 - ? createIncrementalHighlightedDocument(highlighter, language, themeName)
1188 - : null;
1189 - const highlighted = (() => {
1190 - try {
1191 - if (incrementalHighlight) return incrementalHighlight(code);
1192 - return preserveLines
1193 - ? highlighter.codeToHast(code, { lang: language, theme: themeName })
1194 - : highlighter.codeToHtml(code, { lang: language, theme: themeName });
1195 - } catch (error) {
1196 - console.warn(
1197 - `Code highlighting failed for language "${language}", falling back to plain text.`,
1198 - error instanceof Error ? error.message : error,
1199 - );
1200 - return preserveLines
1201 - ? highlighter.codeToHast(code, { lang: "text", theme: themeName })
1202 - : highlighter.codeToHtml(code, { lang: "text", theme: themeName });
1203 - }
1204 - })();
1205 -
1206 - useEffect(() => {
1207 - if (!isStreaming) {
1208 - const highlightedHtml = typeof highlighted === "string" ? highlighted : toHtml(highlighted);
1209 - highlightedCodeCache.set(
1210 - cacheKey,
1211 - highlightedHtml,
1212 - estimateHighlightedSize(highlightedHtml, code),
1213 - );
1214 - }
1215 - }, [cacheKey, code, highlighted, isStreaming]);
1216 -
1217 - return typeof highlighted === "string" ? (
1218 - <div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlighted }} />
1219 - ) : (
1220 - <div className="chat-markdown-shiki">
1221 - <HighlightedCodeLines root={highlighted} />
1222 - </div>
1223 - );
1224 -}
1225 -
735 interface MarkdownFileLinkProps {
736 environmentId: EnvironmentId | null;
737 href: string;
apps/web/src/components/chat/ComposerCodeBlockNodeView.tsx
+1 -1
@@ -3,7 +3,7 @@ import { NodeViewContent, NodeViewWrapper, type NodeViewProps } from "@tiptap/re
3 import { languageOfInfoString, withInfoStringLanguage } from "~/composer-code-languages";
4
5 import { useRenderedAppearance } from "../../hooks/useTheme";
6 -import { MarkdownCodeBlockFrame } from "../ChatMarkdown";
6 +import { MarkdownCodeBlockFrame } from "./MarkdownCodeBlock";
7 import { ComposerCodeBlockLanguagePicker } from "./ComposerCodeBlockLanguagePicker";
8
9 export function ComposerCodeBlockNodeView({
apps/web/src/components/chat/MarkdownCodeBlock.logic.ts new
+119
@@ -0,0 +1,119 @@
1 +import { Children, isValidElement, type ReactNode } from "react";
2 +import type { ExtraProps as ReactMarkdownExtraProps } from "react-markdown";
3 +
4 +import { fnv1a32, type DiffThemeName } from "../../lib/diffRendering";
5 +
6 +const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
7 +
8 +export function extractFenceLanguage(className: string | undefined): string {
9 + const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
10 + const raw = match?.[1] ?? "text";
11 + // Shiki doesn't bundle a gitignore grammar; ini is a close match (#685)
12 + return raw === "gitignore" ? "ini" : raw;
13 +}
14 +
15 +const FENCE_TITLE_ATTR_REGEX = /(?:^|\s)(?:title|file(?:name)?)=(?:"([^"]+)"|'([^']+)'|(\S+))/i;
16 +const FENCE_FILENAME_TOKEN_REGEX = /^[\w@][\w@./-]*\.[A-Za-z0-9]+$/;
17 +
18 +export function extractFenceTitle(meta: string | undefined): string | null {
19 + if (!meta) return null;
20 + const attrMatch = FENCE_TITLE_ATTR_REGEX.exec(meta);
21 + const attrTitle = attrMatch?.[1] ?? attrMatch?.[2] ?? attrMatch?.[3];
22 + if (attrTitle) return attrTitle;
23 + return meta.split(/\s+/).find((candidate) => FENCE_FILENAME_TOKEN_REGEX.test(candidate)) ?? null;
24 +}
25 +
26 +export function extractPreCodeMeta(node: unknown): string | undefined {
27 + const children = (
28 + node as
29 + | {
30 + children?: Array<{
31 + type?: string;
32 + tagName?: string;
33 + data?: { meta?: unknown };
34 + properties?: { dataCodeMeta?: unknown };
35 + }>;
36 + }
37 + | undefined
38 + )?.children;
39 + const codeNode = children?.find((child) => child?.type === "element" && child.tagName === "code");
40 + const meta = codeNode?.properties?.dataCodeMeta ?? codeNode?.data?.meta;
41 + return typeof meta === "string" && meta.trim().length > 0 ? meta.trim() : undefined;
42 +}
43 +
44 +export function isClosedCodeFence(
45 + node: ReactMarkdownExtraProps["node"],
46 + text: string,
47 + code: string,
48 +): boolean {
49 + const start = node?.position?.start.offset;
50 + const end = node?.position?.end.offset;
51 + if (start === undefined || end === undefined) return false;
52 + const source = text.slice(start, end);
53 + const opening = /^(?:`{3,}|~{3,})/.exec(source)?.[0];
54 + // One class for the blockquote prefix: nested quantifiers here backtrack
55 + // exponentially on code lines that start with many `> ` markers.
56 + const closing = /(?:^|\n)[ \t>]*(`{3,}|~{3,})[ \t\r]*$/.exec(source)?.[1];
57 + return (
58 + opening !== undefined &&
59 + closing !== undefined &&
60 + opening[0] === closing[0] &&
61 + closing.length >= opening.length &&
62 + // Only a real closer is omitted from parsed code. A CRLF stream cut after
63 + // CR must not count as an extra source line.
64 + source.replace(/\r$/, "").split(/\r\n|\r|\n/).length > code.split(/\r\n|\r|\n/).length
65 + );
66 +}
67 +
68 +export function nodeToPlainText(node: ReactNode): string {
69 + if (typeof node === "string" || typeof node === "number") {
70 + return String(node);
71 + }
72 + if (Array.isArray(node)) {
73 + return node.map((child) => nodeToPlainText(child)).join("");
74 + }
75 + if (isValidElement<{ children?: ReactNode }>(node)) {
76 + return nodeToPlainText(node.props.children);
77 + }
78 + return "";
79 +}
80 +
81 +export function extractCodeBlock(
82 + children: ReactNode,
83 +): { className: string | undefined; code: string } | null {
84 + const childNodes = Children.toArray(children);
85 + if (childNodes.length !== 1) {
86 + return null;
87 + }
88 +
89 + const onlyChild = childNodes[0];
90 + if (
91 + !isValidElement<{ className?: string; children?: ReactNode; node?: { tagName?: string } }>(
92 + onlyChild,
93 + )
94 + ) {
95 + return null;
96 + }
97 + // With a custom `code` component the child's type is that component, not
98 + // the "code" tag — the hast node react-markdown attaches still names it.
99 + if (onlyChild.type !== "code" && onlyChild.props.node?.tagName !== "code") {
100 + return null;
101 + }
102 +
103 + return {
104 + className: onlyChild.props.className,
105 + code: nodeToPlainText(onlyChild.props.children),
106 + };
107 +}
108 +
109 +export function createHighlightCacheKey(
110 + code: string,
111 + language: string,
112 + themeName: DiffThemeName,
113 +): string {
114 + return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`;
115 +}
116 +
117 +export function estimateHighlightedSize(html: string, code: string): number {
118 + return Math.max(html.length * 2, code.length * 3);
119 +}
apps/web/src/components/chat/MarkdownCodeBlock.tsx new
+390
@@ -0,0 +1,390 @@
1 +import { Check, Copy } from "lucide";
2 +import { PlayIcon, WrapTextIcon } from "lucide-react";
3 +import { toHtml } from "hast-util-to-html";
4 +import React, { use, useEffect, useRef, useState, type ReactNode } from "react";
5 +
6 +import { getClientSettings } from "../../hooks/useSettings";
7 +import type { DiffThemeName } from "../../lib/diffRendering";
8 +import { createIncrementalHighlightedDocument } from "../../lib/incrementalHighlighting";
9 +import { LRUCache } from "../../lib/lruCache";
10 +import { getSyntaxHighlighterPromise } from "../../lib/syntaxHighlighting";
11 +import { cn } from "../../lib/utils";
12 +import {
13 + hasSpecificPierreIconForFileName,
14 + syntheticFileNameForLanguageId,
15 +} from "../../pierre-icons";
16 +import { MorphIcon } from "../MorphIcon";
17 +import { Button } from "../ui/button";
18 +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
19 +import { HighlightedCodeLines } from "./HighlightedCodeLines";
20 +import {
21 + createHighlightCacheKey,
22 + estimateHighlightedSize,
23 + extractFenceLanguage,
24 +} from "./MarkdownCodeBlock.logic";
25 +import { reportMarkdownActionFailure } from "./markdownActionFailure";
26 +import { PierreEntryIcon } from "./PierreEntryIcon";
27 +
28 +const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
29 +const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
30 +
31 +const highlightedCodeCache = new LRUCache<string>(
32 + MAX_HIGHLIGHT_CACHE_ENTRIES,
33 + MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
34 +);
35 +
36 +const THREAD_FIND_IGNORE_PROPS = {
37 + "data-thread-find-ignore": "",
38 +} as React.HTMLAttributes<HTMLDivElement>;
39 +
40 +export function MarkdownCodeBlockFrame({
41 + as: Wrapper = "div",
42 + language,
43 + fenceTitle,
44 + theme,
45 + wrapped = true,
46 + title,
47 + actions,
48 + headerProps,
49 + children,
50 +}: {
51 + as?: React.ElementType;
52 + language: string;
53 + fenceTitle: string | null;
54 + theme: "light" | "dark";
55 + wrapped?: boolean;
56 + title?: React.ReactNode;
57 + actions?: React.ReactNode;
58 + headerProps?: React.HTMLAttributes<HTMLDivElement>;
59 + children: React.ReactNode;
60 +}) {
61 + return (
62 + <Wrapper
63 + className="chat-markdown-codeblock my-[0.65rem] overflow-hidden rounded-lg border border-border/70 bg-secondary leading-snug dark:border-transparent dark:bg-input/32"
64 + data-language={language}
65 + data-wrap={wrapped ? "true" : "false"}
66 + >
67 + <div
68 + {...headerProps}
69 + className={cn(
70 + "chat-markdown-codeblock-header flex items-center justify-between gap-2 pt-1.5 pr-1.5 pb-0 pl-3 select-none",
71 + headerProps?.className,
72 + )}
73 + >
74 + {title ?? (
75 + <span className="inline-flex min-w-0 items-center gap-1.5 font-mono text-2xs">
76 + <MarkdownCodeBlockTitleContent
77 + fenceTitle={fenceTitle}
78 + language={language}
79 + theme={theme}
80 + />
81 + </span>
82 + )}
83 + {actions}
84 + </div>
85 + {children}
86 + </Wrapper>
87 + );
88 +}
89 +
90 +function MarkdownCodeBlockTitleContent({
91 + fenceTitle,
92 + language,
93 + theme,
94 +}: {
95 + fenceTitle: string | null;
96 + language: string;
97 + theme: "light" | "dark";
98 +}) {
99 + if (fenceTitle) {
100 + return (
101 + <>
102 + <PierreEntryIcon pathValue={fenceTitle} kind="file" theme={theme} className="size-3.5" />
103 + <span className="truncate">{fenceTitle}</span>
104 + </>
105 + );
106 + }
107 +
108 + const fileName = syntheticFileNameForLanguageId(language);
109 + if (!hasSpecificPierreIconForFileName(fileName)) {
110 + return <span className="truncate">{language}</span>;
111 + }
112 + return (
113 + <Tooltip>
114 + <TooltipTrigger
115 + render={
116 + <span className="inline-flex shrink-0 rounded-sm" aria-label={`Language: ${language}`} />
117 + }
118 + >
119 + <PierreEntryIcon pathValue={fileName} kind="file" theme={theme} className="size-3.5" />
120 + </TooltipTrigger>
121 + <TooltipPopup side="top">{language}</TooltipPopup>
122 + </Tooltip>
123 + );
124 +}
125 +
126 +export function MarkdownCodeBlock({
127 + code,
128 + language,
129 + fenceTitle,
130 + theme,
131 + onRunShellCommand,
132 + isStreaming,
133 + viewToggle,
134 + canWrap = true,
135 + diagram = false,
136 + children,
137 +}: {
138 + code: string;
139 + language: string;
140 + fenceTitle: string | null;
141 + theme: "light" | "dark";
142 + onRunShellCommand?: ((command: string) => void) | undefined;
143 + isStreaming: boolean;
144 + viewToggle?: ReactNode;
145 + canWrap?: boolean;
146 + diagram?: boolean;
147 + children: ReactNode;
148 +}) {
149 + const [copied, setCopied] = useState(false);
150 + const [wrapped, setWrapped] = useState(() => getClientSettings().wordWrap);
151 + const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
152 + const wrapLabel = wrapped ? "Disable line wrap" : "Wrap lines";
153 + const copyLabel = copied ? "Copied" : "Copy code";
154 + const command = code.trim();
155 + const canRun =
156 + onRunShellCommand !== undefined &&
157 + !isStreaming &&
158 + /^(?:sh|bash|zsh|fish|shell|powershell|pwsh)$/.test(language) &&
159 + code.endsWith("\n") &&
160 + command.length > 0 &&
161 + !command.endsWith("\\") &&
162 + // Control and invisible format characters (bidi overrides, zero-width) can
163 + // make the rendered command differ from what the terminal would receive.
164 + !/[\p{Cc}\p{Cf}]/u.test(code.slice(0, -1));
165 +
166 + const handleCopy = () => {
167 + if (typeof navigator === "undefined" || navigator.clipboard == null) {
168 + return;
169 + }
170 + void navigator.clipboard
171 + .writeText(code)
172 + .then(() => {
173 + if (copiedTimerRef.current != null) {
174 + clearTimeout(copiedTimerRef.current);
175 + }
176 + setCopied(true);
177 + copiedTimerRef.current = setTimeout(() => {
178 + setCopied(false);
179 + copiedTimerRef.current = null;
180 + }, 1200);
181 + })
182 + .catch((cause) => {
183 + reportMarkdownActionFailure(
184 + {
185 + operation: "copy-code-block",
186 + language,
187 + ...(fenceTitle ? { fenceTitle } : {}),
188 + },
189 + cause,
190 + );
191 + });
192 + };
193 +
194 + useEffect(
195 + () => () => {
196 + if (copiedTimerRef.current != null) {
197 + clearTimeout(copiedTimerRef.current);
198 + copiedTimerRef.current = null;
199 + }
200 + },
201 + [],
202 + );
203 +
204 + const copyButton = (
205 + <Tooltip>
206 + <TooltipTrigger
207 + render={
208 + <Button
209 + type="button"
210 + variant="ghost-muted"
211 + size="icon-xs"
212 + onClick={handleCopy}
213 + aria-label={copyLabel}
214 + />
215 + }
216 + >
217 + <MorphIcon className="size-3" icon={copied ? Check : Copy} />
218 + </TooltipTrigger>
219 + <TooltipPopup side="top">{copyLabel}</TooltipPopup>
220 + </Tooltip>
221 + );
222 +
223 + if (diagram) {
224 + return (
225 + <div className="my-[0.65rem] border border-transparent" data-language={language}>
226 + <div className="flex items-center justify-end gap-0.5 pt-1.5 pr-1.5 select-none">
227 + {viewToggle}
228 + {copyButton}
229 + </div>
230 + {children}
231 + </div>
232 + );
233 + }
234 +
235 + return (
236 + <MarkdownCodeBlockFrame
237 + language={language}
238 + fenceTitle={fenceTitle}
239 + theme={theme}
240 + wrapped={wrapped}
241 + headerProps={THREAD_FIND_IGNORE_PROPS}
242 + actions={
243 + <span className="flex items-center gap-0.5" role="toolbar" aria-label="Code block actions">
244 + {canWrap ? (
245 + <Tooltip>
246 + <TooltipTrigger
247 + render={
248 + <Button
249 + type="button"
250 + variant={wrapped ? "secondary" : "ghost-muted"}
251 + size="icon-xs"
252 + aria-pressed={wrapped}
253 + onClick={() => setWrapped((value) => !value)}
254 + aria-label={wrapLabel}
255 + />
256 + }
257 + >
258 + <WrapTextIcon className="size-3" />
259 + </TooltipTrigger>
260 + <TooltipPopup side="top">{wrapLabel}</TooltipPopup>
261 + </Tooltip>
262 + ) : null}
263 + {canRun ? (
264 + <Tooltip>
265 + <TooltipTrigger
266 + render={
267 + <Button
268 + type="button"
269 + variant="ghost-muted"
270 + size="icon-xs"
271 + onClick={() => onRunShellCommand(command)}
272 + aria-label="Run in terminal"
273 + />
274 + }
275 + >
276 + <PlayIcon className="size-3" />
277 + </TooltipTrigger>
278 + <TooltipPopup side="top">Run in terminal</TooltipPopup>
279 + </Tooltip>
280 + ) : null}
281 + {viewToggle}
282 + {copyButton}
283 + </span>
284 + }
285 + >
286 + {children}
287 + </MarkdownCodeBlockFrame>
288 + );
289 +}
290 +
291 +interface SuspenseShikiCodeBlockProps {
292 + className: string | undefined;
293 + code: string;
294 + themeName: DiffThemeName;
295 + isStreaming: boolean;
296 +}
297 +
298 +export function SuspenseShikiCodeBlock({
299 + className,
300 + code,
301 + themeName,
302 + isStreaming,
303 +}: SuspenseShikiCodeBlockProps) {
304 + const [hasStreamed, setHasStreamed] = useState(isStreaming);
305 + if (isStreaming && !hasStreamed) setHasStreamed(true);
306 + const language = extractFenceLanguage(className);
307 + const cacheKey = createHighlightCacheKey(code, language, themeName);
308 + // Once lines are mounted individually, keep that renderer when streaming
309 + // finishes so switching to cached HTML cannot clear an existing selection.
310 + const cachedHighlightedHtml =
311 + !isStreaming && !hasStreamed ? highlightedCodeCache.get(cacheKey) : null;
312 +
313 + if (cachedHighlightedHtml != null) {
314 + return (
315 + <div
316 + className="chat-markdown-shiki"
317 + dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
318 + />
319 + );
320 + }
321 +
322 + return (
323 + <UncachedShikiCodeBlock
324 + code={code}
325 + language={language}
326 + themeName={themeName}
327 + cacheKey={cacheKey}
328 + isStreaming={isStreaming}
329 + preserveLines={isStreaming || hasStreamed}
330 + />
331 + );
332 +}
333 +
334 +interface UncachedShikiCodeBlockProps {
335 + code: string;
336 + language: string;
337 + themeName: DiffThemeName;
338 + cacheKey: string;
339 + isStreaming: boolean;
340 + preserveLines: boolean;
341 +}
342 +
343 +function UncachedShikiCodeBlock({
344 + code,
345 + language,
346 + themeName,
347 + cacheKey,
348 + isStreaming,
349 + preserveLines,
350 +}: UncachedShikiCodeBlockProps) {
351 + const highlighter = use(getSyntaxHighlighterPromise(language));
352 + const incrementalHighlight = preserveLines
353 + ? createIncrementalHighlightedDocument(highlighter, language, themeName)
354 + : null;
355 + const highlighted = (() => {
356 + try {
357 + if (incrementalHighlight) return incrementalHighlight(code);
358 + return preserveLines
359 + ? highlighter.codeToHast(code, { lang: language, theme: themeName })
360 + : highlighter.codeToHtml(code, { lang: language, theme: themeName });
361 + } catch (error) {
362 + console.warn(
363 + `Code highlighting failed for language "${language}", falling back to plain text.`,
364 + error instanceof Error ? error.message : error,
365 + );
366 + return preserveLines
367 + ? highlighter.codeToHast(code, { lang: "text", theme: themeName })
368 + : highlighter.codeToHtml(code, { lang: "text", theme: themeName });
369 + }
370 + })();
371 +
372 + useEffect(() => {
373 + if (!isStreaming) {
374 + const highlightedHtml = typeof highlighted === "string" ? highlighted : toHtml(highlighted);
375 + highlightedCodeCache.set(
376 + cacheKey,
377 + highlightedHtml,
378 + estimateHighlightedSize(highlightedHtml, code),
379 + );
380 + }
381 + }, [cacheKey, code, highlighted, isStreaming]);
382 +
383 + return typeof highlighted === "string" ? (
384 + <div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlighted }} />
385 + ) : (
386 + <div className="chat-markdown-shiki">
387 + <HighlightedCodeLines root={highlighted} />
388 + </div>
389 + );
390 +}
apps/web/src/components/chat/markdownActionFailure.ts new
+15
@@ -0,0 +1,15 @@
1 +interface MarkdownActionFailureContext {
2 + readonly operation: string;
3 + readonly target?: string;
4 + readonly format?: "markdown" | "csv";
5 + readonly language?: string;
6 + readonly fenceTitle?: string;
7 + readonly copyTarget?: string;
8 +}
9 +
10 +export function reportMarkdownActionFailure(
11 + context: MarkdownActionFailureContext,
12 + cause: unknown,
13 +): void {
14 + console.error("[chat-markdown] action failed", context, cause);
15 +}