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

refactor(plugin-shiki): code and test refactor #302

Merged
merged 5 commits into from
Dec 13, 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
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const createMarkdownFilePathGetter = (
const rawRender = md.render.bind(md)

// we need to store file path before each render
md.render = (src, env: MarkdownEnv) => {
md.render = (src, env: MarkdownEnv = {}) => {
store.path = env.filePathRelative

return rawRender(src, env)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { BundledLanguage, BundledTheme, HighlighterGeneric } from 'shiki'
import { createHighlighter } from 'shiki'
import { bundledLanguageNames } from '../../shiki.js'
import type { ShikiHighlightOptions } from '../../types.js'

export const createShikiHighlighter = async ({
langs = bundledLanguageNames,
langAlias = {},
defaultLang,
shikiSetup,
...options
}: ShikiHighlightOptions = {}): Promise<
HighlighterGeneric<BundledLanguage, BundledTheme>
> => {
const shikiHighlighter = await createHighlighter({
langs,
langAlias,
themes:
'themes' in options
? Object.values(options.themes)
: [options.theme ?? 'nord'],
})

await shikiSetup?.(shikiHighlighter)

return shikiHighlighter
}
Original file line number Diff line number Diff line change
@@ -1,56 +1,37 @@
import { transformerCompactLineOptions } from '@shikijs/transformers'
import type MarkdownIt from 'markdown-it'
import { createHighlighter } from 'shiki'
import type { App } from 'vuepress'
import { bundledLanguageNames } from '../../shiki.js'
import type { BundledLanguage, BundledTheme, HighlighterGeneric } from 'shiki'
import {
getTransformers,
whitespaceTransformer,
} from '../../transformers/getTransformers.js'
import type { ShikiHighlightOptions } from '../../types.js'
import { attrsToLines } from '../../utils.js'
import { createMarkdownFilePathGetter } from './createMarkdownFilePathGetter.js'
import type { MarkdownFilePathGetter } from './createMarkdownFilePathGetter.js'
import { getLanguage } from './getLanguage.js'
import { handleMustache } from './handleMustache.js'

export const applyHighlighter = async (
md: MarkdownIt,
app: App,
{
langs = bundledLanguageNames,
langAlias = {},
defaultLang,
transformers: userTransformers = [],
...options
}: ShikiHighlightOptions = {},
): Promise<void> => {
const logLevel = options.logLevel ?? (app.env.isDebug ? 'debug' : 'warn')
const getMarkdownFilePath =
logLevel === 'debug' ? createMarkdownFilePathGetter(md) : null

const highlighter = await createHighlighter({
langs,
langAlias,
themes:
'themes' in options
? Object.values(options.themes)
: [options.theme ?? 'nord'],
})

await options.shikiSetup?.(highlighter)
type MarkdownItHighlight = (
content: string,
language: string,
attrs: string,
) => string

export const getHighLightFunction = (
highlighter: HighlighterGeneric<BundledLanguage, BundledTheme>,
options: ShikiHighlightOptions,
markdownFilePathGetter: MarkdownFilePathGetter,
): MarkdownItHighlight => {
const transformers = getTransformers(options)
const loadedLanguages = highlighter.getLoadedLanguages()

md.options.highlight = (content, language, attrs) =>
return (content, language, attrs) =>
handleMustache(content, (str) =>
highlighter.codeToHtml(str, {
lang: getLanguage(
language,
loadedLanguages,
defaultLang,
logLevel,
getMarkdownFilePath!,
options,
markdownFilePathGetter,
),
meta: {
/**
Expand All @@ -65,7 +46,7 @@ export const applyHighlighter = async (
? [transformerCompactLineOptions(attrsToLines(attrs))]
: []),
...whitespaceTransformer(attrs, options.whitespace),
...userTransformers,
...(options.transformers ?? []),
],
...('themes' in options
? {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { isSpecialLang } from 'shiki'
import { colors } from 'vuepress/utils'
import type { ShikiHighlightOptions } from '../../types.js'
import { logger, resolveLanguage } from '../../utils.js'
import type { MarkdownFilePathGetter } from './createMarkdownFilePathGetter.js'

Expand All @@ -8,9 +9,8 @@ const WARNED_LANGS = new Set<string>()
export const getLanguage = (
lang: string,
loadedLanguages: string[],
defaultLang: string | undefined,
logLevel: string,
getMarkdownFilePath: MarkdownFilePathGetter,
{ defaultLang, logLevel }: ShikiHighlightOptions,
markdownFilePathGetter: MarkdownFilePathGetter,
): string => {
let result = resolveLanguage(lang)

Expand All @@ -26,7 +26,7 @@ export const getLanguage = (
// log file path if unknown language is found
if (logLevel === 'debug') {
logger.info(
`Unknown language ${colors.cyan(result)} found in ${colors.cyan(getMarkdownFilePath())}`,
`Unknown language ${colors.cyan(result)} found in ${colors.cyan(markdownFilePathGetter())}`,
)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './createMarkdownFilePathGetter.js'
export * from './createShikiHighlighter.js'
export * from './getHighLightFunction.js'
2 changes: 1 addition & 1 deletion plugins/markdown/plugin-shiki/src/node/markdown/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export * from './applyHighlighter/index.js'
export * from './highlighter/index.js'
export * from './highlightLinesPlugin.js'
export * from './preWrapperPlugin.js'
82 changes: 46 additions & 36 deletions plugins/markdown/plugin-shiki/src/node/shikiPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,50 +8,60 @@ import {
} from '@vuepress/highlighter-helper'
import type { Plugin } from 'vuepress/core'
import { isPlainObject } from 'vuepress/shared'
import { createMarkdownFilePathGetter } from './markdown/highlighter/createMarkdownFilePathGetter.js'
import type { MarkdownItPreWrapperOptions } from './markdown/index.js'
import {
applyHighlighter,
createShikiHighlighter,
getHighLightFunction,
highlightLinesPlugin,
preWrapperPlugin,
} from './markdown/index.js'
import type { ShikiPluginOptions } from './options.js'
import { prepareClientConfigFile } from './prepareClientConfigFile.js'

export const shikiPlugin = (options: ShikiPluginOptions = {}): Plugin => {
const opt: ShikiPluginOptions = {
preWrapper: true,
lineNumbers: true,
collapsedLines: 'disable',
...options,
}
export const shikiPlugin = (_options: ShikiPluginOptions = {}): Plugin => {
return (app) => {
// FIXME: Remove in stable version
// eslint-disable-next-line @typescript-eslint/no-deprecated
const { code } = app.options.markdown
const options = {
...(isPlainObject(code) ? code : {}),
..._options,
}

options.logLevel ??= app.env.isDebug ? 'debug' : 'warn'
options.preWrapper ??= true
options.lineNumbers ??= true
options.collapsedLines ??= 'disable'

return {
name: '@vuepress/plugin-shiki',

extendsMarkdown: async (md) => {
const { preWrapper, lineNumbers, collapsedLines } = options

const markdownFilePathGetter = createMarkdownFilePathGetter(md)
const shikiHighlighter = await createShikiHighlighter(options)

md.options.highlight = getHighLightFunction(
shikiHighlighter,
options,
markdownFilePathGetter,
)

md.use(highlightLinesPlugin)
md.use<MarkdownItPreWrapperOptions>(preWrapperPlugin, { preWrapper })
if (preWrapper) {
md.use<MarkdownItLineNumbersOptions>(lineNumbersPlugin, {
lineNumbers,
})
md.use<MarkdownItCollapsedLinesOptions>(collapsedLinesPlugin, {
collapsedLines,
})
}
},

return {
name: '@vuepress/plugin-shiki',

extendsMarkdown: async (md, app) => {
// FIXME: Remove in stable version
// eslint-disable-next-line @typescript-eslint/no-deprecated
const { code } = app.options.markdown

await applyHighlighter(md, app, {
...(isPlainObject(code) ? code : {}),
...options,
})

const { preWrapper, lineNumbers, collapsedLines } = opt

md.use(highlightLinesPlugin)
md.use<MarkdownItPreWrapperOptions>(preWrapperPlugin, { preWrapper })
if (preWrapper) {
md.use<MarkdownItLineNumbersOptions>(lineNumbersPlugin, {
lineNumbers,
})
md.use<MarkdownItCollapsedLinesOptions>(collapsedLinesPlugin, {
collapsedLines,
})
}
},

clientConfigFile: (app) => prepareClientConfigFile(app, opt),
clientConfigFile: () => prepareClientConfigFile(app, options),
}
}
}
Loading
Loading