1. How swift-docc-render consumes this
codeListing is one of the block-content kinds dispatched by the shared
render() function inside
components/ContentNode.vue's
BlockType map (codeListing: 'codeListing', line 39). The switch (node.type)
case for it is:
case BlockType.codeListing: {
if (node.metadata && node.metadata.anchor) {
return renderFigure(node);
}
const props = {
syntax: node.syntax,
fileType: node.fileType,
content: node.code,
showLineNumbers: node.showLineNumbers,
copyToClipboard: node.copyToClipboard ?? false,
wrap: node.wrap ?? 0,
lineAnnotations: node.lineAnnotations ?? [],
};
return createElement(CodeListing, { props });
}
(src/components/ContentNode.vue#L267-L281).
Two things stand out mechanically:
-
When
metadata.anchoris present, the node is instead routed through the sharedrenderFigurehelper (src/components/ContentNode.vue#L220-L249), which wraps the (stillCodeListing-rendered) content in a<figure>element and optionally prepends/appends a<figcaption>built frommetadata.title/metadata.abstract. This is the same helper used byvideoanddictionaryExamplenodes that carry an anchor — it is not specific to code listings, it is a generic "give this block a linkable, captioned figure" wrapper. -
node.fileTypeis read out of the render node and passed toCodeListingeven though the vendored JSON Schema and generated Swift type (see section 3) do not declare afileTypeproperty onCodeListing— it is accessed defensively (undefinedwhen absent) and only affects the file-icon glyph if a filename is also present.
The actual leaf component,
components/ContentNode/CodeListing.vue,
renders a <div class="code-listing"> containing an optional filename header, a
copy-to-clipboard button, and a <pre><code>…</code></pre>
block built line-by-line from the content prop (bound from node.code).
Each source line becomes its own <span class="code-line-container">, with an
optional <span class="code-number"> (shown when showLineNumbers is
true) and a <span class="code-line" v-html="line"> holding the
syntax-highlighted markup for that line
(CodeListing.vue#L40-L59).
Syntax highlighting itself happens client-side and asynchronously: a content watcher
(CodeListing.vue#L177-L215)
calls registerHighlightLanguage(this.syntaxNameNormalized) then
highlightContent(...), falling back to plain HTML-escaped text if the language isn't
supported — so syntax (normalized via a small occ→objective-c
legacy-name map, line 144-148) drives which highlighter grammar loads, not which HTML is emitted.
Per-line decoration (highlight/strikeout) comes from the lineAnnotations prop, converted
into per-style Sets of line numbers in the styleLineSets computed property
(CodeListing.vue#L152-L175)
and applied as the highlighted/strikethrough classes on each line's
container span. copyToClipboard gates a small copy button that calls
navigator.clipboard.writeText
(CodeListing.vue#L216-L230),
and wrap (a positive integer) sets a --wrap-ch CSS custom property used by
the scoped SCSS to cap line width at N monospace characters instead of allowing horizontal scroll.
Note that CollapsibleCodeListing.vue and MobileCodeListing.vue (also under
components/ContentNode/) exist in this repo but are not in this dispatch path —
grepping their usages shows they are consumed by EndpointExample.vue and
DictionaryExample.vue (and, for the mobile variant, the tutorial-only
MobileCodePreview.vue), not by the plain block-level codeListing case above.
A bare codeListing node always renders through the single, non-collapsible
CodeListing.vue.
2. Example JSON and rendered mockup
Real fixture:
Tests/DocCArchiveTests/Fixtures/ExampleDocs.doccarchive/data/documentation/exampledocs/examplearticle.json
in this repository, found inside primaryContentSections[0].content[2].
{
"type": "codeListing",
"syntax": "swift",
"code": [
"func main() {",
" print(\"hello world\")",
"}"
]
}
This minimal fixture omits every optional field (metadata, copyToClipboard,
showLineNumbers, wrap, lineAnnotations). To also illustrate
those fields (line numbers, a highlighted line, and a caption via metadata.anchor),
here is a hand-extended variant built strictly from the fields documented in section 3:
{
"type": "codeListing",
"syntax": "swift",
"code": [
"func main() {",
" print(\"hello world\")",
"}"
],
"showLineNumbers": true,
"copyToClipboard": true,
"lineAnnotations": [
{ "style": "highlight", "range": [ { "line": 2 }, { "line": 2 } ] }
],
"metadata": {
"anchor": "main-function",
"abstract": [ { "type": "text", "text": "The program's entry point." } ]
}
}
3. Data sheet
Schema object: #/components/schemas/CodeListing in
Sources/DocCArchive/Vendored/RenderNode.spec.json (line 816), one of the variants under
the RenderBlockContent discriminated union (its type enum member is listed
at line 2462 of the same file). Generated Swift:
Components.Schemas.CodeListing, a plain Codable, Hashable, Sendable struct
at Sources/DocCArchive/generated/Types.swift:4267-4328, reachable as the
.CodeListing case of the generated RenderBlockContent enum
(Types.swift:3617).
| Field | Type | Required? | Enum values / default | Note |
|---|---|---|---|---|
type | string | yes | "codeListing" | Discriminator; generated as _TypePayload with the single case .codeListing. |
code | [string] | yes | — | The listing's source lines, one array element per line (no embedded newlines). Maps to the content prop on CodeListing.vue. |
syntax | string, nullable | yes (schema-required; may be null) | — | Highlighter language id, e.g. "swift". Normalized client-side (occ → objective-c) before being handed to the highlighter. |
metadata | RenderContentMetadata | no | — | Optional anchor/title/abstract/deviceFrame object (spec line 484-503). Presence of anchor is what triggers the renderFigure path in section 1. |
copyToClipboard | boolean | no | defaults to false at the render call site | Shows/hides the copy button. |
showLineNumbers | boolean | no | defaults to false (component prop default) / undefined-falsy at the call site | Toggles the .code-number gutter spans. |
wrap | integer | no | defaults to 0 at the render call site (0 = no wrap/scroll instead) | Max line width in characters; feeds the --wrap-ch custom property. |
lineAnnotations | [LineAnnotation] | no | defaults to [] at the render call site | Each entry has required style (enum "highlight" | "strikeout", spec line 786-789) and required range (array of two Position objects, each with required line and optional character, spec line 802-815). |
Note the schema does not declare a fileType property on CodeListing, even
though ContentNode.vue's render case reads node.fileType and forwards it as
a prop (section 1) — the generated Swift struct therefore has no fileType member either,
and this field, if ever emitted, would simply be dropped by strict decoding against this schema.
4. HTML/CSS mapping in DocC-Render output
Root element: <div class="code-listing" data-syntax="…">, with modifier classes
single-line (exactly one highlighted line of code) and is-wrapped
(wrap > 0), and an inline style="--wrap-ch: N" when wrapping is active
(CodeListing.vue#L12-L17).
Inside it:
<span class="filename">(fromcomponents/ContentNode/CodeListingFilename.vue) — optional, shown only when afileNameprop is supplied; contains aCodeListingFileIconSVG plus the filename text, wrapped in an<a>whenisActionable.<div class="container-general">— scroll container for the code, and hover scope for the copy button (.container-general:hover .copy-button { opacity: 1; }).<button class="copy-button">with state classesidle/success/failuredriving which ofCopyIcon/CheckmarkIcon/CrossIconis shown.<pre><code>(the<code>is the sharedcomponents/CodeBlock.vue) containing one<span class="code-line-container">per source line, each with an optional<span class="code-number" data-line-number="N">and a<span class="code-line">holding highlighted markup. Per-line state classes:highlightedandstrikethrough.
All of the above is scoped SCSS inside
components/ContentNode/CodeListing.vue's own <style scoped lang="scss">
block (imports docc-render/styles/_core.scss). Notable SCSS variables consumed, all
defined in src/styles/core/_vars.scss: $code-listing-with-numbers-padding
(14px 0), $code-number-padding / $code-number-padding-left
(8px), and $highlighted-border-width (4px). CSS custom
properties consumed at paint time: --color-code-line-highlight and
--color-code-line-highlight-border (theme colors, defined per light/dark palette in
src/styles/core/colors/_light.scss / _dark.scss), --line-highlight
(an optional per-instance override), --color-fill-gray-tertiary/--color-fill-gray
(copy-button background), --code-border-radius, --button-border-radius, and
--code-indentationWidth (drives the CSS tab-size of the <pre>).
When wrapped in a figure (anchor case), the outer markup instead comes from
components/ContentNode/Figure.vue — a bare
<figure :id="anchor"><slot /></figure> — plus an optional
<figcaption> from components/ContentNode/Caption.vue; the
CodeListing markup described above still appears unchanged inside that
<figure>.
5. Modern CSS-only alternative
Partial
Current behavior, precisely: two independent pieces of client-side JS state exist on
CodeListing.vue. (1) copyState (component data, one of
idle/success/failure) is set by a click handler on
.copy-button that calls navigator.clipboard.writeText and, on success,
flips copyState to success for one second via setTimeout
before reverting to idle
(CodeListing.vue#L216-L230).
(2) syntaxHighlightedLines (also component data) is populated
asynchronously by an await-ing watcher that loads a highlighter grammar and re-renders
each line's <span class="code-line" v-html="line"> once highlighting resolves.
Neither of these is a good match for a purely declarative, state-in-the-DOM native mechanism, for two different reasons, so the verdict is split:
-
Copy-button visual feedback (partial win): the temporary "copied!" checkmark state
is exactly the shape of problem the
:has()pseudo-class already solves elsewhere in this very file — the scoped SCSS already uses.code-listing:not(:has(.code-number)):has(.highlighted)(CodeListing.vue#L257-L264) to style the container conditionally on a descendant's class, with no JS-computed class on the parent. Butnavigator.clipboard.writeText()itself has no CSS-only equivalent — copying text to the OS clipboard is unavoidably an imperative JS API call — so at most the transient success/failure display (e.g. auto-reverting after N seconds) could be pushed to CSS (a CSS animation on:targetor a checked radio driving a sibling icon swap), while the copy action and its success/failure signal must still originate in JS. This is a partial, not full, replacement. -
Syntax highlighting (not replaceable): tokenizing source text into
per-token
<span>s with language-aware colors is fundamentally a text-processing step that has to happen somewhere in the pipeline (client JS today, but it could equally be build-time). There is no selector or native browser primitive that can classify "this substring is a Swift keyword" — it requires a grammar/lexer, so no CSS-only mechanism applies here regardless of where the JS runs.