Skip to content
Closed
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
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@
"eslint-plugin-jsx-a11y": "^6.10.0",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^7.0.1",
"hast-util-from-parse5": "^8.0.3",
"npm-run-all": "^4.1.5",
"parse5": "^8.0.0",
"postcss": "^8.4.35",
"prettier": "^3.7.4",
"tailwindcss": "^4.1.11",
Expand Down
13 changes: 13 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

228 changes: 228 additions & 0 deletions src/components/CodeBlock.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
import * as React from 'react'
import { twMerge } from 'tailwind-merge'
import { useToast } from '~/components/ToastProvider'
import { Copy } from 'lucide-react'
import type { Mermaid } from 'mermaid'
import { transformerNotationDiff } from '@shikijs/transformers'
import { createHighlighter, type HighlighterGeneric } from 'shiki'

const THEMES = ['github-light', 'tokyo-night']

const LANG_ALIASES: Record<string, string> = {
ts: 'typescript',
js: 'javascript',
sh: 'bash',
shell: 'bash',
console: 'bash',
zsh: 'bash',
md: 'markdown',
txt: 'plaintext',
text: 'plaintext',
}

let highlighterPromise: Promise<HighlighterGeneric<any, any>> | null = null
let mermaidInstance: Mermaid | null = null
const genSvgMap = new Map<string, string>()

async function getHighlighter(language: string) {
if (!highlighterPromise) {
highlighterPromise = createHighlighter({
themes: THEMES,
langs: [
'typescript',
'javascript',
'tsx',
'jsx',
'bash',
'json',
'html',
'css',
'markdown',
'plaintext',
],
})
}

const highlighter = await highlighterPromise
const normalizedLang = LANG_ALIASES[language] || language
const langToLoad = normalizedLang === 'mermaid' ? 'plaintext' : normalizedLang

if (!highlighter.getLoadedLanguages().includes(langToLoad as any)) {
try {
await highlighter.loadLanguage(langToLoad as any)
} catch {
console.warn(`Shiki: Language "${langToLoad}" not found, using plaintext`)
}
}

return highlighter
}

async function getMermaid(): Promise<Mermaid> {
if (!mermaidInstance) {
const { default: mermaid } = await import('mermaid')
mermaid.initialize({ startOnLoad: false, securityLevel: 'loose' })
mermaidInstance = mermaid
}
return mermaidInstance
}

function extractPreAttributes(html: string): {
class: string | null
style: string | null
} {
const match = html.match(/<pre\b([^>]*)>/i)
if (!match) {
return { class: null, style: null }
}

const attributes = match[1]

const classMatch = attributes.match(/\bclass\s*=\s*["']([^"']*)["']/i)
const styleMatch = attributes.match(/\bstyle\s*=\s*["']([^"']*)["']/i)

return {
class: classMatch ? classMatch[1] : null,
style: styleMatch ? styleMatch[1] : null,
}
}

export type CodeBlockProps = React.HTMLProps<HTMLPreElement> & {
isEmbedded?: boolean
showTypeCopyButton?: boolean
}

export function CodeBlock({
isEmbedded,
showTypeCopyButton = true,
...props
}: CodeBlockProps) {
let lang = props?.children?.props?.className?.replace('language-', '')

if (lang === 'diff') {
lang = 'plaintext'
}

const children = props.children as
| undefined
| {
props: {
children: string
}
}

const [copied, setCopied] = React.useState(false)
const ref = React.useRef<any>(null)
const { notify } = useToast()

const code = children?.props.children

const [codeElement, setCodeElement] = React.useState(
<>
<pre ref={ref} className={`shiki github-light h-full`}>
<code>{lang === 'mermaid' ? <svg /> : code}</code>
</pre>
<pre className={`shiki tokyo-night`}>
<code>{lang === 'mermaid' ? <svg /> : code}</code>
</pre>
</>,
)

React[
typeof document !== 'undefined' ? 'useLayoutEffect' : 'useEffect'
](() => {
;(async () => {
const normalizedLang = LANG_ALIASES[lang] || lang
const effectiveLang =
normalizedLang === 'mermaid' ? 'plaintext' : normalizedLang

const highlighter = await getHighlighter(lang)

const htmls = await Promise.all(
THEMES.map(async (theme) => {
const output = highlighter.codeToHtml(code, {
lang: effectiveLang,
theme,
transformers: [transformerNotationDiff()],
})

if (lang === 'mermaid') {
const preAttributes = extractPreAttributes(output)
let svgHtml = genSvgMap.get(code || '')
if (!svgHtml) {
const mermaid = await getMermaid()
const { svg } = await mermaid.render('foo', code || '')
genSvgMap.set(code || '', svg)
svgHtml = svg
}
return `<div class='${preAttributes.class} py-4 bg-neutral-50'>${svgHtml}</div>`
}

return output
}),
)

setCodeElement(
<div
className={twMerge(
isEmbedded ? 'h-full [&>pre]:h-full [&>pre]:rounded-none' : '',
)}
dangerouslySetInnerHTML={{ __html: htmls.join('') }}
ref={ref}
/>,
)
})()
}, [code, lang])

return (
<div
className={twMerge(
'codeblock w-full max-w-full relative not-prose border border-gray-500/20 rounded-md [&_pre]:rounded-md [*[data-tab]_&]:only:border-0',
props.className,
)}
style={props.style}
>
{showTypeCopyButton ? (
<div
className={twMerge(
`absolute flex items-stretch bg-white text-sm z-10 rounded-md`,
`dark:bg-gray-800 overflow-hidden divide-x divide-gray-500/20`,
'shadow-md',
isEmbedded ? 'top-2 right-4' : '-top-3 right-2',
)}
>
{lang ? <div className="px-2">{lang}</div> : null}
<button
className="px-2 py-1 flex items-center text-gray-500 hover:bg-gray-500 hover:text-gray-100 dark:hover:text-gray-200 transition duration-200"
onClick={() => {
let copyContent =
typeof ref.current?.innerText === 'string'
? ref.current.innerText
: ''

if (copyContent.endsWith('\n')) {
copyContent = copyContent.slice(0, -1)
}

navigator.clipboard.writeText(copyContent)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
notify(
<div>
<div className="font-medium">Copied code</div>
<div className="text-gray-500 dark:text-gray-400 text-xs">
Code block copied to clipboard
</div>
</div>,
)
}}
aria-label="Copy code to clipboard"
>
{copied ? <span className="text-xs">Copied!</span> : <Copy />}
</button>
</div>
) : null}
{codeElement}
</div>
)
}
26 changes: 22 additions & 4 deletions src/components/Doc.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ import { GamHeader } from './Gam'
import { Toc } from './Toc'
import { TocMobile } from './TocMobile'
import { DocFeedbackProvider } from './DocFeedbackProvider'
import { MarkdownHeading } from '~/utils/markdown'

type DocProps = {
title: string
content: string
html: { markup: string; headings: Array<MarkdownHeading> }
repo: string
branch: string
filePath: string
Expand All @@ -33,6 +35,7 @@ type DocProps = {
function DocContent({
title,
content,
html,
repo,
branch,
filePath,
Expand All @@ -43,9 +46,16 @@ function DocContent({
libraryVersion,
pagePath,
}: DocProps) {
const { headings } = useMarkdownHeadings()
const { headings, setHeadings } = useMarkdownHeadings()

const isTocVisible = shouldRenderToc && headings && headings.length > 1
React.useEffect(() => {
if (html?.headings?.length) {
setHeadings(html.headings)
}
}, [html?.headings, setHeadings])

const isTocVisible =
shouldRenderToc && (html?.headings?.length ?? headings.length) > 1

const markdownContainerRef = React.useRef<HTMLDivElement>(null)
const [activeHeadings, setActiveHeadings] = React.useState<Array<string>>([])
Expand Down Expand Up @@ -169,10 +179,18 @@ function DocContent({
libraryId={libraryId}
libraryVersion={libraryVersion}
>
<Markdown rawContent={content} />
<Markdown
htmlMarkup={html?.markup ?? ''}
headingsOverride={html?.headings}
rawContent={content}
/>
</DocFeedbackProvider>
) : (
<Markdown rawContent={content} />
<Markdown
htmlMarkup={html?.markup ?? ''}
headingsOverride={html?.headings}
rawContent={content}
/>
)}
</div>
<div className="h-12" />
Expand Down
10 changes: 9 additions & 1 deletion src/components/FeedEntry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ export interface FeedEntry {
title: string
content: string
excerpt?: string | null
html?: {
markup: string
headings: Array<{ id: string; text: string; level: number }>
}
publishedAt: number
createdAt: number
updatedAt?: number
Expand Down Expand Up @@ -415,7 +419,11 @@ export function FeedEntry({

{/* Content */}
<div className="text-xs text-gray-900 dark:text-gray-100 leading-snug mb-3">
<Markdown rawContent={entry.content} />
<Markdown
htmlMarkup={entry.html?.markup ?? ''}
headingsOverride={entry.html?.headings}
rawContent={entry.content}
/>
</div>

{/* External Link */}
Expand Down
6 changes: 5 additions & 1 deletion src/components/FeedEntryTimeline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,11 @@ export function FeedEntryTimeline({
!expanded && 'line-clamp-6',
)}
>
<Markdown rawContent={entry.content} />
<Markdown
htmlMarkup={entry.html?.markup ?? ''}
headingsOverride={entry.html?.headings}
rawContent={entry.content}
/>
</div>

{/* Show more/less button */}
Expand Down
Loading