Code
A read-only, syntax-highlighted code block themed entirely from the code-token family.
Live demo
Code is a turnkey, read-only code block with the tokenizer built in; it's the first component to read the --code-* family. It tokenizes with Prism, whose output is class-based, so the block re-themes live the moment the theme changes: the colors are just cascading CSS variables, never baked inline.
The lang prop names the language with aliases resolved (ts → typescript), and the source is the element's text content (or, for Astro, a code prop). Grammar loading is fully lazy and per-language. A page with no code block loads nothing; a page with a few languages loads Prism core once plus only those grammar chunks, walking each grammar's dependencies first. At runtime the block paints immediately as plain-but-themed text and recolors in place once the grammar resolves, so there is no flash and no layout shift; the Astro binding tokenizes at build and ships pre-colored with zero browser JS. preload warms a block's grammar eagerly to kill even the minor recolor flash, sharing one warm path with the page-level XtyleCode.warm() static. An unknown language falls back to plain-but-themed text rather than erroring.
When to use
How this component composes with the rest of the set.
Props
8 props, straight from the manifest.
| Prop | Type | Default | Bindings | Description |
|---|---|---|---|---|
ts → typescript). An unknown id falls back to plain-but-themed text. In markup the attribute is language; lang is the HTML global and means a natural language, not a programming one. | ||||
modulepreload hint, killing the minor recolor flash on known code-heavy pages. | ||||
copy="false" to drop it. It only paints where it can work: hidden in an insecure context (no Clipboard API) and on the zero-JS Astro path. | ||||
wrap (a wrapped line keeps a single number at its top). The gutter is pure derived chrome; it borrows --code-comment and --field-border, adding no tokens, and renders on the zero-JS Astro path too. | ||||
--code-line-highlight to call out the ones that matter: a 1-based spec like 2, 2,4, or 4-6, mixable as 1,3-5,8. Pairs with line-numbers, works under wrap, and renders on the zero-JS Astro path; it reuses a token the algorithm already derives, so it adds none. | ||||
Appearance
States
scroll-focus
Keyboard focus on a block wide enough to scroll horizontally, which turns tabbable only when it overflows: an outline sitting outside the border box, so the scrolled code can't cover it.
Anatomy
The named parts that make up the component. A ::part() handle is reachable from your own stylesheet; the class beside it is the component's internal selector, which a shadow boundary keeps to itself.
pre
The block surface: the scroll container that carries the code background and padding.
code
The tokenized source: .token.* spans colored by the per-scope code tokens.
caption
An optional header strip above the block, set via caption (a filename, say); reads in the mono face on a neutral surface and rounds the block's top corners into it.
copy
The copy-to-clipboard button, anchored top-right; fades in on hover or focus and flashes a vivid Copied state on success.
line
A single logical line of source, wrapped as a row when line-numbers or highlight is set.
line-number
The per-line gutter cell, shown when line-numbers is set; it sticks to the left edge as the code scrolls sideways and reads dimmed, like a comment. It is a real node the fragment draws, one per row, so a mod can restyle it, move it to the trailing edge, or grow a fold column beside it.
line-highlight
A line called out by highlight; the whole row is tinted with --code-line-highlight, the low-alpha accent the algorithm derives for exactly this.
Tokens & coverage
What the component consumes, checked live against what the algorithm produces.
Live coverage check against the xtyle-default register
(derive(xtyleDefault, { anchors }) →
coverComponent(manifest, register)). Every token this component
consumes must be a key the algorithm produces.
--border-thick--border-thin--code-attr--code-bg--code-comment--code-fg--code-function--code-keyword--code-line-highlight--code-number--code-operator--code-punctuation--code-regexp--code-selection--code-string--code-tag--code-type--code-variable--duration-fast--ease-standard--field-border--font-mono--font-sans--leading-normal--neutral--neutral-bg--neutral-fg--neutral-text--radius-md--radius-sm--ring--space-1--space-2--space-4--success--success-vivid--text-sm--text-xsSlots
The source code as text content (html/svelte). For Astro, pass the source via the code prop instead.
Accessibility
Code
Languages and preload
A TypeScript block and a preloaded Rust block, both colored from the code-token family.
<xtyle-code lang="ts">const greet = (name: string) => `hi ${name}`;</xtyle-code>
<xtyle-code lang="rust" preload>fn main() { println!("hello"); }</xtyle-code><script lang="ts">
import { Code } from "@xtyle/svelte";
</script>
<Code lang="ts">{`const greet = (name: string) => \`hi ${name}\`;`}</Code>---
import Code from "@xtyle/astro/Code.astro";
---
<Code lang="ts" code={`const greet = (name: string) => \`hi ${name}\`;`} />Soft-wrap long lines
wrap folds long lines into the column instead of scrolling them sideways. It's a declarative host attribute, so it needs no JavaScript and works on the static Astro path.
<xtyle-code lang="ts" wrap>const message = "a long line that soft-wraps in a narrow column instead of scrolling sideways";</xtyle-code><script lang="ts">
import { Code } from "@xtyle/svelte";
</script>
<Code lang="ts" wrap>{`const message = "a long line that soft-wraps instead of scrolling";`}</Code>---
import Code from "@xtyle/astro/Code.astro";
---
<Code lang="ts" wrap code={`const message = "a long line that soft-wraps instead of scrolling";`} />Line numbers
line-numbers adds a counter gutter that sticks to the left edge as the code scrolls and keeps a single number per logical line even under wrap.
<xtyle-code lang="ts" line-numbers>function add(a: number, b: number) {
return a + b;
}
const sum = add(2, 3);</xtyle-code><script lang="ts">
import { Code } from "@xtyle/svelte";
</script>
<Code lang="ts" lineNumbers>{`function add(a, b) {
return a + b;
}`}</Code>---
import Code from "@xtyle/astro/Code.astro";
---
<Code lang="ts" lineNumbers code={`function add(a, b) {
return a + b;
}`} />Highlighting lines
highlight tints the lines that matter, via a 1-based spec like 2,4 or 4-6, drawn from the --code-line-highlight token the algorithm already derives; it pairs with line-numbers.
<xtyle-code lang="ts" line-numbers highlight="2,4">function total(items) {
let sum = 0;
for (const n of items) sum += n;
return sum;
}</xtyle-code><script lang="ts">
import { Code } from "@xtyle/svelte";
</script>
<Code lang="ts" lineNumbers highlight="2,4">{`function total(items) {
let sum = 0;
for (const n of items) sum += n;
return sum;
}`}</Code>---
import Code from "@xtyle/astro/Code.astro";
---
<Code lang="ts" lineNumbers highlight="2,4" code={`function total(items) {
let sum = 0;
for (const n of items) sum += n;
return sum;
}`} />A caption header
caption adds a header strip above the block for a filename or label, rounding the top corners into it. It reuses chrome tokens and renders on the static Astro path.
<xtyle-code lang="ts" caption="theme.ts">export const accent = "#5b8cff";</xtyle-code><script lang="ts">
import { Code } from "@xtyle/svelte";
</script>
<Code lang="ts" caption="theme.ts">{`export const accent = "#5b8cff";`}</Code>---
import Code from "@xtyle/astro/Code.astro";
---
<Code lang="ts" caption="theme.ts" code={`export const accent = "#5b8cff";`} />Languages
Every language the code block can highlight, 299 in all; each grammar lazy-loaded per block. An unknown language renders as plain, themed text rather than erroring.
Added by xtyle
Prism ships neither; xtyle adds them. Everything else is Prism's canonical set.
Aliases
All 299 languages
abapabnfactionscriptadaagdaalantlr4apacheconfapexaplapplescriptaqlarduinoarffarmasmarturoasciidocasm6502asmatmelaspnetastroautohotkeyautoitavisynthavro-idlawkbashbasicbatchbbcodebbjbicepbirbbisonbnfbqnbrainfuckbrightscriptbrobslccfscriptchaiscriptcilcilkccilkcppclikeclojurecmakecobolcoffeescriptconcurnascooklangcoqcppcrystalcsharpcshtmlcspcsscss-extrascsvcuecypherddartdataweavedaxdhalldiffdjangodns-zone-filedockerdotebnfeditorconfigeiffelejselixirelmerberlangetluaexcel-formulafactorfalsefirestore-security-rulesflowfortranfsharpftlgapgcodegdscriptgedcomgettextgherkingitglslgmlgngogo-modulegradlegraphqlgroovyhamlhandlebarshaskellhaxehclhlslhoonhpkphstshttpichigojamiconicu-message-formatidrisiecstignoreinform7iniiojjavajavadocjavadoclikejavascriptjavastacktracejexljoliejqjs-extrasjs-templatesjsdocjsonjson5jsonpjsstacktracejsxjuliakeepalivedkeymankotlinkumirkustolatexlattelesslilypondlinker-scriptliquidlisplivescriptllvmloglolcodeluamagmamakefilemarkdownmarkupmarkup-templatingmatamatlabmaxscriptmelmermaidmetafontmizarmongodbmonkeymoonscriptn1qln4jsnand2tetris-hdlnaniscriptnasmneonnevodnginxnimnixnsisobjectivecocamlodinopenclopenqasmozparigpparserpascalpascaligopcaxispeoplecodeperlphpphp-extrasphpdocplant-umlplsqlpowerquerypowershellprocessingprologpromqlpropertiesprotobufpslpugpuppetpurepurebasicpurescriptpythonqqmlqoreqsharprracketreasonregexregorenpyrescriptrestriproboconfrobotframeworkrubyrustsassassscalaschemescssshell-sessionsmalismalltalksmartysmlsoliditysolution-filesoysparqlsplunk-splsqfsqlsquirrelstanstatastylussupercollidersvelteswiftsystemdt4-cst4-templatingt4-vbtaptcltextiletomltremortsxtt2turtletwigtypescripttyposcriptunrealscriptuorazorurivvalavbnetvelocityverilogvhdlvimvisual-basicwarpscriptwasmweb-idlwgslwikiwolframwrenxeoraxml-docxojoxqueryyamlyangzig