@devries-cameron20 / t3code Mirror · read-only / commits / 5c5d6ed3b6
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 tables and details live in their own components (#22692)

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

Julius Marminge committed Oct 21, 2026 at 01:32 UTC 5c5d6ed3b6a24416169878a4c6dfc564dbae33b9
3 files changed +236 -220
apps/web/src/components/ChatMarkdown.tsx
+4 -220
@@ -1,5 +1,4 @@
1 import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
2 -import { MarkdownFindContext, findRevealRef } from "./chat/markdownFindContext";
2 import {
3 buildFileLinkParentSuffixByPath,
4 fileLinkLabel,
@@ -26,7 +25,6 @@ import {
25 encodeComposerContextClipboardHtml,
26 } from "@t3tools/shared/composerContextClipboard";
27 import {
29 - ChevronRightIcon,
28 FileSpreadsheetIcon,
29 FileTextIcon,
30 GlobeIcon,
@@ -42,7 +40,6 @@ import {
40 TriangleAlertIcon,
41 type LucideIcon,
42 } from "lucide-react";
45 -import { Check, Copy, Maximize2, Minimize2 } from "lucide";
43 import {
44 AssetWorkspaceAssetNotFoundError,
45 AuthPreviewOperateScope,
@@ -85,7 +82,6 @@ import React, {
82 type ClipboardEvent as ReactClipboardEvent,
83 type KeyboardEvent as ReactKeyboardEvent,
84 type MouseEvent as ReactMouseEvent,
88 - isValidElement,
85 use,
86 memo,
87 useEffect,
@@ -136,11 +132,7 @@ import {
132 } from "./chat/externalLinkContextMenu";
133 import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
134 import { Button } from "./ui/button";
139 -import { MorphIcon } from "~/components/MorphIcon";
135 import { ContextChip } from "./ContextChip";
141 -import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "./ui/collapsible";
142 -import { ScrollArea } from "./ui/scroll-area";
143 -import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
136 import { stackedThreadToast, toastManager } from "./ui/toast";
137 import { recordVisitForThread } from "../browserHistoryStore";
138 import {
@@ -153,12 +145,8 @@ import { resolveDiffThemeName } from "../lib/diffRendering";
145 import { GitHubIcon } from "./Icons";
146 import { RenderErrorBoundary } from "./RenderErrorBoundary";
147 import { useRenderedAppearance } from "../hooks/useTheme";
156 -import { getClientSettings, useClientSettings } from "../hooks/useSettings";
157 -import {
158 - chatMarkdownClipboardPayload,
159 - serializeTableElementToCsv,
160 - serializeTableElementToMarkdown,
161 -} from "../markdown-clipboard";
148 +import { useClientSettings } from "../hooks/useSettings";
149 +import { chatMarkdownClipboardPayload } from "../markdown-clipboard";
150 import {
151 resolveInlineCodeFileLinkMeta,
152 resolveMarkdownFileLinkMeta,
@@ -212,7 +200,6 @@ import {
200 resolvePullRequestPreviewTarget,
201 useOpenChangeRequestLink,
202 } from "~/lib/openPullRequestLink";
215 -import { observeResize } from "~/lib/observeResize";
203 import { useOpenLink } from "../browser/useOpenLink";
204 import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
205 import { isPreviewAvailableFor } from "../browser/previewRuntime";
@@ -227,6 +214,8 @@ import { resolveLinkTarget } from "../browser/browserLinkTarget";
214 import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview";
215 import { MarkdownCodeBlock, SuspenseShikiCodeBlock } from "./chat/MarkdownCodeBlock";
216 import { MarkdownMermaidCodeBlock } from "./chat/MarkdownMermaidCodeBlock";
217 +import { MarkdownTable } from "./chat/MarkdownTable";
218 +import { MarkdownDetails } from "./chat/MarkdownDetails";
219 import {
220 extractCodeBlock,
221 extractFenceLanguage,
@@ -450,211 +439,6 @@ const GITHUB_ALERT_PRESENTATIONS: Record<
439 },
440 };
441
453 -/**
454 - * Whether any cell is clipped in the unwrapped layout. Only then does the wrap
455 - * toggle change anything, so short tables hide it. Measures with the container
456 - * briefly unwrapped and restores it before the browser paints.
457 - */
458 -function tableHasClippedCells(container: HTMLElement, table: HTMLTableElement): boolean {
459 - const viewport = table.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
460 - const scrollLeft = viewport?.scrollLeft ?? 0;
461 - const previous = container.dataset.expanded;
462 - container.dataset.expanded = "false";
463 - try {
464 - for (const row of table.rows) {
465 - for (const cell of row.cells) {
466 - if (cell.scrollWidth > cell.clientWidth) return true;
467 - }
468 - }
469 - return false;
470 - } finally {
471 - if (previous === undefined) delete container.dataset.expanded;
472 - else container.dataset.expanded = previous;
473 - // The unwrapped layout can be narrower and clamp a sideways scroll.
474 - if (viewport && scrollLeft > 0) viewport.scrollLeft = scrollLeft;
475 - }
476 -}
477 -
478 -function MarkdownTable({ children, ...props }: React.ComponentProps<"table">) {
479 - const containerRef = useRef<HTMLDivElement | null>(null);
480 - const tableRef = useRef<HTMLTableElement | null>(null);
481 - const [expanded, setExpanded] = useState(() => getClientSettings().wordWrap);
482 - const [hasClippedCells, setHasClippedCells] = useState(false);
483 - const [copied, setCopied] = useState(false);
484 - const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
485 - const expandLabel = expanded ? "Collapse table cells" : "Expand table cells";
486 - const copyLabel = copied ? "Copied" : "Copy table";
487 -
488 - const measureClippedCells = () => {
489 - const container = containerRef.current;
490 - const table = tableRef.current;
491 - if (!container || !table) return;
492 - setHasClippedCells(tableHasClippedCells(container, table));
493 - };
494 -
495 - // A streamed cell can grow until it clips while the table keeps its size,
496 - // so remeasure after every render, not only on resize.
497 - useLayoutEffect(measureClippedCells);
498 -
499 - // Column width changes can clip a cell without rendering this table.
500 - useLayoutEffect(() => {
501 - const table = tableRef.current;
502 - if (!table) return;
503 - return observeResize(table, measureClippedCells);
504 - }, [measureClippedCells]);
505 -
506 - const handleCopy = (format: "markdown" | "csv") => {
507 - const table = containerRef.current?.querySelector("table");
508 - if (!table || typeof navigator === "undefined" || navigator.clipboard == null) {
509 - return;
510 - }
511 - const text =
512 - format === "markdown"
513 - ? serializeTableElementToMarkdown(table)
514 - : serializeTableElementToCsv(table);
515 - void navigator.clipboard
516 - .writeText(text)
517 - .then(() => {
518 - if (copiedTimerRef.current != null) {
519 - clearTimeout(copiedTimerRef.current);
520 - }
521 - setCopied(true);
522 - copiedTimerRef.current = setTimeout(() => {
523 - setCopied(false);
524 - copiedTimerRef.current = null;
525 - }, 1200);
526 - })
527 - .catch((cause) => {
528 - reportMarkdownActionFailure({ operation: "copy-table", format }, cause);
529 - });
530 - };
531 -
532 - useEffect(
533 - () => () => {
534 - if (copiedTimerRef.current != null) {
535 - clearTimeout(copiedTimerRef.current);
536 - copiedTimerRef.current = null;
537 - }
538 - },
539 - [],
540 - );
541 -
542 - return (
543 - <div
544 - ref={containerRef}
545 - className="chat-markdown-table-container"
546 - data-expanded={expanded ? "true" : "false"}
547 - >
548 - <ScrollArea radius="none" chainVerticalScroll scrollFade className="w-full max-w-full">
549 - <table ref={tableRef} {...props}>
550 - {children}
551 - </table>
552 - </ScrollArea>
553 - <div className="mt-0.5 flex items-center justify-between select-none">
554 - {hasClippedCells ? (
555 - <Tooltip>
556 - <TooltipTrigger
557 - render={
558 - <Button
559 - type="button"
560 - variant={expanded ? "secondary" : "ghost-muted"}
561 - size="icon-xs"
562 - aria-pressed={expanded}
563 - onClick={() => setExpanded((value) => !value)}
564 - aria-label={expandLabel}
565 - />
566 - }
567 - >
568 - <MorphIcon className="size-3" icon={expanded ? Minimize2 : Maximize2} />
569 - </TooltipTrigger>
570 - <TooltipPopup side="top">{expandLabel}</TooltipPopup>
571 - </Tooltip>
572 - ) : (
573 - <span />
574 - )}
575 - <Menu>
576 - <Tooltip>
577 - <TooltipTrigger
578 - render={
579 - <MenuTrigger
580 - render={
581 - <Button
582 - type="button"
583 - variant="ghost-muted"
584 - size="icon-xs"
585 - aria-label={copyLabel}
586 - />
587 - }
588 - />
589 - }
590 - >
591 - <MorphIcon className="size-3" icon={copied ? Check : Copy} />
592 - </TooltipTrigger>
593 - <TooltipPopup side="top">{copyLabel}</TooltipPopup>
594 - </Tooltip>
595 - <MenuPopup align="end">
596 - <MenuItem onClick={() => handleCopy("markdown")}>Copy as Markdown</MenuItem>
597 - <MenuItem onClick={() => handleCopy("csv")}>Copy as CSV</MenuItem>
598 - </MenuPopup>
599 - </Menu>
600 - </div>
601 - </div>
602 - );
603 -}
604 -
605 -function MarkdownDetails({
606 - children,
607 - open = false,
608 -}: Pick<React.ComponentProps<"details">, "children" | "open">) {
609 - const [isOpen, setIsOpen] = useState(open);
610 - const searching = use(MarkdownFindContext);
611 - const expanded = isOpen;
612 - const revealForFind = () => setIsOpen(true);
613 - // Base UI only listens for `beforematch` on a panel mounted at its first
614 - // render; a closed panel mounts later, when find starts, so listen here.
615 - const revealRef = findRevealRef(revealForFind);
616 - const childNodes = Children.toArray(children);
617 - const summaryIndex = childNodes.findIndex(
618 - (child) => isValidElement(child) && child.type === "summary",
619 - );
620 - const summaryNode = summaryIndex >= 0 ? childNodes[summaryIndex] : null;
621 - const summary =
622 - isValidElement<{ children?: ReactNode }>(summaryNode) && summaryNode.props.children
623 - ? summaryNode.props.children
624 - : "Details";
625 - const content = childNodes.filter((_, index) => index !== summaryIndex);
626 -
627 - return (
628 - <div className="my-2 border-y border-border/60">
629 - <Collapsible
630 - open={expanded}
631 - onOpenChange={setIsOpen}
632 - data-markdown-details=""
633 - data-markdown-details-open={expanded ? "true" : "false"}
634 - >
635 - <CollapsibleTrigger
636 - className="flex w-full items-center gap-2 py-2 text-left text-sm font-medium text-foreground data-panel-open:[&_svg]:rotate-90"
637 - data-markdown-details-summary=""
638 - >
639 - <ChevronRightIcon
640 - className="size-4 shrink-0 text-muted-foreground transition-transform"
641 - aria-hidden
642 - />
643 - <span>{summary}</span>
644 - </CollapsibleTrigger>
645 - <CollapsiblePanel ref={revealRef} hiddenUntilFound={searching}>
646 - <div
647 - className="pb-3 ps-6 text-foreground/[calc(80%+var(--appearance-contrast-boost)/5)]"
648 - data-markdown-details-content=""
649 - >
650 - {content}
651 - </div>
652 - </CollapsiblePanel>
653 - </Collapsible>
654 - </div>
655 - );
656 -}
657 -
442 interface MarkdownFileLinkProps {
443 environmentId: EnvironmentId | null;
444 href: string;
apps/web/src/components/chat/MarkdownDetails.tsx new
+65
@@ -0,0 +1,65 @@
1 +import { ChevronRightIcon } from "lucide-react";
2 +import {
3 + Children,
4 + isValidElement,
5 + use,
6 + useState,
7 + type ComponentProps,
8 + type ReactNode,
9 +} from "react";
10 +
11 +import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
12 +import { findRevealRef, MarkdownFindContext } from "./markdownFindContext";
13 +
14 +export function MarkdownDetails({
15 + children,
16 + open = false,
17 +}: Pick<ComponentProps<"details">, "children" | "open">) {
18 + const [isOpen, setIsOpen] = useState(open);
19 + const searching = use(MarkdownFindContext);
20 + const expanded = isOpen;
21 + const revealForFind = () => setIsOpen(true);
22 + // Base UI only listens for `beforematch` on a panel mounted at its first
23 + // render; a closed panel mounts later, when find starts, so listen here.
24 + const revealRef = findRevealRef(revealForFind);
25 + const childNodes = Children.toArray(children);
26 + const summaryIndex = childNodes.findIndex(
27 + (child) => isValidElement(child) && child.type === "summary",
28 + );
29 + const summaryNode = summaryIndex >= 0 ? childNodes[summaryIndex] : null;
30 + const summary =
31 + isValidElement<{ children?: ReactNode }>(summaryNode) && summaryNode.props.children
32 + ? summaryNode.props.children
33 + : "Details";
34 + const content = childNodes.filter((_, index) => index !== summaryIndex);
35 +
36 + return (
37 + <div className="my-2 border-y border-border/60">
38 + <Collapsible
39 + open={expanded}
40 + onOpenChange={setIsOpen}
41 + data-markdown-details=""
42 + data-markdown-details-open={expanded ? "true" : "false"}
43 + >
44 + <CollapsibleTrigger
45 + className="flex w-full items-center gap-2 py-2 text-left text-sm font-medium text-foreground data-panel-open:[&_svg]:rotate-90"
46 + data-markdown-details-summary=""
47 + >
48 + <ChevronRightIcon
49 + className="size-4 shrink-0 text-muted-foreground transition-transform"
50 + aria-hidden
51 + />
52 + <span>{summary}</span>
53 + </CollapsibleTrigger>
54 + <CollapsiblePanel ref={revealRef} hiddenUntilFound={searching}>
55 + <div
56 + className="pb-3 ps-6 text-foreground/[calc(80%+var(--appearance-contrast-boost)/5)]"
57 + data-markdown-details-content=""
58 + >
59 + {content}
60 + </div>
61 + </CollapsiblePanel>
62 + </Collapsible>
63 + </div>
64 + );
65 +}
apps/web/src/components/chat/MarkdownTable.tsx new
+167
@@ -0,0 +1,167 @@
1 +import { Check, Copy, Maximize2, Minimize2 } from "lucide";
2 +import { useEffect, useLayoutEffect, useRef, useState, type ComponentProps } from "react";
3 +
4 +import { getClientSettings } from "../../hooks/useSettings";
5 +import { observeResize } from "../../lib/observeResize";
6 +import {
7 + serializeTableElementToCsv,
8 + serializeTableElementToMarkdown,
9 +} from "../../markdown-clipboard";
10 +import { MorphIcon } from "../MorphIcon";
11 +import { Button } from "../ui/button";
12 +import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
13 +import { ScrollArea } from "../ui/scroll-area";
14 +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
15 +import { reportMarkdownActionFailure } from "./markdownActionFailure";
16 +
17 +/**
18 + * Whether any cell is clipped in the unwrapped layout. Only then does the wrap
19 + * toggle change anything, so short tables hide it. Measures with the container
20 + * briefly unwrapped and restores it before the browser paints.
21 + */
22 +function tableHasClippedCells(container: HTMLElement, table: HTMLTableElement): boolean {
23 + const viewport = table.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
24 + const scrollLeft = viewport?.scrollLeft ?? 0;
25 + const previous = container.dataset.expanded;
26 + container.dataset.expanded = "false";
27 + try {
28 + for (const row of table.rows) {
29 + for (const cell of row.cells) {
30 + if (cell.scrollWidth > cell.clientWidth) return true;
31 + }
32 + }
33 + return false;
34 + } finally {
35 + if (previous === undefined) delete container.dataset.expanded;
36 + else container.dataset.expanded = previous;
37 + // The unwrapped layout can be narrower and clamp a sideways scroll.
38 + if (viewport && scrollLeft > 0) viewport.scrollLeft = scrollLeft;
39 + }
40 +}
41 +
42 +export function MarkdownTable({ children, ...props }: ComponentProps<"table">) {
43 + const containerRef = useRef<HTMLDivElement | null>(null);
44 + const tableRef = useRef<HTMLTableElement | null>(null);
45 + const [expanded, setExpanded] = useState(() => getClientSettings().wordWrap);
46 + const [hasClippedCells, setHasClippedCells] = useState(false);
47 + const [copied, setCopied] = useState(false);
48 + const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
49 + const expandLabel = expanded ? "Collapse table cells" : "Expand table cells";
50 + const copyLabel = copied ? "Copied" : "Copy table";
51 +
52 + const measureClippedCells = () => {
53 + const container = containerRef.current;
54 + const table = tableRef.current;
55 + if (!container || !table) return;
56 + setHasClippedCells(tableHasClippedCells(container, table));
57 + };
58 +
59 + // A streamed cell can grow until it clips while the table keeps its size,
60 + // so remeasure after every render, not only on resize.
61 + useLayoutEffect(measureClippedCells);
62 +
63 + // Column width changes can clip a cell without rendering this table.
64 + useLayoutEffect(() => {
65 + const table = tableRef.current;
66 + if (!table) return;
67 + return observeResize(table, measureClippedCells);
68 + }, [measureClippedCells]);
69 +
70 + const handleCopy = (format: "markdown" | "csv") => {
71 + const table = containerRef.current?.querySelector("table");
72 + if (!table || typeof navigator === "undefined" || navigator.clipboard == null) {
73 + return;
74 + }
75 + const text =
76 + format === "markdown"
77 + ? serializeTableElementToMarkdown(table)
78 + : serializeTableElementToCsv(table);
79 + void navigator.clipboard
80 + .writeText(text)
81 + .then(() => {
82 + if (copiedTimerRef.current != null) {
83 + clearTimeout(copiedTimerRef.current);
84 + }
85 + setCopied(true);
86 + copiedTimerRef.current = setTimeout(() => {
87 + setCopied(false);
88 + copiedTimerRef.current = null;
89 + }, 1200);
90 + })
91 + .catch((cause) => {
92 + reportMarkdownActionFailure({ operation: "copy-table", format }, cause);
93 + });
94 + };
95 +
96 + useEffect(
97 + () => () => {
98 + if (copiedTimerRef.current != null) {
99 + clearTimeout(copiedTimerRef.current);
100 + copiedTimerRef.current = null;
101 + }
102 + },
103 + [],
104 + );
105 +
106 + return (
107 + <div
108 + ref={containerRef}
109 + className="chat-markdown-table-container"
110 + data-expanded={expanded ? "true" : "false"}
111 + >
112 + <ScrollArea radius="none" chainVerticalScroll scrollFade className="w-full max-w-full">
113 + <table ref={tableRef} {...props}>
114 + {children}
115 + </table>
116 + </ScrollArea>
117 + <div className="mt-0.5 flex items-center justify-between select-none">
118 + {hasClippedCells ? (
119 + <Tooltip>
120 + <TooltipTrigger
121 + render={
122 + <Button
123 + type="button"
124 + variant={expanded ? "secondary" : "ghost-muted"}
125 + size="icon-xs"
126 + aria-pressed={expanded}
127 + onClick={() => setExpanded((value) => !value)}
128 + aria-label={expandLabel}
129 + />
130 + }
131 + >
132 + <MorphIcon className="size-3" icon={expanded ? Minimize2 : Maximize2} />
133 + </TooltipTrigger>
134 + <TooltipPopup side="top">{expandLabel}</TooltipPopup>
135 + </Tooltip>
136 + ) : (
137 + <span />
138 + )}
139 + <Menu>
140 + <Tooltip>
141 + <TooltipTrigger
142 + render={
143 + <MenuTrigger
144 + render={
145 + <Button
146 + type="button"
147 + variant="ghost-muted"
148 + size="icon-xs"
149 + aria-label={copyLabel}
150 + />
151 + }
152 + />
153 + }
154 + >
155 + <MorphIcon className="size-3" icon={copied ? Check : Copy} />
156 + </TooltipTrigger>
157 + <TooltipPopup side="top">{copyLabel}</TooltipPopup>
158 + </Tooltip>
159 + <MenuPopup align="end">
160 + <MenuItem onClick={() => handleCopy("markdown")}>Copy as Markdown</MenuItem>
161 + <MenuItem onClick={() => handleCopy("csv")}>Copy as CSV</MenuItem>
162 + </MenuPopup>
163 + </Menu>
164 + </div>
165 + </div>
166 + );
167 +}