Skip to content
This repository has been archived by the owner on Feb 7, 2024. It is now read-only.

feat: add codeToHtmlDualThemes #5

Merged
merged 1 commit into from
Aug 13, 2023
Merged

feat: add codeToHtmlDualThemes #5

merged 1 commit into from
Aug 13, 2023

Conversation

antfu
Copy link
Owner

@antfu antfu commented Aug 13, 2023

shikiji added an experimental light/dark dual themes support. Different from markdown-it-shiki's approach which renders the code twice, shikiji's dual themes approach uses CSS variables to store the colors on each token. It's more performant with a smaller bundle size.

Use codeToHtmlDualThemes to render the code with dual themes:

import { getHighlighter } from 'shikiji'

const shiki = await getHighlighter({
  themes: ['nord', 'min-light'],
  langs: ['javascript'],
})

const code = shiki.codeToHtmlDualThemes('console.log("hello")', {
  lang: 'javascript',
  theme: {
    light: 'min-light',
    dark: 'nord',
  }
})

The following HTML will be generated (preview):

<pre
  class="shiki shiki-dual-themes min-light--nord"
  style="background-color: #ffffff;--shiki-dark-bg:#2e3440ff;color: #ffffff;--shiki-dark-bg:#2e3440ff"
  tabindex="0"
>
  <code>
    <span class="line">
      <span style="color:#1976D2;--shiki-dark:#D8DEE9">console</span>
      <span style="color:#6F42C1;--shiki-dark:#ECEFF4">.</span>
      <span style="color:#6F42C1;--shiki-dark:#88C0D0">log</span>
      <span style="color:#24292EFF;--shiki-dark:#D8DEE9FF">(</span>
      <span style="color:#22863A;--shiki-dark:#ECEFF4">&quot;</span>
      <span style="color:#22863A;--shiki-dark:#A3BE8C">hello</span>
      <span style="color:#22863A;--shiki-dark:#ECEFF4">&quot;</span>
      <span style="color:#24292EFF;--shiki-dark:#D8DEE9FF">)</span>
    </span>
  </code>
</pre>

To make it reactive to your site's theme, you need to add a short CSS snippet:

Query-based Dark Mode
@media (prefers-color-scheme: dark) {
  .shiki {
    background-color: var(--shiki-dark-bg) !important;
    color: var(--shiki-dark) !important;
  }
  .shiki span {
    color: var(--shiki-dark) !important;
  }
}
Class-based Dark Mode
html.dark .shiki {
  background-color: var(--shiki-dark-bg) !important;
  color: var(--shiki-dark) !important;
}
html.dark .shiki span {
  color: var(--shiki-dark) !important;
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant