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(plugin-shikiji): add support for twoslashOptions #335

Merged
merged 2 commits into from
Nov 11, 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
692 changes: 580 additions & 112 deletions docs/notes/theme/guide/代码/twoslash.md

Large diffs are not rendered by default.

16 changes: 13 additions & 3 deletions plugins/plugin-shikiji/src/node/highlight/highlight.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { HighlighterOptions, ThemeOptions } from '../types.js'
import { customAlphabet } from 'nanoid'
import { bundledLanguages, createHighlighter } from 'shiki'
import { logger } from 'vuepress/utils'
import { colors, logger } from 'vuepress/utils'
import { getLanguage } from './getLanguage.js'
import { baseTransformers, getInlineTransformers } from './transformers.js'

Expand Down Expand Up @@ -45,7 +45,13 @@ export async function highlight(
lang,
transformers: [
...baseTransformers,
...getInlineTransformers({ attrs, lang, enabledTwoslash, whitespace }),
...getInlineTransformers({
attrs,
lang,
enabledTwoslash,
whitespace,
twoslash: options.twoslash,
}),
...userTransformers,
],
meta: { __raw: attrs },
Expand All @@ -59,7 +65,11 @@ export async function highlight(
return rendered
}
catch (e) {
logger.error(e)
logger.error(
(e as Error)?.message,
'\n',
(e as Error)?.stack ? colors.gray(String((e as Error)?.stack)) : '',
)
return str
}
}
Expand Down
1 change: 1 addition & 0 deletions plugins/plugin-shikiji/src/node/highlight/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './highlight.js'
export * from './resolveTsPaths.js'
export * from './scanLanguages.js'
28 changes: 28 additions & 0 deletions plugins/plugin-shikiji/src/node/highlight/resolveTsPaths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import fs from 'node:fs/promises'
import path from 'node:path'
import process from 'node:process'

export async function resolveTsPaths(): Promise<Record<string, string[]> | undefined> {
const tsconfigPath = path.join(process.cwd(), 'tsconfig.json')
try {
const tsconfig = JSON.parse(await fs.readFile(tsconfigPath, 'utf-8'))
const paths = tsconfig.compilerOptions?.paths ?? undefined
const baseUrl = tsconfig.compilerOptions?.baseUrl

if (baseUrl && paths) {
const dirname = path.join(process.cwd(), baseUrl)
for (const key in paths) {
const value = paths[key]
if (Array.isArray(value))
paths[key] = value.map(v => path.resolve(dirname, v))
else if (value)
paths[key] = path.resolve(dirname, value)
}
}

return paths
}
catch {
return undefined
}
}
18 changes: 17 additions & 1 deletion plugins/plugin-shikiji/src/node/highlight/transformers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import type { TransformerTwoslashOptions } from '@shikijs/twoslash/core'
import type { ShikiTransformer } from 'shiki'
import type { VueSpecificOptions } from 'twoslash-vue'
import type { WhitespacePosition } from '../utils/index.js'
import process from 'node:process'
import {
transformerCompactLineOptions,
transformerNotationDiff,
Expand All @@ -10,7 +13,9 @@ import {
transformerRemoveNotationEscape,
transformerRenderWhitespace,
} from '@shikijs/transformers'
import { defaultTwoslashOptions } from '@shikijs/twoslash/core'
import { addClassToHast } from 'shiki'
import { isPlainObject } from 'vuepress/shared'
import { defaultHoverInfoProcessor, transformerTwoslash } from '../twoslash/rendererTransformer.js'
import { attrsToLines, resolveWhitespacePosition } from '../utils/index.js'

Expand Down Expand Up @@ -53,22 +58,33 @@ export const baseTransformers: ShikiTransformer[] = [
]

const vueRE = /-vue$/
export function getInlineTransformers({ attrs, lang, enabledTwoslash, whitespace }: {
export function getInlineTransformers({ attrs, lang, enabledTwoslash, whitespace, twoslash }: {
attrs: string
lang: string
enabledTwoslash: boolean
whitespace: boolean | WhitespacePosition
twoslash?: boolean | TransformerTwoslashOptions['twoslashOptions'] & VueSpecificOptions
}): ShikiTransformer[] {
const vPre = vueRE.test(lang) ? '' : 'v-pre'
const inlineTransformers: ShikiTransformer[] = [
transformerCompactLineOptions(attrsToLines(attrs)),
]

if (enabledTwoslash) {
const { compilerOptions, ...twoslashOptions } = isPlainObject(twoslash) ? twoslash : {}
const defaultOptions = defaultTwoslashOptions()
inlineTransformers.push(transformerTwoslash({
processHoverInfo(info) {
return defaultHoverInfoProcessor(info)
},
twoslashOptions: {
...defaultOptions,
...twoslashOptions,
compilerOptions: {
baseUrl: process.cwd(),
...compilerOptions,
},
},
}))
}
else {
Expand Down
16 changes: 14 additions & 2 deletions plugins/plugin-shikiji/src/node/shikiPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type {
import { isPlainObject } from 'vuepress/shared'
import { colors } from 'vuepress/utils'
import { copyCodeButtonPlugin } from './copy-code-button/index.js'
import { highlight, scanLanguages } from './highlight/index.js'
import { highlight, resolveTsPaths, scanLanguages } from './highlight/index.js'
import {
collapsedLinesPlugin,
highlightLinesPlugin,
Expand Down Expand Up @@ -47,7 +47,7 @@ export function shikiPlugin({

clientConfigFile: app => prepareClientConfigFile(app, {
copyCode: copyCode !== false,
twoslash: options.twoslash ?? false,
twoslash: !!options.twoslash,
}),

extendsMarkdown: async (md, app) => {
Expand All @@ -64,6 +64,18 @@ export function shikiPlugin({
}
}

if (options.twoslash) {
const paths = await resolveTsPaths()
if (paths) {
options.twoslash = isPlainObject(options.twoslash) ? options.twoslash : {}
options.twoslash.compilerOptions ??= {}
options.twoslash.compilerOptions.paths = {
...paths,
...options.twoslash.compilerOptions.paths,
}
}
}

md.options.highlight = await highlight(theme, options)
if (app.env.isDebug) {
logger.info(`highlight Loaded in: ${(performance.now() - start).toFixed(2)}ms`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ export interface VitePressPluginTwoslashOptions extends TransformerTwoslashVueOp

/**
* Create a Shiki transformer for VitePress to enable twoslash integration
*
* Add this to `markdown.codeTransformers` in `.vitepress/config.ts`
*/
export function transformerTwoslash(options: VitePressPluginTwoslashOptions = {}): ShikiTransformer {
const {
Expand Down
4 changes: 3 additions & 1 deletion plugins/plugin-shikiji/src/node/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { TransformerTwoslashOptions } from '@shikijs/twoslash/core'
import type {
BuiltinTheme,
BundledLanguage,
Expand All @@ -8,6 +9,7 @@ import type {
StringLiteralUnion,
ThemeRegistration,
} from 'shiki'
import type { VueSpecificOptions } from 'twoslash-vue'
import type { LocaleConfig } from 'vuepress/shared'

export type ShikiLang =
Expand Down Expand Up @@ -73,7 +75,7 @@ export interface HighlighterOptions {
* Enable transformerTwoslash
* @default false
*/
twoslash?: boolean
twoslash?: boolean | TransformerTwoslashOptions['twoslashOptions'] & VueSpecificOptions

/**
* Enable transformerRenderWhitespace
Expand Down
2 changes: 2 additions & 0 deletions theme/src/client/styles/twoslash.css
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
--twoslash-tag-warn-bg: var(--vp-c-warning-soft);
--twoslash-tag-annotate-color: var(--vp-c-green-1);
--twoslash-tag-annotate-bg: var(--vp-c-green-soft);
--twoslash-highlighted-bg: var(--vp-c-gray-soft);
--twoslash-highlighted-border: var(--vp-c-border);
}

/* Respect people's wishes to not have animations */
Expand Down