Skip to content

feat: add PreviewableCode component with Mermaid and PlantUML support #1131

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions app/tag-data.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
{
"markdown": 2,
"code": 2,
"features": 2,
"next-js": 6,
"tailwind": 3,
"guide": 5,
"feature": 2,
"multi-author": 1,
"hello": 1,
"math": 1,
"ols": 1,
"github": 1,
"writings": 1,
"book": 1,
"reflection": 1,
"guide": 5,
"tailwind": 3,
"holiday": 1,
"canada": 1,
"images": 1,
"markdown": 1,
"code": 1,
"features": 1
"feature": 2,
"writings": 1,
"book": 1,
"reflection": 1,
"multi-author": 1
}
13 changes: 11 additions & 2 deletions components/MDXComponents.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
import TOCInline from 'pliny/ui/TOCInline'
import Pre from 'pliny/ui/Pre'
// import Pre from 'pliny/ui/Pre'
import BlogNewsletterForm from 'pliny/ui/BlogNewsletterForm'
import type { MDXComponents } from 'mdx/types'
import Image from './Image'
import CustomLink from './Link'
import TableWrapper from './TableWrapper'
import PreviewableCode from './PreviewableCode'
import Mermaid from './Mermaid'
import PlantUML from './PlantUML'

// Configure available renderers
const renderers = {
mermaid: Mermaid,
plantuml: PlantUML,
}

export const components: MDXComponents = {
Image,
TOCInline,
a: CustomLink,
pre: Pre,
pre: (props) => <PreviewableCode defaultView={'code'} renderers={renderers} {...props} />,
table: TableWrapper,
BlogNewsletterForm,
}
118 changes: 118 additions & 0 deletions components/Mermaid.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
'use client'

import { useEffect, useState } from 'react'
import mermaid from 'mermaid'

// Module-level initialization flag
let mermaidInitialized = false

const initializeMermaid = () => {
if (!mermaidInitialized) {
mermaid.initialize({
startOnLoad: true,
theme: 'base',
logLevel: 'error',
securityLevel: 'loose',
suppressErrorRendering: true,
flowchart: {
curve: 'basis',
padding: 20,
nodeSpacing: 50,
rankSpacing: 50,
htmlLabels: true,
defaultRenderer: 'dagre-wrapper',
},
themeVariables: {
fontFamily:
'ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif',
primaryColor: '#6366f1',
primaryTextColor: '#ffffff',
primaryBorderColor: '#4f46e5',
lineColor: '#6366f1',
secondaryColor: '#f1f5f9',
tertiaryColor: '#e2e8f0',
},
})
mermaidInitialized = true
}
}

interface ErrorDisplayProps {
error: Error | string
code: string
}

const ErrorDisplay = ({ error, code }: ErrorDisplayProps) => (
<div className="overflow-hidden rounded-lg border border-red-200">
<details className="group">
<summary className="cursor-pointer list-none border-b border-red-200 bg-red-50 px-4 py-2">
<div className="flex items-center">
<span className="mr-2 text-red-500">⚠️</span>
<span className="font-medium text-red-700">Mermaid Syntax Error</span>
<svg
className="ml-2 h-5 w-5 transform text-red-500 transition-transform group-open:rotate-180"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</div>
</summary>
<div className="border-b border-red-200 bg-red-50 px-4 py-2">
<pre className="font-mono text-sm font-medium break-words whitespace-pre-wrap text-red-700">
{typeof error === 'string' ? error : error.message || 'Failed to render diagram'}
</pre>
</div>
</details>
<div className="bg-gray-50 p-4">
<pre className="language-mermaid overflow-x-auto text-sm">{code}</pre>
</div>
</div>
)

interface MermaidProps {
code: string
}

const Mermaid = ({ code }: MermaidProps) => {
const [svg, setSvg] = useState<string>('')
const [error, setError] = useState<Error | string | null>(null)

useEffect(() => {
// Initialize mermaid once for the entire application
initializeMermaid()

if (typeof code === 'string') {
try {
// Generate a unique ID for this diagram
const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`
// Here we manually render the mermaid diagram, we can also let mermaid.js to automatically render the diagram
// by return <pre className="language-mermaid">{chart}</pre>
mermaid.render(id, code.trim()).then(
({ svg }) => {
setError(null)
setSvg(svg)
},
(error) => {
console.error('Mermaid rendering failed:', error)
setError(error)
setSvg('')
}
)
} catch (error) {
console.error('Mermaid error:', error)
setError(error instanceof Error ? error : 'Failed to render diagram')
setSvg('')
}
}
}, [code])

if (error) {
return <ErrorDisplay error={error} code={code} />
}

return <div className="mermaid-chart my-4" dangerouslySetInnerHTML={{ __html: svg }} />
}

export default Mermaid
57 changes: 57 additions & 0 deletions components/PlantUML.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'use client'

import { useEffect, useState } from 'react'
import PlantUmlEncoder from 'plantuml-encoder'

interface PlantUMLProps {
code: string
dpi?: number
}

const PlantUML = ({ code, dpi = 600 }: PlantUMLProps) => {
const [url, setUrl] = useState<string>('')
const [svgUrl, setSvgUrl] = useState<string>('')
const [isHovered, setIsHovered] = useState(false)

useEffect(() => {
if (typeof code === 'string') {
const resolution = `skinparam dpi ${dpi}`
const text = `${resolution}\n${code.trim()}`
const encoded = PlantUmlEncoder.encode(text)
setUrl(`https://www.plantuml.com/plantuml/img/${encoded}`)
setSvgUrl(`https://www.plantuml.com/plantuml/svg/${encoded}`)
}
}, [code, dpi])

if (!url) {
return null
}

return (
<div
className="plantuml-chart relative mx-auto max-w-4xl"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={url}
alt="PlantUML diagram"
className="mx-auto block w-full rounded-md object-contain"
style={{ maxHeight: '80vh' }}
/>
<a
href={svgUrl}
target="_blank"
rel="noopener noreferrer"
className={`absolute right-2 bottom-2 rounded-md bg-white/80 px-2 py-1 text-xs text-gray-600 shadow-sm transition-all duration-200 hover:bg-white hover:text-gray-900 dark:bg-gray-800/80 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200 ${
isHovered ? 'translate-y-0 opacity-100' : 'translate-y-2 opacity-0'
}`}
>
View SVG
</a>
</div>
)
}

export default PlantUML
119 changes: 119 additions & 0 deletions components/PreviewableCode.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
'use client'

import type { ReactNode, ComponentType } from 'react'
import Pre from 'pliny/ui/Pre'
import { Tab, TabGroup, TabPanel, TabPanels, TabList } from '@headlessui/react'
import { Fragment } from 'react'

interface PreviewableCodeBlock {
type: string
props: {
className?: string
children: ReactNode
}
}

const extractTextFromAST = (children: ReactNode): string => {
if (typeof children === 'string') return children
if (Array.isArray(children)) return children.map(extractTextFromAST).join('')
if (children && typeof children === 'object' && 'props' in children) {
const childrenWithProps = children as { props: { children: ReactNode } }
return extractTextFromAST(childrenWithProps.props.children)
}
return String(children || '')
}

const isPreviewableCodeBlock = (children: unknown): children is PreviewableCodeBlock => {
return (
children !== null &&
typeof children === 'object' &&
'props' in children &&
'type' in children &&
children.type === 'code'
)
}

interface PreviewableCodeProps {
children: ReactNode
enablePreview?: boolean
defaultView?: 'preview' | 'code'
renderers: { [key: string]: ComponentType<{ code: string; [key: string]: unknown }> }
[key: string]: unknown
}

const PreviewableCode = ({
children,
enablePreview = true,
defaultView = 'preview',
renderers,
...props
}: PreviewableCodeProps) => {
// If preview is disabled or the code block is not previewable, return the raw code block
if (!enablePreview || !isPreviewableCodeBlock(children)) {
return <Pre {...props}>{children}</Pre>
}

const { className } = children.props
const languageMatch = /language-(\w+)/.exec(className || '')

if (!languageMatch) {
return <Pre {...props}>{children}</Pre>
}

const language = languageMatch[1]
const Renderer = renderers[language]

if (!Renderer) {
console.warn(`No renderer found for language: ${language}`)
return <Pre {...props}>{children}</Pre>
}

const rawText = extractTextFromAST(children.props.children)

return (
<TabGroup defaultIndex={defaultView === 'preview' ? 0 : 1}>
<div className="border-b border-gray-200 dark:border-gray-700">
<TabList className="-mb-px flex space-x-8">
<Tab as={Fragment}>
{({ selected }) => (
<button
className={`border-b-2 px-4 py-2 text-sm font-medium transition-colors ${
selected
? 'border-primary-500 text-primary-600 dark:text-primary-500'
: 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
} `}
>
Code
</button>
)}
</Tab>
<Tab as={Fragment}>
{({ selected }) => (
<button
className={`border-b-2 px-4 py-2 text-sm font-medium transition-colors ${
selected
? 'border-primary-500 text-primary-600 dark:text-primary-500'
: 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
} `}
>
Preview
</button>
)}
</Tab>
</TabList>
</div>
<TabPanels>
<TabPanel>
<Pre {...props}>{children}</Pre>
</TabPanel>
</TabPanels>
<TabPanel>
<div className="">
<Renderer {...props} code={rawText} />
</div>
</TabPanel>
</TabGroup>
)
}

export default PreviewableCode
Loading