Custom code block
How to build copy buttons, collapse thresholds, and other code-block UI when Comark does not pass a raw `code` prop.
Comark stores fenced code under a <pre><code> subtree instead of duplicating it as a <pre> attribute. Syntax highlighting plugins such as Shiki and Rangi replace the code text with tokenized span nodes, which renderers expose through the default slot.
If you are migrating from MDC or Nuxt Content, a custom
ProsePre that read (props.code || '').split('\n') for copy or collapse no longer receives props.code. Reconstruct the source from the AST node instead.What <pre> receives
Fence metadata stays on the node attributes and arrives as component props:
| Prop | Origin |
|---|---|
language | Fence info string |
filename | [name] in the fence |
highlights | {1,3-5} line highlights |
meta | Remaining fence meta |
class | Highlighter classes added by Shiki or Rangi |
style | Inline theme styles when preStyles is enabled |
There is no code or lines prop. The <code> subtree renders in the default slot and stays on the AST node.
Read code with __node and textContent
@comark/vue passes the element node when your component declares a __node prop. Pass __node to textContent() from comark/utils to extract the raw code without the fence or trailing newline:
components/ProsePre.vue
<script setup lang="ts">
import { computed } from 'vue'
import { textContent } from 'comark/utils'
import type { ElementNode } from 'comark'
defineOptions({ inheritAttrs: false })
const props = defineProps<{
__node?: ElementNode
language?: string
filename?: string
}>()
const COLLAPSE_THRESHOLD = 15
const code = computed(() => (props.__node ? textContent(props.__node) : ''))
const lines = computed(() => code.value.split('\n').length)
const isLong = computed(() => lines.value > COLLAPSE_THRESHOLD)
async function copy() {
await navigator.clipboard.writeText(code.value)
}
</script>
<template>
<div class="relative group">
<button type="button" @click="copy">Copy</button>
<div :class="isLong && 'max-h-[360px] overflow-hidden'">
<pre
v-bind="$attrs"
:language="props.language"
:filename="props.filename"
><slot /></pre>
</div>
</div>
</template>This runs during SSR, stays in sync when __node changes, and doesn't read the DOM.
In React, TypeScript prop declarations are erased at runtime. Accept
__node in your component props and add a runtime marker with ProsePre.propTypes = { __node: () => null } so @comark/react injects the node, then call textContent(__node).