From 150c66a97ff40673cd1560c1f2cfb9b6b5f99547 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 14 Jul 2025 19:43:52 -0700 Subject: [PATCH] code block syntax highlighting with lowlight because prism wasn't working --- package-lock.json | 56 +++++++ package.json | 1 + src/ui/MarkdownRenderer.test.tsx | 27 ++-- src/ui/MarkdownRenderer.tsx | 105 +++++++++--- src/ui/SyntaxHighlighter.ts | 266 +++++++++++++++++++++++++++++++ 5 files changed, 419 insertions(+), 36 deletions(-) create mode 100644 src/ui/SyntaxHighlighter.ts diff --git a/package-lock.json b/package-lock.json index 18d898342..03652f7ff 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,6 +21,7 @@ "glob": "^11.0.3", "ignore-walk": "^7.0.0", "ink": "^6.0.1", + "lowlight": "^3.3.0", "minimatch": "^10.0.3", "open": "^10.1.0", "react": "^19.1.0", @@ -2902,6 +2903,14 @@ "@types/node": "*" } }, + "node_modules/@types/hast": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", + "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", + "dependencies": { + "@types/unist": "*" + } + }, "node_modules/@types/http-assert": { "version": "1.5.6", "resolved": "https://registry.npmjs.org/@types/http-assert/-/http-assert-1.5.6.tgz", @@ -3111,6 +3120,11 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/unist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", + "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==" + }, "node_modules/@types/uuid": { "version": "9.0.8", "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz", @@ -4670,6 +4684,14 @@ "node": ">= 0.8" } }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "engines": { + "node": ">=6" + } + }, "node_modules/detect-newline": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", @@ -4680,6 +4702,18 @@ "node": ">=8" } }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/diff": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/diff/-/diff-7.0.0.tgz", @@ -8346,6 +8380,28 @@ "loose-envify": "cli.js" } }, + "node_modules/lowlight": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lowlight/-/lowlight-3.3.0.tgz", + "integrity": "sha512-0JNhgFoPvP6U6lE/UdVsSq99tn6DhjjpAj5MxG49ewd2mOBVtwWYIT8ClyABhq198aXXODMU6Ox8DrGy/CpTZQ==", + "dependencies": { + "@types/hast": "^3.0.0", + "devlop": "^1.0.0", + "highlight.js": "~11.11.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/lowlight/node_modules/highlight.js": { + "version": "11.11.1", + "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.11.1.tgz", + "integrity": "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", diff --git a/package.json b/package.json index e7add936a..8ac72fd10 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,7 @@ "glob": "^11.0.3", "ignore-walk": "^7.0.0", "ink": "^6.0.1", + "lowlight": "^3.3.0", "minimatch": "^10.0.3", "open": "^10.1.0", "react": "^19.1.0", diff --git a/src/ui/MarkdownRenderer.test.tsx b/src/ui/MarkdownRenderer.test.tsx index 128f78bab..c9797dbf4 100644 --- a/src/ui/MarkdownRenderer.test.tsx +++ b/src/ui/MarkdownRenderer.test.tsx @@ -155,28 +155,26 @@ describe("MarkdownRenderer", () => { const result = renderMarkdown("```\nconst x = 1;\nconsole.log(x);\n```"); expect(result.length).toBe(1); expect(React.isValidElement(result[0])).toBe(true); - expect((result[0] as any).props.color).toBe("cyan"); - expect((result[0] as any).props.children).toBe( - "\nconst x = 1;\nconsole.log(x);\n" - ); + // The result should be a Text element containing syntax highlighted code + expect((result[0] as any).type).toBe("ink-text"); + expect((result[0] as any).props.children).toBeDefined(); + expect(Array.isArray((result[0] as any).props.children)).toBe(true); }); it("renders single line code blocks", () => { const result = renderMarkdown("```console.log('hello')```"); expect(result.length).toBe(1); expect(React.isValidElement(result[0])).toBe(true); - expect((result[0] as any).props.color).toBe("cyan"); - expect((result[0] as any).props.children).toBe("console.log('hello')"); + expect((result[0] as any).type).toBe("ink-text"); + expect((result[0] as any).props.children).toBeDefined(); }); it("renders code blocks with language specification", () => { const result = renderMarkdown("```javascript\nconst x = 1;\n```"); expect(result.length).toBe(1); expect(React.isValidElement(result[0])).toBe(true); - expect((result[0] as any).props.color).toBe("cyan"); - expect((result[0] as any).props.children).toBe( - "javascript\nconst x = 1;\n" - ); + expect((result[0] as any).type).toBe("ink-text"); + expect((result[0] as any).props.children).toBeDefined(); }); it("handles code blocks mixed with other formatting", () => { @@ -185,10 +183,8 @@ describe("MarkdownRenderer", () => { ); expect(result.length).toBe(5); expect(result[0]).toBe("Here's some code:\n"); - expect((result[1] as any).props.color).toBe("cyan"); - expect((result[1] as any).props.children).toBe( - "\nfunction test() {\n return 42;\n}\n" - ); + expect(React.isValidElement(result[1])).toBe(true); + expect((result[1] as any).type).toBe("ink-text"); expect(result[2]).toBe("\nAnd "); expect((result[3] as any).props.bold).toBe(true); expect((result[3] as any).props.children).toBe("bold"); @@ -199,8 +195,7 @@ describe("MarkdownRenderer", () => { const result = renderMarkdown("``````"); expect(result.length).toBe(1); expect(React.isValidElement(result[0])).toBe(true); - expect((result[0] as any).props.color).toBe("cyan"); - expect((result[0] as any).props.children).toBe(""); + expect((result[0] as any).type).toBe("ink-text"); }); }); }); diff --git a/src/ui/MarkdownRenderer.tsx b/src/ui/MarkdownRenderer.tsx index bad1ec28b..a5e570ec3 100644 --- a/src/ui/MarkdownRenderer.tsx +++ b/src/ui/MarkdownRenderer.tsx @@ -1,8 +1,10 @@ import { Text } from "ink"; import React from "react"; +import { highlightCode, detectLanguage, SyntaxHighlighterTheme, defaultTheme } from "./SyntaxHighlighter.js"; interface MarkdownRendererProps { content: string; + theme?: SyntaxHighlighterTheme; } interface MarkdownPattern { @@ -10,15 +12,14 @@ interface MarkdownPattern { render: (content: string, key: string) => React.ReactNode; } -const MarkdownRenderer: React.FC = ({ content }) => { +const MarkdownRenderer: React.FC = ({ content, theme = defaultTheme }) => { const patterns: MarkdownPattern[] = [ { - regex: /```([\s\S]*?)```/g, - render: (content, key) => ( - - {content} - - ), + regex: /```(?:(\w+)\n)?([\s\S]*?)```/g, + render: (content, key) => { + // content here is the captured group, but we need to parse the full match + return null; // This will be handled separately + }, }, { regex: /^(#{1,6})\s+(.+)$/gm, @@ -74,7 +75,27 @@ const MarkdownRenderer: React.FC = ({ content }) => { const parts: React.ReactNode[] = []; let currentIndex = 0; - // Find all matches for all patterns + // First, handle code blocks separately + const codeBlockRegex = /```(?:(\w+)\n)?([\s\S]*?)```/g; + const codeBlocks: Array<{ + index: number; + length: number; + language: string; + code: string; + }> = []; + + let codeMatch; + while ((codeMatch = codeBlockRegex.exec(text)) !== null) { + const language = codeMatch[1] || detectLanguage(codeMatch[2]); + codeBlocks.push({ + index: codeMatch.index, + length: codeMatch[0].length, + language, + code: codeMatch[2].trim() + }); + } + + // Find all matches for other patterns (excluding code blocks) const allMatches: Array<{ index: number; length: number; @@ -82,26 +103,59 @@ const MarkdownRenderer: React.FC = ({ content }) => { render: (content: string, key: string) => React.ReactNode; }> = []; - patterns.forEach((pattern) => { - let match; + patterns.slice(1).forEach((pattern) => { // Skip the first pattern (code blocks) + let match: RegExpExecArray | null; const regex = new RegExp(pattern.regex.source, pattern.regex.flags); while ((match = regex.exec(text)) !== null) { - allMatches.push({ - index: match.index, - length: match[0].length, - content: match[2] || match[1], // Use second capture group for headings, first for others - render: pattern.render, - }); + // Skip if this match is inside a code block + const isInCodeBlock = codeBlocks.some(block => + match!.index >= block.index && match!.index < block.index + block.length + ); + + if (!isInCodeBlock) { + allMatches.push({ + index: match.index, + length: match[0].length, + content: match[2] || match[1], // Use second capture group for headings, first for others + render: pattern.render, + }); + } } }); + // Combine code blocks and other matches + const combinedMatches: Array<{ + index: number; + length: number; + type: 'code' | 'other'; + content?: string; + render?: (content: string, key: string) => React.ReactNode; + language?: string; + code?: string; + }> = [ + ...codeBlocks.map(block => ({ + index: block.index, + length: block.length, + type: 'code' as const, + language: block.language, + code: block.code + })), + ...allMatches.map(match => ({ + index: match.index, + length: match.length, + type: 'other' as const, + content: match.content, + render: match.render + })) + ]; + // Sort matches by index to process them in order - allMatches.sort((a, b) => a.index - b.index); + combinedMatches.sort((a, b) => a.index - b.index); // Process matches, avoiding overlaps - let processedMatches: typeof allMatches = []; - for (const match of allMatches) { + let processedMatches: typeof combinedMatches = []; + for (const match of combinedMatches) { const overlaps = processedMatches.some( (processed) => (match.index >= processed.index && @@ -123,7 +177,16 @@ const MarkdownRenderer: React.FC = ({ content }) => { } // Add the formatted match - parts.push(match.render(match.content, `format-${idx}-${match.index}`)); + if (match.type === 'code') { + const highlightedCode = highlightCode(match.code!, match.language!, theme); + parts.push( + + {highlightedCode} + + ); + } else { + parts.push(match.render!(match.content!, `format-${idx}-${match.index}`)); + } currentIndex = match.index + match.length; }); @@ -140,3 +203,5 @@ const MarkdownRenderer: React.FC = ({ content }) => { }; export default MarkdownRenderer; +export type { SyntaxHighlighterTheme }; +export { defaultTheme }; diff --git a/src/ui/SyntaxHighlighter.ts b/src/ui/SyntaxHighlighter.ts new file mode 100644 index 000000000..024e551e1 --- /dev/null +++ b/src/ui/SyntaxHighlighter.ts @@ -0,0 +1,266 @@ +import { createLowlight } from 'lowlight'; +import { Text } from 'ink'; +import React from 'react'; +import js from 'highlight.js/lib/languages/javascript.js'; +import ts from 'highlight.js/lib/languages/typescript.js'; +import python from 'highlight.js/lib/languages/python.js'; +import java from 'highlight.js/lib/languages/java.js'; +import c from 'highlight.js/lib/languages/c.js'; +import cpp from 'highlight.js/lib/languages/cpp.js'; +import csharp from 'highlight.js/lib/languages/csharp.js'; +import go from 'highlight.js/lib/languages/go.js'; +import rust from 'highlight.js/lib/languages/rust.js'; +import php from 'highlight.js/lib/languages/php.js'; +import ruby from 'highlight.js/lib/languages/ruby.js'; +import swift from 'highlight.js/lib/languages/swift.js'; +import kotlin from 'highlight.js/lib/languages/kotlin.js'; +import sql from 'highlight.js/lib/languages/sql.js'; +import json from 'highlight.js/lib/languages/json.js'; +import yaml from 'highlight.js/lib/languages/yaml.js'; +import bash from 'highlight.js/lib/languages/bash.js'; +import markdown from 'highlight.js/lib/languages/markdown.js'; +import css from 'highlight.js/lib/languages/css.js'; +import xml from 'highlight.js/lib/languages/xml.js'; + +export interface SyntaxHighlighterTheme { + keyword: string; + string: string; + comment: string; + number: string; + operator: string; + punctuation: string; + function: string; + variable: string; + property: string; + class: string; + constant: string; + regex: string; + default: string; +} + +export const defaultTheme: SyntaxHighlighterTheme = { + keyword: 'magenta', + string: 'green', + comment: 'gray', + number: 'cyan', + operator: 'white', + punctuation: 'white', + function: 'yellow', + variable: 'white', + property: 'blue', + class: 'yellow', + constant: 'cyan', + regex: 'red', + default: 'white' +}; + +// Map highlight.js token types to theme colors +const tokenColorMap: Record = { + 'keyword': 'keyword', + 'string': 'string', + 'comment': 'comment', + 'number': 'number', + 'operator': 'operator', + 'punctuation': 'punctuation', + 'function': 'function', + 'variable': 'variable', + 'property': 'property', + 'class': 'class', + 'constant': 'constant', + 'regexp': 'regex', + 'boolean': 'constant', + 'null': 'constant', + 'undefined': 'constant', + 'builtin': 'keyword', + 'tag': 'keyword', + 'attr': 'property', + 'attribute': 'property', + 'selector': 'property', + 'important': 'keyword', + 'atrule': 'keyword', + 'rule': 'keyword', + 'entity': 'constant', + 'url': 'string', + 'symbol': 'constant', + 'prolog': 'comment', + 'doctype': 'comment', + 'cdata': 'comment', + 'title': 'function', + 'section': 'keyword', + 'name': 'function', + 'strong': 'keyword', + 'emphasis': 'string', + 'quote': 'string', + 'built_in': 'keyword', + 'literal': 'constant', + 'type': 'class', + 'params': 'variable', + 'meta': 'comment', + 'link': 'string' +}; + +export function highlightCode( + code: string, + language: string = 'javascript', + theme: SyntaxHighlighterTheme = defaultTheme +): React.ReactNode[] { + try { + // Create lowlight instance and register languages + const lowlight = createLowlight(); + lowlight.register({ + javascript: js, + typescript: ts, + python: python, + java: java, + c: c, + cpp: cpp, + csharp: csharp, + go: go, + rust: rust, + php: php, + ruby: ruby, + swift: swift, + kotlin: kotlin, + sql: sql, + json: json, + yaml: yaml, + bash: bash, + markdown: markdown, + css: css, + html: xml, + xml: xml + }); + + const result = lowlight.highlight(language, code, { prefix: '' }); + + // Convert the hast tree to React elements + const elements: React.ReactNode[] = []; + + let keyCounter = 0; + + function processNode(node: any, parentColor: string = theme.default): React.ReactNode { + if (node.type === 'text') { + const text = node.value; + if (text) { + return React.createElement(Text, { + key: `text-${keyCounter++}`, + color: parentColor + }, text); + } + return null; + } + + if (node.type === 'element') { + const className = node.properties?.className || []; + + // Extract token type from class names + let tokenType = ''; + for (const cls of className) { + if (tokenColorMap[cls]) { + tokenType = cls; + break; + } + } + + // Get color from theme + const colorKey = tokenColorMap[tokenType] || 'default'; + const color = theme[colorKey]; + + if (node.children && node.children.length > 0) { + // Process child nodes with this color + const children: React.ReactNode[] = []; + for (let i = 0; i < node.children.length; i++) { + const child = processNode(node.children[i], color); + if (child) { + if (Array.isArray(child)) { + children.push(...child); + } else { + children.push(child); + } + } + } + + return children; + } + + const textContent = getTextContent(node); + if (textContent) { + return React.createElement(Text, { + key: `element-${keyCounter++}`, + color + }, textContent); + } + } + + return null; + } + + // Helper function to extract text content from a node + function getTextContent(node: any): string { + if (node.type === 'text') { + return node.value || ''; + } + + if (node.type === 'element' && node.children) { + return node.children.map(getTextContent).join(''); + } + + return ''; + } + + // Process all child nodes + if (result.children) { + for (let i = 0; i < result.children.length; i++) { + const element = processNode(result.children[i]); + if (element) { + if (Array.isArray(element)) { + elements.push(...element); + } else { + elements.push(element); + } + } + } + } + + return elements; + + } catch (error) { + // Fallback to plain text on error + return [React.createElement(Text, { key: 'error-fallback', color: theme.default }, code)]; + } +} + +export function detectLanguage(code: string): string { + // Simple language detection based on common patterns + const patterns = [ + { regex: /^\s*import\s+.*from\s+['"]/, language: 'javascript' }, + { regex: /^\s*const\s+\w+\s*=\s*require\s*\(/, language: 'javascript' }, + { regex: /^\s*function\s+\w+\s*\(/, language: 'javascript' }, + { regex: /^\s*interface\s+\w+\s*\{/, language: 'typescript' }, + { regex: /^\s*type\s+\w+\s*=/, language: 'typescript' }, + { regex: /^\s*def\s+\w+\s*\(/, language: 'python' }, + { regex: /^\s*class\s+\w+\s*:/, language: 'python' }, + { regex: /^\s*public\s+class\s+\w+/, language: 'java' }, + { regex: /^\s*#include\s*