DlCode

Display your code snippets with syntax highlighting, copy, tabs, transformations and more

The DlCode block component displays code snippets in a visually appealing and readable format. Among others it supports syntax highlighting, copy-to-clipboard functionality, easily integrates into your content pages of any kind. Use this component whenever you want to showcase code examples or command-line instructions to your users.

Features

  • 🖍️ multiple-language syntax highlighting with Shiki
  • 🎨 configurable highlighter
  • 🖌️ built-in visual transformations: highlighting, focusing, diffing
  • 🧑‍💻 custom and pre-built code transformations
  • 🪄 dynamic fragments resolving
  • 📋 one-click copy to clipboard
  • 🗂️ automatic code blocks tabbing
  • 🗂️ automatic tabs overlapping
  • 📏 collapsible long code blocks
  • 🔗 internal reference links with JSDoc @link tag
  • 🧩 theme-friendly visual adjustments
  • ⚠️ extensive error reporter

Usage

Use the ::dl-code as a block component with your Markdown code block provided in the default slot.

::dl-code```tsconst text: string = 'text';```::

With a tab

Notice that in the previous example, no tabs are displayed above the code block. To show tabs (the filename with its extension), you need to set the tabs prop, aligned with MDC formatting.

::dl-code{tabs="tab.md"}```tsconst text: string = 'text';```::

With multiple tabs

To display multiple tabs with different code blocks, separate the tab names with commas. Remember that the number of code blocks must be the same as the number of defined tabs. Hence, different setup will print the Nuxt Error.

::dl-code{tabs="first-tab.md, second-tab.md"}```tsconst first: string = 'first';``````tsconst second: string = 'second';```::
::dl-code{tabs="first-tab.md, second-tab.md"}```tsconst second: string = 'second';``````tsconst first: string = 'first';```::

The difference between the tab contents is simply to demonstrate how switching between tabs works - the code will execute the same result.

Tabs overlapping

If you define multiple tab code components, the total width of the tab list will be calculated. If the tabs would overlap the block container, they will be grouped into a special context menu accessible from the right side of the component. Here is the simple example.

Be aware that this calculation must be performed only client-side. As a result, for the first visible block, you may see a loading indicator that will eventually be replaced by the component's content.

With visual transforms (highlighting, diffing, focusing)

The DlCode component implements couple of Shiki's visual transformers that you can use to highlight specific parts of your code. These transforms are applied by adding special markers inside your code blocks. You can use the same syntax as their original configuration presents.

Implemented transforms are:

  • transformerNotationHighlight,
  • transformerNotationDiff,
  • transformerNotationFocus,

and this is how you can use them.

Highlighting specific lines

::dl-code```tsconst greet = (name: string) => {  // use [\!\code highlight] or [\!\code highlight:2] to cover multiple lines  return `Hi, ${name}!`;};```::
const greet = (name: string) => {  return `Hi, ${name}!`;};

The ! character has been escaped manually to demonstrate the code usage, remove the backslash when using it.

Diffing the code blocks

::dl-code```tsconst greet = (name: string) => {  // use [\!\code ++] or [\!\code ++:3] to cover multiple lines */  // return `Hi, ${name}!`;};```::
const greet = (name: string) => {  return `Hi, ${name}!`;  return `Hello, ${name}!`;};

The ! character has been escaped manually to demonstrate the code usage, remove the backslash when using it.

Focusing (unbluring) specific lines of code

::dl-code```tsconst greet = (name: string) => {  // use [\!\code focus] or [\!\code focus:2] to cover multiple lines  return `Hi, ${name}!`;};```::
const greet = (name: string) => {  return `Hi, ${name}!`;};

The ! character has been escaped manually to demonstrate the code usage, remove the backslash when using it.

With dynamic string replacement

The DlCode component supports dynamic string replacement within code blocks. This might be particularly very useful when you want to showcase code snippets that include variables or placeholders that should be replaced with actual values at runtime. To enable this feature, use the dynamic prop to provide the string that should be injected. Within your code block add :dl-dynamic: wherever you want the replacement to occur. This is how you can do it:

::dl-code{dynamic="value"}```tsconst item = :/dl-dynamic/:;// results in (when rendered): const item = value;```::

The :dl-dynamic: placeholder will be replaced with the value provided by the dynamic prop when the code block is rendered. For example, we use this feature on the utilities page to provide a dynamic imports description for certain utilities. So this solution might be a great way to handle dynamic values within your shareable components.

Global Configuration

While basic, component-based configuration is managed through the props, the DlCode component also supports several global options. These options are set in the app.config.ts file under the dl.components.DlCode key. Below you'll find a list of all available options and details on how to configure them.

extensionIcons

An object mapping file extensions to icon names, used in the component tabs.

Extension to Icon mapping

Under the hood, DocLayer uses the Nuxt Icon Module (with the vscode set) to provide icons for the DlCode component tab list. When defining a tab name as a file, its extension must correspond to a specific icon name (e.g., .sh ➡️ shell). Sometimes these icons have different names and don’t follow extension definitions. This mapping helps avoid icon display issues.

More about module configuration, you can read here.

typedefaultrequired
Record<string, string>see belowno

Below are the settings provided by default.

export default defineDoclayerAppConfig({  dl: {    // the rest of the config    components: {      DlCode: {        extensionIcons: {          default: 'shell', // required          example: 'dotenv', // for .env.example file          mjs: 'js-official',          cjs: 'js-official',          ts: 'typescript-official',          sh: 'shell',          terminal: 'shell',          md: 'markdown',          yaml: 'light-yaml',          yml: 'light-yaml',          env: 'dotenv',        },      },    },  },});

To extend the list of icons, simply define the same object inside your app.config.ts file and add new extension-to-icon mappings.

highlighter

This object configures the custom implementation of the Shiki code highlighter.

Custom Highlighter

Although Nuxt Content provides a built-in Shiki highlighter that automatically generates code blocks, we've decided to build our own custom DlCodeHighlighter component with a custom implementation of Shiki.

This gives us greater control over how code snippets are rendered, flexibility for custom configuration, and - most importantly - the ability to perform post-rendering code transformations, such as escaping specific code sections, which you can control as well.

typedefaultrequired
Highlightersee belowno

Below are the settings provided by default.

import type { BundledLanguage } from 'shiki/bundle/web';export default defineDoclayerAppConfig({  dl: {    // the rest of the config    components: {      DlCode: {        highlighter: {          langs: [            'sh',            'bash',            'html',            `xml`,            'md',            'mdc',            'markdown',            'vue',            'yml',            'ts',            'typescript',            'js',            'json',            'css',            'scss',            'php',          ] satisfies BundledLanguage[],          themes: { dark: 'github-dark-default', light: 'github-light-default' },        },      },    },  },});

To add more languages for the highlighter, simply provide your own list in the configuration object inside the app.config.ts file, they will be merged. If you want to specify a new themes, be aware that they will replace the default github themes.

Single Shiki instance

Please note that the highlighter uses a single, globally defined instance of the Shiki. If you want to use different highlighter instances for specific code blocks, you can achieve this by using the utilShikiHighlighter composable.

Code transformer

Note that the highlighter uses a specialized code transformer. This transformer processes the contents of code blocks inside the DlCode component and is currently used to escape selected chunks of code. The transformer is configured globally via dl.transformers.code.

maxHeight

Value that lets you set the maximum height of the code block. If the content exceeds this height, an expand button will appear. To always show the full block, set a large value (e.g., 1000rem).

typedefaultrequired
'${string}rem'50remno

lazy

Determines whether the DlCode component should be lazy loaded.

typedefaultrequired
booleanfalseno

Props

Here are the properties you can use with the DlCode component. Each property should be set on an individual component instance; they do not affect the global configuration. More about defining properties in MDC components you can read here.

nametypedefaultdescription
lazybooleanundefined

Whether to lazy load the component.

tabsstring

empty string

Comma-separated list of tab names (file names) for code blocks.

maxHeightstring50rem

Maximum height of the code block.

dynamicstringundefined

Handles dynamic string to be replaced within the code with :dl-dynamic: placeholder. Read more here.

Slots

namedescription
default

Default slot for the code content.

ui

Dedicated slot for defining the component’s ui object. More about styling MDC components you can read here.

Styling

Styling from Markdown

Every DocLayer component can be styled directly within your Markdown file using dedicated slot/property configuration. This allows you to customize the appearance of the component's markup elements without modifying global styles. More about components styling you can read here.

Below you'll find the default set of Tailwind classes for the component's dedicated markup elements.

<script lang="ts">const ui = defineDoclayerComponentUi({  base: [    'uc-code-block-border',    'uc-code-block-bg',    'u-space-mt',    'u-border-radius',    'border',    'pb-0',    'max-h-[50rem]',    'min-w-[20rem]',    'relative',    'overflow-hidden',    'z-1',  ],  tab: [    'u-text-color',    'u-space-p/2',    'pr-0',    'max-w-fit',    'items-center',    'relative',    'opacity-50',    'cursor-pointer',    'transition-all',  ],  tabInsert: [    'invisible',    'pl-2',    'h-10',    'flex',    'items-center',    'justify-self-start',    'rounded-sm',    'text-sm',    'whitespace-nowrap',  ],  tabs: [    'uc-code-block-tabs-bg',    'uc-code-block-border',    'flex',    'flex-row',    'border-b',    'rounded-t-lg',    'pr-14',    'overflow-hidden',  ],  overlappedTab: ['visible!'],  overlappedTabsDropdown: [],  tabsSkeleton: ['absolute', 'top-[1.2rem]', 'left-4', 'h-6', 'w-[90%]', 'bg-gray-300', 'dark:bg-gray-700'],  code: ['uc-code-block-pre-bg', 'u-space-px', 'py-4', 'rounded-b-lg', 'text-left'],  actions: ['flex', 'items-end', 'justify-end', 'space-x-2', 'absolute', 'top-[0.9rem]', 'right-[0.9rem]', 'max-w-fit'],  actionButton: ['u-border-radius', 'flex', 'items-center', 'justify-center', 'w-8', 'h-8', 'transition-all'],  heightAdjustmentButton: ['absolute', 'bottom-[0.8rem]', 'right-[0.8rem]', 'z-5'],});</script>

CSS Variables

Here is a set of CSS variables you can use to customize the appearance of the DlCode component globally. More about theming and styling with CSS variables, you can read here.

@theme {  --app-code-block-bg: var(--app-block-bg);  --app-code-block-highlight-bg: light-dark(var(--color-gray-100), var(--color-gray-900));  --app-code-block-text-size: var(--app-code-text-size);  --app-code-block-text-line-height: var(--app-code-text-line-height);  --app-code-block-diff-add-bg: color-mix(    in srgb,    light-dark(var(--color-green-300), var(--color-green-800)) 20%,    transparent  );  --app-code-block-diff-add-text-color: var(--color-green-600);  --app-code-block-diff-remove-bg: color-mix(    in srgb,    light-dark(var(--color-amber-200), var(--color-amber-800)) 20%,    transparent  );  --app-code-block-diff-remove-text-color: var(--color-amber-500);  --app-code-block-blur-factor: 2px;  --app-code-block-border: var(--app-border-color);  --app-code-block-tabs-bg:    to bottom right, light-dark(var(--color-gray-100), var(--app-bg-dark)),    light-dark(var(--app-bg-light), var(--color-gray-950));  --app-code-block-pre-bg: light-dark(var(--color-white), #050505);  --app-code-block-bottom-shade-bg: to bottom, transparent, var(--app-code-block-pre-bg);  --app-code-block-bottom-shade-height: 3rem;}

CSS Utilities

Below are the CSS utility classes used by the DlCode component. They make use of the CSS variables described above and define the default styling for the component's markup elements.

@utility uc-code-block-bg {  @apply bg-(--app-code-block-bg);}@utility uc-code-block-border {  @apply border-(--app-code-block-border);}@utility uc-code-block-pre-bg {  @apply bg-(--app-code-block-pre-bg);}@utility uc-code-block-tabs-bg {  @apply bg-linear-(--app-code-block-tabs-bg);}

Recipes

Below you'll find a few solutions to common issues you may encounter while writing content inside the DlCode component. If you find something worth reporting, please open an issue in the DocLayer repository.

Escaping code from being parsed

Sometimes, code placed inside the DlCode component may cause parsing issues, especially when it contains a mix of characters like quotes, colons, or other special symbols. This is particularly relevant for the dl-search Module parsing process - module will log code blocks with potential issues.

For example, JSON data is typically formatted with double quotes, which is the correct and standard way. However, if your code block also uses double quotes (such as in Vue props), the parser might have trouble interpreting it correctly, potentially causing formatting issues. To avoid this, it's better to use single quotes in your regular code definitions.

However, if you need to prevent code from being parsed (for example, if it causes formatting issues or is being unintentionally processed), wrap that code with [[ esc ]]...[[ /esc ]] tags. Any content inside these tags will be resolved, removed, or rendered as plain text, ensuring it is properly preserved.

You can also escape regular content - learn more about this here.

Using escaping tags inside the DlCode component
content.md

Because using these tags inside the DlCode component will escape (remove) them, you can see the example in the image above.

If you encounter any issues with formatting Markdown and MDC component definitions you can use this notation: &[[esc]]. It will divide the code properly and apply escaping.

Caution when using code transformer

Escaped code will be automatically processed and potentially removed in the output generated by the dl-search Module. However, the visual presentation (within the content) of these escape tags is managed by a dl.transformers.code global property. If you modify this functionality, the way how code is processed inside your components may/will change.

Hiding action buttons from being displayed

Sometimes, when presenting code, you may not need tabs or action buttons. To hide these, simply use the ui slot and hide the relevant section with the appropriate Tailwind class. You can do it like this:

::dl-code```tssome code here```#ui{ "actions": "hidden" }::