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 v1 #287

Open
wants to merge 2 commits into
base: master
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
2 changes: 2 additions & 0 deletions packages/site-kit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@
"svelte-persisted-store": "^0.9.2"
},
"devDependencies": {
"@shikijs/twoslash": "^1.5.1",
"@sveltejs/kit": "^2.5.7",
"@sveltejs/package": "^2.3.1",
"@types/node": "^20.12.11",
"flexsearch": "^0.7.43",
"magic-string": "^0.30.10",
"marked": "^12.0.2",
"prettier": "^3.2.5",
"shiki": "^1.5.1",
"shiki-twoslash": "^3.1.2",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we remove this?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh yeh this not needed anymore

"svelte": "^4.2.16",
"typescript": "^5.4.5",
Expand Down
65 changes: 21 additions & 44 deletions packages/site-kit/src/lib/markdown/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
import { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
import ts from 'typescript';
import { highlight } from './shiki.js';
import { SHIKI_LANGUAGE_MAP, escape, normalizeSlugify, transform } from './utils.js';

/**
Expand All @@ -18,9 +19,6 @@ const METADATA_REGEX =
/** @type {Map<string, string>} */
const CACHE_MAP = new Map();

/** @type {import('shiki-twoslash')} */
let twoslash_module;

/** @type {import('prettier')} */
let prettier_module;

Expand Down Expand Up @@ -112,11 +110,8 @@ export async function render_content_markdown(
body,
{ twoslashBanner, modules = [], cacheCodeSnippets = true, resolveTypeLinks } = {}
) {
twoslash_module ??= await import('shiki-twoslash');
prettier_module ??= await import('prettier');

const highlighter = await twoslash_module.createShikiHighlighter({ theme: 'css-variables' });

const { type_links, type_regex } = create_type_links(modules, resolveTypeLinks);
const SNIPPET_CACHE = await create_snippet_cache(cacheCodeSnippets);

Expand Down Expand Up @@ -144,7 +139,6 @@ export async function render_content_markdown(

let html = syntax_highlight({
filename,
highlighter,
language,
source,
twoslashBanner,
Expand Down Expand Up @@ -199,7 +193,7 @@ export async function render_content_markdown(
? `<a href="${type_links.get(name)?.relativeURL}">${name}</a>`
: '';
return `${prefix || ''}${link}`;
})
})
: text) +
'</code>'
);
Expand Down Expand Up @@ -454,8 +448,8 @@ export async function convert_to_ts(js_code, indent = '', offset = '') {
js_code.includes('---cut---')
? js_code.indexOf('\n', js_code.indexOf('---cut---')) + 1
: js_code.includes('/// file:')
? js_code.indexOf('\n', js_code.indexOf('/// file:')) + 1
: 0
? js_code.indexOf('\n', js_code.indexOf('/// file:')) + 1
: 0
);
code.appendLeft(insertion_point, offset + import_statements + '\n');
}
Expand Down Expand Up @@ -930,25 +924,18 @@ function replace_blank_lines(html) {
* source: string,
* filename: string,
* language: string,
* highlighter: ReturnType<import('shiki-twoslash').createShikiHighlighter>
* twoslashBanner?: TwoslashBanner
* options: SnippetOptions
* }} param0
*/
function syntax_highlight({ source, filename, language, highlighter, twoslashBanner, options }) {
function syntax_highlight({ source, filename, language, twoslashBanner, options }) {
let html = '';

if (/^(dts|yaml|yml)/.test(language)) {
html = replace_blank_lines(
twoslash_module.renderCodeToHTML(
source,
language === 'dts' ? 'ts' : language,
{ twoslash: false },
{ themeName: 'css-variables' },
highlighter
)
);
} else if (/^(js|ts)/.test(language)) {
// console.log({ source, language });

if (/^(dts|yaml|yml)$/.test(language)) {
html = replace_blank_lines(highlight(source, language === 'dts' ? 'ts' : language));
} else if (/^(js|ts)$/.test(language)) {
try {
const banner = twoslashBanner?.(filename, source, language, options);

Expand All @@ -963,24 +950,7 @@ function syntax_highlight({ source, filename, language, highlighter, twoslashBan
}
}

const twoslash = twoslash_module.runTwoSlash(source, language, {
defaultCompilerOptions: {
allowJs: true,
checkJs: true,
target: ts.ScriptTarget.ES2022,
types: ['svelte', '@sveltejs/kit']
}
});

html = twoslash_module.renderCodeToHTML(
twoslash.code,
'ts',
{ twoslash: true },
// @ts-ignore Why shiki-twoslash requires a theme name?
{},
highlighter,
twoslash
);
html = highlight(source, 'ts', !/^(tutorial)/.test(filename));
} catch (e) {
console.error(`Error compiling snippet in ${filename}`);
// @ts-ignore
Expand Down Expand Up @@ -1020,13 +990,20 @@ function syntax_highlight({ source, filename, language, highlighter, twoslashBan
})
.join('')}</code></pre>`;
} else {
const highlighted = highlighter.codeToHtml(source, {
lang: SHIKI_LANGUAGE_MAP[/** @type {keyof typeof SHIKI_LANGUAGE_MAP} */ (language)]
});
const highlighted = highlight(
source,
SHIKI_LANGUAGE_MAP[/** @type {keyof typeof SHIKI_LANGUAGE_MAP} */ (language)] ?? language
);

html = replace_blank_lines(highlighted);
}

// Remove any instance of element:
// <div class="error"></div>, it can have any content inside.
// And <span class="error-behind"></span> too
html = html.replace(/<div class="error">[^]*?<\/div>/g, '');
html = html.replace(/<\s*span\s*class="error-behind"[^>]*>.*?<\s*\/span\s*>/gs, '');

return html;
}

Expand Down
63 changes: 63 additions & 0 deletions packages/site-kit/src/lib/markdown/shiki.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { rendererClassic, transformerTwoslash } from '@shikijs/twoslash';
import { createCssVariablesTheme, getWasmInlined } from 'shiki';
import { getHighlighterCore } from 'shiki/core';
import css from 'shiki/langs/css.mjs';
import diff from 'shiki/langs/diff.mjs';
import html from 'shiki/langs/html.mjs';
import javascript from 'shiki/langs/javascript.mjs';
import json from 'shiki/langs/json.mjs';
import markdown from 'shiki/langs/markdown.mjs';
import bash from 'shiki/langs/shellscript.mjs';
import svelte from 'shiki/langs/svelte.mjs';
import typescript from 'shiki/langs/typescript.mjs';
import yaml from 'shiki/langs/yaml.mjs';
import ts from 'typescript';

const svelte_theme = createCssVariablesTheme({
name: 'css-variables',
variablePrefix: '--shiki-',
variableDefaults: {},
fontStyle: true
});

const shiki = await getHighlighterCore({
themes: [svelte_theme],
langs: [javascript, svelte, typescript, diff, json, yaml, markdown, html, css, bash],
loadWasm: getWasmInlined,
langAlias: {
sh: 'bash'
}
});

/**
* @param {string} code
* @param {string} lang
* @param {boolean} twoslash
*/
export function highlight(code, lang, twoslash = false) {
return shiki.codeToHtml(code, {
lang,
themes: { light: 'css-variables' },
theme: 'css-variables',
transformers: [
transformerTwoslash({
renderer: rendererClassic(),
filter: () => twoslash,
// onTwoslashError: (error, code, lang) => {
// console.error('Shiki twoslash error: ', { lang, code, error });
// },
// onShikiError: (error, code, lang) => {
// console.error('Shiki error: ', { lang, code, error });
// },
twoslashOptions: {
compilerOptions: {
allowJs: true,
checkJs: true,
target: ts.ScriptTarget.ES2022,
types: ['svelte', '@sveltejs/kit', '@types/node']
}
}
})
]
});
}
2 changes: 1 addition & 1 deletion packages/site-kit/src/lib/styles/code.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ body,
body.light,
body.dark {
--shiki-color-text: var(--sk-code-base);
--shiki-color-background: hsl(var(--sk-back-3-hsl));
--shiki-background: hsl(var(--sk-back-3-hsl));
--shiki-token-constant: var(--sk-code-base);
--shiki-token-string: var(--sk-code-string);
--shiki-token-comment: var(--sk-code-comment);
Expand Down
10 changes: 10 additions & 0 deletions packages/site-kit/src/lib/styles/text.css
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,16 @@
color: var(--sk-code-diff-base);
}

.text :where(pre.shiki code) {
display: flex;
flex-direction: column;
}

.text :where(pre.shiki code .line) {
flex-grow: 1 1 auto;
min-height: 22.09px;
}

.language-diff :where(.inserted, .deleted) {
position: relative;
}
Expand Down
50 changes: 50 additions & 0 deletions pnpm-lock.yaml

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