An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
Add CodeBlock component for syntax highlighting
Yoshiki Miurabe95d847a0b3
diff --git a/bun.lockb b/bun.lockbindex 8529fa88..c0d8b90b 100755Binary files a/bun.lockb and b/bun.lockb differdiff --git a/components/message.tsx b/components/message.tsxindex 8c1a5294..a2d006f7 100644--- a/components/message.tsx+++ b/components/message.tsx@@ -6,6 +6,7 @@ import remarkGfm from 'remark-gfm'import remarkMath from 'remark-math'import rehypeKatex from 'rehype-katex'import 'katex/dist/katex.min.css'+import { CodeBlock } from './ui/codeblock'export function BotMessage({ content }: { content: string }) {// Check if the content contains LaTeX patterns@@ -21,7 +22,7 @@ export function BotMessage({ content }: { content: string }) {<MemoizedReactMarkdownrehypePlugins={[[rehypeExternalLinks, { target: '_blank' }],- rehypeKatex+ [rehypeKatex as any, { throwOnError: false, strict: false }]]}remarkPlugins={[remarkGfm, remarkMath]}className="prose-sm prose-neutral prose-a:text-accent-foreground/50"@@ -36,6 +37,38 @@ export function BotMessage({ content }: { content: string }) {rehypePlugins={[[rehypeExternalLinks, { target: '_blank' }]]}remarkPlugins={[remarkGfm]}className="prose-sm prose-neutral prose-a:text-accent-foreground/50"+ components={{+ code({ node, inline, className, children, ...props }) {+ if (children.length) {+ if (children[0] == '▍') {+ return (+ <span className="mt-1 cursor-default animate-pulse">▍</span>+ )+ }++ children[0] = (children[0] as string).replace('`▍`', '▍')+ }++ const match = /language-(\w+)/.exec(className || '')++ if (inline) {+ return (+ <code className={className} {...props}>+ {children}+ </code>+ )+ }++ return (+ <CodeBlock+ key={Math.random()}+ language={(match && match[1]) || ''}+ value={String(children).replace(/\n$/, '')}+ {...props}+ />+ )+ }+ }}>{content}</MemoizedReactMarkdown>diff --git a/components/ui/codeblock.tsx b/components/ui/codeblock.tsxnew file mode 100644index 00000000..3d564509--- /dev/null+++ b/components/ui/codeblock.tsx@@ -0,0 +1,141 @@+// Referenced from Vercel's AI Chatbot and modified to fit the needs of this project+// https://github.com/vercel/ai-chatbot/blob/c2757f87f986b7f15fdf75c4c89cb2219745c53f/components/ui/codeblock.tsx++'use client'++import { FC, memo } from 'react'+import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'+import { coldarkDark } from 'react-syntax-highlighter/dist/cjs/styles/prism'++import { useCopyToClipboard } from '@/lib/hooks/use-copy-to-clipboard'+import { Button } from '@/components/ui/button'+import { generateId } from 'ai'+import { Check, Copy, Download } from 'lucide-react'++interface Props {+ language: string+ value: string+}++interface languageMap {+ [key: string]: string | undefined+}++export const programmingLanguages: languageMap = {+ javascript: '.js',+ python: '.py',+ java: '.java',+ c: '.c',+ cpp: '.cpp',+ 'c++': '.cpp',+ 'c#': '.cs',+ ruby: '.rb',+ php: '.php',+ swift: '.swift',+ 'objective-c': '.m',+ kotlin: '.kt',+ typescript: '.ts',+ go: '.go',+ perl: '.pl',+ rust: '.rs',+ scala: '.scala',+ haskell: '.hs',+ lua: '.lua',+ shell: '.sh',+ sql: '.sql',+ html: '.html',+ css: '.css'+ // add more file extensions here, make sure the key is same as language prop in CodeBlock.tsx component+}++const CodeBlock: FC<Props> = memo(({ language, value }) => {+ const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 })++ const downloadAsFile = () => {+ if (typeof window === 'undefined') {+ return+ }+ const fileExtension = programmingLanguages[language] || '.file'+ const suggestedFileName = `file-${generateId()}${fileExtension}`+ const fileName = window.prompt('Enter file name' || '', suggestedFileName)++ if (!fileName) {+ // User pressed cancel on prompt.+ return+ }++ const blob = new Blob([value], { type: 'text/plain' })+ const url = URL.createObjectURL(blob)+ const link = document.createElement('a')+ link.download = fileName+ link.href = url+ link.style.display = 'none'+ document.body.appendChild(link)+ link.click()+ document.body.removeChild(link)+ URL.revokeObjectURL(url)+ }++ const onCopy = () => {+ if (isCopied) return+ copyToClipboard(value)+ }++ return (+ <div className="relative w-full font-sans codeblock bg-neutral-800">+ <div className="flex items-center justify-between w-full px-6 py-2 pr-4 bg-neutral-700 text-zinc-100">+ <span className="text-xs lowercase">{language}</span>+ <div className="flex items-center space-x-1">+ <Button+ variant="ghost"+ className="focus-visible:ring-1"+ onClick={downloadAsFile}+ size="icon"+ >+ <Download className="w-4 h-4" />+ <span className="sr-only">Download</span>+ </Button>+ <Button+ variant="ghost"+ size="icon"+ className="text-xs focus-visible:ring-1 focus-visible:ring-offset-0"+ onClick={onCopy}+ >+ {isCopied ? (+ <Check className="w-4 h-4" />+ ) : (+ <Copy className="w-4 h-4" />+ )}+ <span className="sr-only">Copy code</span>+ </Button>+ </div>+ </div>+ <SyntaxHighlighter+ language={language}+ style={coldarkDark}+ PreTag="div"+ showLineNumbers+ customStyle={{+ margin: 0,+ width: '100%',+ background: 'transparent',+ padding: '1.5rem 1rem'+ }}+ lineNumberStyle={{+ userSelect: 'none'+ }}+ codeTagProps={{+ style: {+ fontSize: '0.9rem',+ fontFamily: 'var(--font-mono)'+ }+ }}+ >+ {value}+ </SyntaxHighlighter>+ </div>+ )+})+CodeBlock.displayName = 'CodeBlock'++export { CodeBlock }diff --git a/package.json b/package.jsonindex 9c7b8b64..bf4c2da8 100644--- a/package.json+++ b/package.json@@ -39,7 +39,8 @@"ollama-ai-provider": "^0.7.0","react-dom": "^18","react-icons": "^5.0.1",- "react-markdown": "^9.0.1",+ "react-markdown": "^8.0.7",+ "react-syntax-highlighter": "^15.5.0","react-textarea-autosize": "^8.5.3","rehype-external-links": "^3.0.0","rehype-katex": "^7.0.0",@@ -51,13 +52,14 @@"zod": "^3.23.8"},"devDependencies": {- "typescript": "^5","@types/node": "^20","@types/react": "^18","@types/react-dom": "^18",+ "@types/react-syntax-highlighter": "^15.5.13",+ "eslint": "^8",+ "eslint-config-next": "^14.2.3","postcss": "^8","tailwindcss": "^3.4.1",- "eslint": "^8",- "eslint-config-next": "^14.2.3"+ "typescript": "^5"}}