·
7 min read

Focus & Code Diff in Nuxt Content Code Blocks

Focus & Code Diff in Nuxt Content Code Blocks Image

Custom code blocks are essential for my blog as my articles usually contain a lot of code snippets. My blog is powered by Nuxt Content v2, which is a Nuxt 3 module. I already wrote an article about how you can create custom code blocks using Nuxt Content v2.

In this article, I'll show you how to focus certain lines of your code or highlight a diff inside a custom code block. This feature is adopted from Vitepress which provides similar functionality.

Focus Lines

Sometimes, you want to focus on certain lines of your code. For example, you want to highlight the most important lines of your code snippet.

In our example, we can do this by adding // [!code focus] in the line that should be highlighted:

```js [focus.js] export default { data() { return { msg: 'Focused!', // [!code focus] } }, } ```

The above code results in the following code block:

focus.js
export default { data() { return { msg: 'Focused!', // [!code focus] } }, }

If you hover over the code block, you can see that the whole code is visible without any highlighting.

Diff Lines

Another use case is to highlight a diff inside a code block. For example, you want to show the difference between two code snippets.

In our example, we can do this by adding // [!code ++] in the line that should be highlighted as added and // [!code --] in the line that should be highlighted as removed:

```js [diff.js] export default { data () { return { msg: 'Removed' // [!code --] msg: 'Added' // [!code ++] } } } ```

The above code results in the following code block:

diff.js
export default { data () { return { msg: 'Removed' // [!code --] msg: 'Added' // [!code ++] } } }

Implementation

Info

Update from January 2024: The following implementation is only necessary if you don't use shikiji, which provides transformers for the focus and diff syntax.

Let's now take a look at the implementation of this feature.

We opt out of the default code highlighting provided by Nuxt Content and handle it ourselves. We use Shiki to highlight the code, which is also used by Nuxt Content under the hood. The process of custom rendering of code blocks is documented in the Shiki README.

Let's start by writing a composable that returns a Shiki highlighter instance. As we'll have multiple Shiki instances on the same page we need to make sure that we only create one instance and reuse it. This is achieved by putting the highlighter instance in a ref outside of the composable.

Additionally, the composable exports the renderToHtml function from Shiki which we use later to render the highlighted code to HTML:

composables/useShikiHighlighter.ts
import { getHighlighter, Highlighter, renderToHtml } from 'shiki-es' const highlighter = ref<Highlighter | null>(null) export const useShikiHighlighter = () => { if (highlighter.value === null) { getHighlighter({ theme: 'dark-plus', themes: ['dark-plus'], langs: ['css', 'scss', 'js', 'ts', 'groovy', 'java', 'diff', 'vue', 'html', 'json', 'xml'], }).then((_highlighter) => { highlighter.value = _highlighter }) } return { highlighter, renderToHtml } }

Now it's time to create the custom code block component.

Info

If you never did this before, I'd recommend you to read my article about how to create a custom code block with Nuxt Content v2 first.

The basic structure of our custom ProseCode component looks like this:

components/content/ProseCode.vue
<script setup lang="ts"> interface Props { code?: string language?: string | null filename?: string | null highlights?: Array<number> } const props = withDefaults(defineProps<Props>(), { code: '', language: null, filename: null, highlights: () => [], }) </script> <template> <div class="mb-8 mt-4 rounded-md bg-[#1e1e1e]"> {{ code }} </div> </template>

Let's extend that component by using our useShikiHighlighter composable to highlight the code:

components/content/ProseCode.vue
<script setup lang="ts"> // ... const html = ref(null) const shiki = useShikiHighlighter() watch( shiki.highlighter, (newHighlighter) => { if (!newHighlighter || !props.code) { return } const tokens = newHighlighter.codeToThemedTokens(props.code.trim(), props.language ?? undefined) html.value = shiki.renderToHtml(tokens, { fg: newHighlighter.getForegroundColor('dark-plus'), bg: newHighlighter.getBackgroundColor('dark-plus'), // custom element renderer elements: { pre({ className, style, children }) { return `<pre tabindex="1" class="${className} bg-[#1e1e1e] style="${style}">${children}</pre>` }, code({ children, className, style }) { return `<code class="${className}" style="${style}">${children}</code>` }, line({ className, index, children }) { return `<div class="${className} w-full inline-flex"> <div>${children}</div> </div>` }, }, }) }, { immediate: true } ) </script> <template> <div class="mb-8 mt-4 rounded-md bg-[#1e1e1e]"> <div v-if="html" v-html="html"></div> <span v-else>{{ code }}</span> </div> </template>

Let's go through the code step by step:

  1. We create a html ref that will contain the highlighted code as HTML
  2. We use the useShikiHighlighter composable to get the highlighter instance and the renderToHtml function
  3. We watch the highlighter ref and call renderToHtml when the highlighter is available
  4. We use the codeToThemedTokens function to get the tokens for the code
  5. We use the renderToHtml function to render the tokens to HTML
  6. We use the elements option to customize the HTML output of the code block. The line element can be used to customize the HTML output of each line. We use it to add a div around each line to make it possible to highlight single lines.
  7. We use the v-html directive to render the highlighted code as HTML

You can now easily extend the code to highlight lines if certain comments are inside the code passed via props:

components/content/ProseCode.vue
<script setup lang="ts"> // ... const html = ref(null) const shiki = useShikiHighlighter() const removeCodeBlockIdentifiers = (code: string) => { return code .replace(codeBlockIdentifiers.FOCUS, '') .replace(codeBlockIdentifiers.DIFF_ADD, '') .replace(codeBlockIdentifiers.DIFF_REMOVE, '') } const codeBlockIdentifiers = { FOCUS: '// [!code focus]', DIFF_ADD: '// [!code ++]', DIFF_REMOVE: '// [!code --]', } as const const moreThanOneLineCode = computed(() => (props.code ? props.code.trim().split('\n').length > 1 : false)) watch( shiki.highlighter, (newHighlighter) => { if (!newHighlighter || !props.code) { return } const tokens = newHighlighter.codeToThemedTokens(props.code.trim(), props.language ?? undefined) html.value = shiki.renderToHtml(tokens, { fg: newHighlighter.getForegroundColor('dark-plus'), bg: newHighlighter.getBackgroundColor('dark-plus'), // custom element renderer elements: { pre({ className, style, children }: any) { const shallFocus = props.code.includes(codeBlockIdentifiers.FOCUS) const hasDiff = props.code.includes(codeBlockIdentifiers.DIFF_ADD) || props.code.includes(codeBlockIdentifiers.DIFF_REMOVE) return `<pre tabindex="1" class="${className} bg-[#1e1e1e] ${shallFocus ? 'has-focused-lines' : ''} ${ hasDiff ? 'has-diff' : '' }" style="${style}">${children}</pre>` }, code({ children, className, style }) { return `<code class="${className}" style="${style}">${children}</code>` }, line({ className, index, children }: any) { const shallHighlight = props.highlights?.includes(index + 1) ?? false const shallFocus = children.includes(codeBlockIdentifiers.FOCUS) const shallDiffRemove = children.includes(codeBlockIdentifiers.DIFF_REMOVE) const shallDiffAdd = children.includes(codeBlockIdentifiers.DIFF_ADD) const modifiedChildren = removeCodeBlockIdentifiers(children) let beforeElement = '<div class="ml-4"></div>' if (shallDiffAdd) { beforeElement = `<div class="ml-4 mr-6 text-[#738a9466]">${ index + 1 } <span class="text-[#10b981]">+</span></div>` } else if (shallDiffRemove) { beforeElement = `<div class="ml-4 mr-6 text-[#738a9466]">${ index + 1 } <span class="text-[#f43f5e]">-</span></div>` } else { beforeElement = `<div class="ml-4 mr-6 text-[#738a9466]">${index + 1}</div>` } return `<div class="${className} ${shallHighlight ? 'bg-[#363b46]' : ''} ${shallFocus ? 'has-focus' : ''} ${ shallDiffRemove ? 'diff remove' : '' } ${shallDiffAdd ? 'diff add' : ''} w-full inline-flex"> ${beforeElement} <div>${modifiedChildren}</div> </div>` }, }, }) }, { immediate: true } ) </script> <style scoped lang="scss"> :deep(pre) { > code { & .line.diff.remove { background-color: rgba(244, 63, 94, 0.2); opacity: 0.7; } & .line.diff.add { background-color: rgba(16, 185, 129, 0.2); } } } :deep(pre.has-focused-lines) { > code { & .line:not(.has-focus) { filter: blur(0.095rem); opacity: 0.4; transition: filter 0.35s, opacity 0.35s; } } } :deep(pre.has-focused-lines:hover) { > code { & .line:not(.has-focus) { filter: blur(0); opacity: 1; } } } </style>

The idea is quite simple: We look for our predefined set of comments inside the code and add a custom class to the line if the comment is present. We can then use this class to style the line accordingly.

Of course, you also need to remove these comments from the code before passing it to the codeToThemedTokens function. Otherwise, the comments would be rendered as HTML.

StackBlitz Demo

The code for this article is interactively available on StackBlitz:

Conclusion

In this article, you learned how to use the Nuxt content module to render code blocks that highlight single lines or highlight lines that were added or removed. By opting out of the default code highlighting of the Nuxt content module, you can use the Shiki library to render any custom code block that you need.

I like such small customizations that can make a big difference in the user experience. I hope you enjoyed this article and learned something new.

If you liked this article, follow me on Twitter to get notified about new blog posts and more content from me.

Alternatively (or additionally), you can subscribe to my weekly Vue newsletter:

I will never share any of your personal data. You can unsubscribe at any time.

If you found this article helpful.You will love these ones as well.
Rendering Dynamic Markdown in Nuxt 3+ Image

Rendering Dynamic Markdown in Nuxt 3+

Analyze Memory Leaks in Your Nuxt App Image

Analyze Memory Leaks in Your Nuxt App

Self-Host Your Nuxt App With Coolify Image

Self-Host Your Nuxt App With Coolify

A Comprehensive Guide to Data Fetching in Nuxt 3 Image

A Comprehensive Guide to Data Fetching in Nuxt 3