message.tsx 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*
  2. * Derived from vercel/ai-elements (skills/ai-elements/scripts/message.tsx).
  3. * Copyright 2023 Vercel, Inc. Licensed under Apache-2.0.
  4. * Modified by ZCode: local integration, formatting and adaptations.
  5. * See THIRD-PARTY-NOTICES.md in the repository root for license and provenance.
  6. */
  7. "use client";
  8. import {
  9. Attachment,
  10. AttachmentPreview,
  11. AttachmentRemove,
  12. Attachments,
  13. } from "@/components/ai-elements/attachments";
  14. import {
  15. Message,
  16. MessageAction,
  17. MessageActions,
  18. MessageBranch,
  19. MessageBranchContent,
  20. MessageBranchNext,
  21. MessageBranchPage,
  22. MessageBranchPrevious,
  23. MessageBranchSelector,
  24. MessageContent,
  25. MessageResponse,
  26. MessageToolbar,
  27. } from "@/components/ai-elements/message";
  28. import { CopyIcon, RefreshCcwIcon, ThumbsDownIcon, ThumbsUpIcon } from "lucide-react";
  29. import { nanoid } from "nanoid";
  30. import { memo, useCallback, useState } from "react";
  31. const messages: {
  32. key: string;
  33. from: "user" | "assistant";
  34. versions?: { id: string; content: string }[];
  35. content?: string;
  36. attachments?: {
  37. id: string;
  38. type: "file";
  39. url: string;
  40. mediaType?: string;
  41. filename?: string;
  42. }[];
  43. }[] = [
  44. {
  45. attachments: [
  46. {
  47. filename: "palace-of-fine-arts.jpg",
  48. id: nanoid(),
  49. mediaType: "image/jpeg",
  50. type: "file",
  51. url: "https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=400&fit=crop",
  52. },
  53. {
  54. filename: "react-hooks-guide.pdf",
  55. id: nanoid(),
  56. mediaType: "application/pdf",
  57. type: "file",
  58. url: "",
  59. },
  60. ],
  61. content: "How do React hooks work and when should I use them?",
  62. from: "user",
  63. key: nanoid(),
  64. },
  65. {
  66. from: "assistant",
  67. key: nanoid(),
  68. versions: [
  69. {
  70. content: `# React Hooks Guide
  71. React hooks are functions that let you "hook into" React state and lifecycle features from function components. Here's what you need to know:
  72. ## Core Hooks
  73. ### useState
  74. Adds state to functional components:
  75. \`\`\`jsx
  76. const [count, setCount] = useState(0);
  77. return (
  78. <button onClick={() => setCount(count + 1)}>
  79. Count: {count}
  80. </button>
  81. );
  82. \`\`\`
  83. ### useEffect
  84. Handles side effects (data fetching, subscriptions, DOM updates):
  85. \`\`\`jsx
  86. useEffect(() => {
  87. document.title = \`You clicked \${count} times\`;
  88. // Cleanup function (optional)
  89. return () => {
  90. document.title = 'React App';
  91. };
  92. }, [count]); // Dependency array
  93. \`\`\`
  94. ## When to Use Hooks
  95. - ✅ **Function components** - Hooks only work in function components
  96. - ✅ **Replacing class components** - Modern React favors hooks over classes
  97. - ✅ **Sharing stateful logic** - Create custom hooks to reuse logic
  98. - ❌ **Class components** - Use lifecycle methods instead
  99. ## Rules of Hooks
  100. 1. Only call hooks at the **top level** (not inside loops, conditions, or nested functions)
  101. 2. Only call hooks from **React functions** (components or custom hooks)
  102. Would you like to explore more advanced hooks like \`useCallback\` or \`useMemo\`?`,
  103. id: nanoid(),
  104. },
  105. {
  106. content: `React hooks are special functions that let you use React features in function components. The most common ones are:
  107. - **useState** - for managing component state
  108. - **useEffect** - for side effects like data fetching
  109. - **useContext** - for consuming context values
  110. - **useRef** - for accessing DOM elements
  111. Here's a simple example:
  112. \`\`\`jsx
  113. function Counter() {
  114. const [count, setCount] = useState(0);
  115. return (
  116. <button onClick={() => setCount(count + 1)}>
  117. Clicked {count} times
  118. </button>
  119. );
  120. }
  121. \`\`\`
  122. Which specific hook would you like to learn more about?`,
  123. id: nanoid(),
  124. },
  125. {
  126. content: `Absolutely! React hooks are a powerful feature introduced in React 16.8. They solve several problems:
  127. ## Key Benefits
  128. 1. **Simpler code** - No need for class components
  129. 2. **Reusable logic** - Extract stateful logic into custom hooks
  130. 3. **Better organization** - Group related code together
  131. ## Most Popular Hooks
  132. | Hook | Purpose |
  133. |------|---------|
  134. | useState | Add state to components |
  135. | useEffect | Handle side effects |
  136. | useContext | Access context values |
  137. | useReducer | Complex state logic |
  138. | useCallback | Memoize functions |
  139. | useMemo | Memoize values |
  140. The beauty of hooks is that they let you reuse stateful logic without changing your component hierarchy. Want to dive into a specific hook?`,
  141. id: nanoid(),
  142. },
  143. ],
  144. },
  145. ];
  146. const handleCopy = (content: string) => {
  147. navigator.clipboard.writeText(content);
  148. };
  149. const handleRetry = () => {
  150. console.log("Retrying...");
  151. };
  152. interface LikeActionProps {
  153. messageKey: string;
  154. isLiked: boolean;
  155. onToggle: (key: string) => void;
  156. }
  157. const LikeAction = memo(({ messageKey, isLiked, onToggle }: LikeActionProps) => {
  158. const handleClick = useCallback(() => onToggle(messageKey), [messageKey, onToggle]);
  159. return (
  160. <MessageAction label="Like" onClick={handleClick} tooltip="Like this response">
  161. <ThumbsUpIcon className="size-4" fill={isLiked ? "currentColor" : "none"} />
  162. </MessageAction>
  163. );
  164. });
  165. LikeAction.displayName = "LikeAction";
  166. interface DislikeActionProps {
  167. messageKey: string;
  168. isDisliked: boolean;
  169. onToggle: (key: string) => void;
  170. }
  171. const DislikeAction = memo(({ messageKey, isDisliked, onToggle }: DislikeActionProps) => {
  172. const handleClick = useCallback(() => onToggle(messageKey), [messageKey, onToggle]);
  173. return (
  174. <MessageAction label="Dislike" onClick={handleClick} tooltip="Dislike this response">
  175. <ThumbsDownIcon className="size-4" fill={isDisliked ? "currentColor" : "none"} />
  176. </MessageAction>
  177. );
  178. });
  179. DislikeAction.displayName = "DislikeAction";
  180. interface CopyActionProps {
  181. content: string;
  182. }
  183. const CopyAction = memo(({ content }: CopyActionProps) => {
  184. const handleClick = useCallback(() => handleCopy(content), [content]);
  185. return (
  186. <MessageAction label="Copy" onClick={handleClick} tooltip="Copy to clipboard">
  187. <CopyIcon className="size-4" />
  188. </MessageAction>
  189. );
  190. });
  191. CopyAction.displayName = "CopyAction";
  192. const Example = () => {
  193. const [liked, setLiked] = useState<Record<string, boolean>>({});
  194. const [disliked, setDisliked] = useState<Record<string, boolean>>({});
  195. const handleToggleLike = useCallback((key: string) => {
  196. setLiked((prev) => ({ ...prev, [key]: !prev[key] }));
  197. }, []);
  198. const handleToggleDislike = useCallback((key: string) => {
  199. setDisliked((prev) => ({ ...prev, [key]: !prev[key] }));
  200. }, []);
  201. return (
  202. <div className="flex flex-col gap-4">
  203. {/* biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Demo component with complex rendering logic */}
  204. {messages.map((message) => (
  205. <Message from={message.from} key={message.key}>
  206. {message.versions?.length && message.versions.length > 1 ? (
  207. <MessageBranch defaultBranch={0} key={message.key}>
  208. <MessageBranchContent>
  209. {message.versions?.map((version) => (
  210. <MessageContent key={version.id}>
  211. <MessageResponse>{version.content}</MessageResponse>
  212. </MessageContent>
  213. ))}
  214. </MessageBranchContent>
  215. {message.from === "assistant" && (
  216. <MessageToolbar>
  217. <MessageBranchSelector>
  218. <MessageBranchPrevious />
  219. <MessageBranchPage />
  220. <MessageBranchNext />
  221. </MessageBranchSelector>
  222. <MessageActions>
  223. <MessageAction
  224. label="Retry"
  225. onClick={handleRetry}
  226. tooltip="Regenerate response"
  227. >
  228. <RefreshCcwIcon className="size-4" />
  229. </MessageAction>
  230. <LikeAction
  231. isLiked={liked[message.key] ?? false}
  232. messageKey={message.key}
  233. onToggle={handleToggleLike}
  234. />
  235. <DislikeAction
  236. isDisliked={disliked[message.key] ?? false}
  237. messageKey={message.key}
  238. onToggle={handleToggleDislike}
  239. />
  240. <CopyAction content={message.versions?.find((v) => v.id)?.content || ""} />
  241. </MessageActions>
  242. </MessageToolbar>
  243. )}
  244. </MessageBranch>
  245. ) : (
  246. <div key={message.key}>
  247. {message.attachments && message.attachments.length > 0 && (
  248. <Attachments className="mb-2" variant="grid">
  249. {message.attachments.map((attachment) => (
  250. <Attachment data={attachment} key={attachment.id}>
  251. <AttachmentPreview />
  252. <AttachmentRemove />
  253. </Attachment>
  254. ))}
  255. </Attachments>
  256. )}
  257. <MessageContent>
  258. {message.from === "assistant" ? (
  259. <MessageResponse>{message.content}</MessageResponse>
  260. ) : (
  261. message.content
  262. )}
  263. </MessageContent>
  264. {message.from === "assistant" && message.versions && (
  265. <MessageActions>
  266. <MessageAction label="Retry" onClick={handleRetry} tooltip="Regenerate response">
  267. <RefreshCcwIcon className="size-4" />
  268. </MessageAction>
  269. <LikeAction
  270. isLiked={liked[message.key] ?? false}
  271. messageKey={message.key}
  272. onToggle={handleToggleLike}
  273. />
  274. <DislikeAction
  275. isDisliked={disliked[message.key] ?? false}
  276. messageKey={message.key}
  277. onToggle={handleToggleDislike}
  278. />
  279. <CopyAction content={message.content || ""} />
  280. </MessageActions>
  281. )}
  282. </div>
  283. )}
  284. </Message>
  285. ))}
  286. </div>
  287. );
  288. };
  289. export default Example;