Skip to content
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

feat: shiki highlighter #96

Merged
merged 2 commits into from
Jun 28, 2024
Merged
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 @@ -50,6 +50,7 @@
"@radix-ui/react-tabs": "1.1.0",
"@radix-ui/react-toast": "1.2.1",
"@radix-ui/react-tooltip": "1.1.1",
"@shikijs/transformers": "1.9.1",
"@tanstack/query-sync-storage-persister": "5.45.0",
"@tanstack/react-query": "5.45.1",
"@tanstack/react-query-persist-client": "5.45.1",
Expand Down Expand Up @@ -93,6 +94,7 @@
"rehype-parse": "9.0.0",
"rehype-sanitize": "6.0.0",
"rehype-stringify": "10.0.0",
"shiki": "1.9.1",
"sonner": "^1.5.0",
"superjson": "2.2.1",
"swiper": "11.1.4",
Expand Down
25 changes: 25 additions & 0 deletions pnpm-lock.yaml

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

1 change: 1 addition & 0 deletions src/renderer/src/components/ui/code-highlighter/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./copy-button"
export * from "./shiki"
162 changes: 162 additions & 0 deletions src/renderer/src/components/ui/code-highlighter/shiki/Shiki.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
/* eslint-disable @eslint-react/dom/no-dangerously-set-innerhtml */
import { useUIStore } from "@renderer/store"
import type { FC } from "react"
import { useLayoutEffect, useMemo, useRef, useState } from "react"
import type {
BundledLanguage,
BundledTheme,
DynamicImportLanguageRegistration,
DynamicImportThemeRegistration,
} from "shiki"
import { createHighlighterCore } from "shiki/core"
import { default as getWasm } from "shiki/wasm"

import { CopyButton } from "../copy-button"
import { shikiTransformers } from "./shared"

const shiki = await createHighlighterCore({
themes: [

import("shiki/themes/github-dark.mjs"),
],
langs: [],
loadWasm: getWasm,
})

export interface ShikiProps {
language: string | undefined
code: string

attrs?: string

}

let langModule: Record<
BundledLanguage,
DynamicImportLanguageRegistration
> | null = null
let themeModule: Record<BundledTheme, DynamicImportThemeRegistration> | null =
null

export const ShikiHighLighter: FC<ShikiProps> = (props) => {
const { code, language } = props
const loadThemesRef = useRef([] as string[])
const loadLanguagesRef = useRef([] as string[])

const [loaded, setLoaded] = useState(false)

const codeTheme = useUIStore((s) => s.codeHighlightTheme)
useLayoutEffect(() => {
let isMounted = true
setLoaded(false)

async function loadShikiLanguage(language: string, languageModule: any) {
if (!shiki) return
if (!shiki.getLoadedLanguages().includes(language)) {
await shiki.loadLanguage(await languageModule())
}
}
async function loadShikiTheme(theme: string, themeModule: any) {
if (!shiki) return
if (!shiki.getLoadedThemes().includes(theme)) {
await shiki.loadTheme(await themeModule())
}
}

async function register() {
if (!language || !codeTheme) return

const [{ bundledLanguages }, { bundledThemes }] =
langModule && themeModule ?
[
{
bundledLanguages: langModule,
},
{ bundledThemes: themeModule },
] :
await Promise.all([import("shiki/langs"), import("shiki/themes")])

langModule = bundledLanguages
themeModule = bundledThemes

if (
language &&
loadLanguagesRef.current.includes(language) &&
codeTheme &&
(loadThemesRef.current.includes(codeTheme))
) {
return
}
return Promise.all([
(async () => {
if (language) {
const importFn = (bundledLanguages as any)[language]
if (!importFn) return
await loadShikiLanguage(language || "", importFn)
loadLanguagesRef.current.push(language)
}
})(),
(async () => {
if (codeTheme) {
const importFn = (bundledThemes as any)[codeTheme]
if (!importFn) return
await loadShikiTheme(codeTheme || "", importFn)
loadThemesRef.current.push(codeTheme)
}
})(),
])
}
register().then(() => {
if (isMounted) {
setLoaded(true)
}
})
return () => {
isMounted = false
}
}, [codeTheme, language])

if (!loaded) {
return (
<pre>
<code>{code}</code>
</pre>
)
}
return <ShikiCode {...props} codeTheme={codeTheme} />
}

const ShikiCode: FC<ShikiProps & {
codeTheme: string

}> = ({ code, language, codeTheme }) => {
const rendered = useMemo(() => {
try {
return shiki.codeToHtml(code, {
lang: language!,
themes: {
dark: codeTheme,
light: codeTheme,
},
transformers: shikiTransformers,
})
} catch {
// console.error(err)
return null
}
}, [code, language, codeTheme])

if (!rendered) {
return (
<pre>
<code>{code}</code>
</pre>
)
}
return (
<div className="group relative">
<div dangerouslySetInnerHTML={{ __html: rendered }} />
<CopyButton value={code} className="absolute right-2 top-2 opacity-0 duration-200 group-hover:opacity-100" />
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./Shiki"
12 changes: 12 additions & 0 deletions src/renderer/src/components/ui/code-highlighter/shiki/shared.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {
transformerMetaHighlight,
transformerNotationDiff,
transformerNotationHighlight,
} from "@shikijs/transformers"
import type { ShikiTransformer } from "shiki"

export const shikiTransformers: ShikiTransformer[] = [
transformerMetaHighlight(),
transformerNotationDiff(),
transformerNotationHighlight(),
]
2 changes: 1 addition & 1 deletion src/renderer/src/components/ui/image/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const usePreviewImages = () => {
</div>
),
title: "Image",

overlay: true,
CustomModalComponent: ({ children }) => children,
clickOutsideToDismiss: true,
})
Expand Down
31 changes: 13 additions & 18 deletions src/renderer/src/components/ui/modal/stacked/overlay.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useUIStore } from "@renderer/store"
import { m } from "framer-motion"

import { RootPortal } from "../../portal"
Expand All @@ -9,20 +8,16 @@ export const ModalOverlay = ({
}: {
onClick?: () => void
zIndex?: number
}) => {
const modalSettingOverlay = useUIStore((state) => state.modalOverlay)
if (!modalSettingOverlay) return null
return (
<RootPortal>
<m.div
id="modal-overlay"
onClick={onClick}
className="fixed inset-0 z-[11] bg-zinc-50/80 dark:bg-neutral-900/80"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
style={{ zIndex }}
/>
</RootPortal>
)
}
}) => (
<RootPortal>
<m.div
id="modal-overlay"
onClick={onClick}
className="fixed inset-0 z-[11] bg-zinc-50/80 dark:bg-neutral-900/80"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
style={{ zIndex }}
/>
</RootPortal>
)
7 changes: 6 additions & 1 deletion src/renderer/src/components/ui/modal/stacked/provider.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useUIStore } from "@renderer/store"
import { AnimatePresence } from "framer-motion"
import { useAtomValue } from "jotai"
import type { FC, PropsWithChildren } from "react"
Expand All @@ -21,6 +22,10 @@ const ModalStack = () => {
// Vite HMR issue
// useDismissAllWhenRouterChange()

const modalSettingOverlay = useUIStore((state) => state.modalOverlay)

const forceOverlay = stack.some((item) => item.overlay)

return (
<AnimatePresence mode="popLayout">
{stack.map((item, index) => (
Expand All @@ -31,7 +36,7 @@ const ModalStack = () => {
isTop={index === stack.length - 1}
/>
))}
{stack.length > 0 && <ModalOverlay zIndex={MODAL_STACK_Z_INDEX + stack.length - 1} />}
{stack.length > 0 && (modalSettingOverlay || forceOverlay) && <ModalOverlay zIndex={MODAL_STACK_Z_INDEX + stack.length - 1} />}
</AnimatePresence>
)
}
Loading
Loading