Open History to see the last commit
1import { NodeViewContent, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";
2
3import { languageOfInfoString, withInfoStringLanguage } from "~/composer-code-languages";
4
5import { useTheme } from "../../hooks/useTheme";
6import { MarkdownCodeBlockFrame } from "../ChatMarkdown";
7import { ComposerCodeBlockLanguagePicker } from "./ComposerCodeBlockLanguagePicker";
8
9/**
10 * Draws a composer fence in the chat view's own code block frame, so a draft
11 * looks like the message it is about to become, with the language title
12 * swapped for a picker that rewrites the fence's language in place.
13 *
14 * The chrome stops at the language. Chat's wrap and copy buttons act on text
15 * the reader cannot change; here the text is the draft, and both are already
16 * a selection away.
17 */
18export function ComposerCodeBlockNodeView({
19 node,
20 editor,
21 getPos,
22 updateAttributes,
23}: NodeViewProps) {
24 const { resolvedTheme } = useTheme();
25 const info = typeof node.attrs.language === "string" ? node.attrs.language : "";
26 const language = languageOfInfoString(info);
27
28 const changeLanguage = (next: string) => {
29 updateAttributes({ language: withInfoStringLanguage(info, next) });
30 // Back into the code, at its end, the way a picker hands focus back.
31 const position = getPos();
32 if (typeof position === "number") {
33 editor
34 .chain()
35 .focus(position + 1 + node.content.size)
36 .run();
37 }
38 };
39
40 return (
41 <MarkdownCodeBlockFrame
42 as={NodeViewWrapper}
43 language={language || "text"}
44 fenceTitle={null}
45 theme={resolvedTheme}
46 headerProps={{ contentEditable: false }}
47 title={
48 <ComposerCodeBlockLanguagePicker
49 language={language}
50 theme={resolvedTheme}
51 disabled={!editor.isEditable}
52 onChange={changeLanguage}
53 />
54 }
55 >
56 <div className="chat-markdown-shiki">
57 <pre className="max-w-full overflow-x-auto px-3 pt-1 pb-2">
58 {/* A caret needs a line to sit on even before any code is typed. */}
59 <NodeViewContent<"code">
60 as="code"
61 className="block min-h-[1lh] font-mono whitespace-pre-wrap text-inherit [overflow-wrap:anywhere]"
62 />
63 </pre>
64 </div>
65 </MarkdownCodeBlockFrame>
66 );
67}