# Code

## Usage

`Code` marks a short technical reference inside a sentence, such as a function name, a prop, a file path, or a command-line flag. It renders a semantic `<code>` element in a monospace font on a muted background, and it wraps long identifiers instead of pushing the surrounding paragraph wider.

`CodeBlock` presents a read-only snippet of one or more lines. It adds the parts a snippet needs to stand on its own: a header with a title and the language, a copy button, optional line numbers, optional highlighted lines, optional syntax highlighting, a bounded scroll area, and an optional collapse control. Both components are exported from `@astryx-vue/core/Code`.

```vue
<script setup lang="ts">
import { Code, CodeBlock } from '@astryx-vue/core/Code'

const snippet = 'const total = items.length'
</script>

<template>
  <p>Count the items with <Code>items.length</Code>.</p>

  <CodeBlock :code="snippet" language="typescript" title="count.ts" />
</template>
```

The `language` prop selects the tokenizer. The built-in set covers `typescript`, `javascript`, `tsx`, `jsx`, `ts`, `js`, `json`, `html`, `xml`, `svg`, `css`, `scss`, `less`, `python`, `py`, `bash`, `sh`, `zsh`, `shell`, `php`, `hack`, `yaml`, `yml`, `markdown`, and `md`. Anything else, including `plaintext`, renders the code exactly as written without tokens, and `plaintext` also hides the language label because it says nothing the reader needs. A language the tokenizer does not know is not an error: you can also pass your own `tokenizer` function that returns tokens with absolute offsets, and it will be painted while the displayed and copied text stays the source string.

The header appears when there is a title or a visible language label, and it is where the copy button lives. When neither exists, the copy button floats at the top end of the block instead, so copying stays available without a header. `hasLanguageLabel` turns the label off while keeping the header a title-only bar.

Line numbers are off by default. Turn them on with `hasLineNumbers`; the gutter is sized to the widest line number so the code column starts at a stable offset. `highlightLines` takes one-indexed line numbers and tints those lines to draw attention to them. Set `isWrapped` when long lines should wrap rather than scroll sideways, and `maxHeight` to bound the height before the code scrolls vertically; `0` is a valid bound and means the body is fully collapsed to its header height. The block is as wide as its longest line by default: `width="fit-content"` keeps a short snippet compact with a floor, while `width="100%"` fills the parent. `container="section"` drops the border, radius, and background so a block sits inside a card or panel without painting a second surface.

A long block can collapse. Set `isCollapsible` and the header becomes a disclosure control once the header is visible and the code reaches `collapsibleThreshold` lines, which is 10 by default. The block starts expanded, reports its state through `aria-expanded`, and points at the region it controls through `aria-controls`. While collapsed, that region stays mounted but `inert`, so the code is out of the tab order and out of the accessibility tree instead of sitting there invisibly. If the control disappears, for example because the title is removed, the block expands again on its own.

The copy button writes the exact `code` string, so what a reader pastes always matches the source even when the display is tokenized, numbered, or wrapped. After a successful write the control name changes to `Copied`, the icon flips from a copy glyph to a check, and a polite live region announces the same word; the hover hint keeps reading `Copy code`, because the icon flip is the confirmation. A rejected clipboard write keeps the control in its resting state and emits nothing. `copyLabel`, `copiedLabel`, and `codeLabel` carry the English defaults and exist so an application can localize those strings.

The code viewport is a named `role="group"` with a keyboard stop, so a keyboard user can scroll a snippet that overflows. The copy control and the collapse control are separate siblings, each with its own accessible name, so activating one never triggers the other. Syntax colors come from the `--astryx-code-syntax-*` tokens, and `highlightMode` chooses how they are painted: `auto` uses the CSS Custom Highlight API when the browser supports it well and falls back to spans, `ranges` paints through the API without adding any element to the code text, and `spans` wraps every token in an element. The text, the semantics, and the copy output are the same in all three.

### Anatomy

- **Container**: The semantic code element that contains the inline code content and paints the background, typography, padding, and radius.

## Best practices

| Guidance | Practices |
| --- | --- |
| Do | Use `Code` for short references inside prose, such as a property name or a flag, and `CodeBlock` for anything that stands on its own or spans more than one line. |
| Do | Set `language` to match the snippet so the tokens are accurate, and add a `title` when the code is a file. The title tells readers where the snippet came from. |
| Do | Use `size="inherit"` on inline code inside larger or smaller text so the code matches the line it sits in. |
| Do | Reach for `maxHeight` or `isCollapsible` on long snippets instead of nesting the block in your own scroll container. |
| Don't | Turn on line numbers for a two-line snippet. They add clutter without helping anyone find a line. |
| Don't | Put a paragraph of prose inside a `CodeBlock`, or use `Code` for a whole file. Each component has one job. |
| Don't | Rely on syntax colors alone to carry meaning. Tokens paint the code; they do not explain it. |

## Examples

### Text sizes

Inline code rendered inside heading, body, supporting, and label text. Code automatically matches the font size of its parent text element.

```vue
<script setup lang="ts">
import { Code } from '@astryx-vue/core/Code'
import { Heading } from '@astryx-vue/core/Heading'
import { VStack } from '@astryx-vue/core/Stack'
import { Text } from '@astryx-vue/core/Text'
</script>

<template>
  <VStack :gap="3">
    <Heading :level="3">
      Heading with <Code size="inherit">inline code</Code>
    </Heading>
    <Text type="body">
      Body text with <Code size="inherit">inline code</Code>
    </Text>
    <Text type="supporting">
      Supporting text with <Code size="inherit">inline code</Code>
    </Text>
    <Text type="label">
      Label text with <Code size="inherit">inline code</Code>
    </Text>
  </VStack>
</template>
```

### Inline

Inline code references mixed within a paragraph of body text. Use Code to mark up function names, hooks, or API terms so they stand out from surrounding prose.

```vue
<script setup lang="ts">
import { Code } from '@astryx-vue/core/Code'
import { Text } from '@astryx-vue/core/Text'
</script>

<template>
  <Text type="body" style="max-width: 400px">
    Use <Code>useState</Code>for local state and <Code>useEffect</Code>for side effects. If you need shared state across components, consider <Code>useContext</Code>or a state management library.
  </Text>
</template>
```

### Content types

Inline code used for variables, terminal commands, CSS properties, file paths, and keyboard shortcuts. Shows how Code adapts to different kinds of technical content.

```vue
<script setup lang="ts">
import { Code } from '@astryx-vue/core/Code'
import { VStack } from '@astryx-vue/core/Stack'
import { Text } from '@astryx-vue/core/Text'
</script>

<template>
  <VStack :gap="3">
    <Text type="body">
      Variable: <Code>const count = 0</Code>
    </Text>
    <Text type="body">
      Terminal: <Code>yarn build --watch</Code>
    </Text>
    <Text type="body">
      CSS property: <Code>border-radius: 8px</Code>
    </Text>
    <Text type="body">
      File path: <Code>packages/core/src/CodeBlock/Code.tsx</Code>
    </Text>
    <Text type="body">
      Keyboard shortcut: <Code>Ctrl+Shift+P</Code>
    </Text>
  </VStack>
</template>
```

## Props

### Code

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `color` | `CodeColor` | `'primary'` | Text color of the inline code: `primary`, `secondary`, or `inherit` for the surrounding text color. |
| `size` | `'inherit'` | - | Font size. Omit it to use the code type scale, or set `inherit` to adopt the surrounding font size and line height. |

### CodeBlock

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `code` | `string` | - | The read-only code to display. This exact string is what the copy button writes, whatever the block paints. |
| `language` | `string` | `'plaintext'` | Language used for syntax highlighting. An unknown language renders without tokens, and `plaintext` also hides the language label. |
| `title` | `string` | - | Filename or label shown in the header bar. A title alone creates the header. |
| `hasLanguageLabel` | `boolean` | `true` | Whether the language name appears in the header. It is never shown for `plaintext`. |
| `hasLineNumbers` | `boolean` | `false` | Whether to draw a line number gutter. The gutter is sized to the widest number. |
| `highlightLines` | `number[]` | - | One-indexed line numbers to emphasize with an accent background. Out-of-range numbers have no effect. |
| `hasCopyButton` | `boolean` | `true` | Whether to show the copy button, in the header when there is one and floating at the top end otherwise. |
| `isWrapped` | `boolean` | `false` | Whether long lines wrap instead of scrolling horizontally. |
| `maxHeight` | `number \| string` | - | Maximum height before the code body scrolls vertically. Numbers are pixels, so `0` is a valid zero-pixel bound. |
| `isCollapsible` | `boolean` | `false` | Whether the header collapses the body. The control only appears when the header is visible and the code reaches `collapsibleThreshold` lines. |
| `collapsibleThreshold` | `number` | `10` | Number of lines a block needs before the collapse control appears. |
| `size` | `'sm' \| 'md'` | `'md'` | Text size variant. `md` uses the code type scale and `sm` the supporting size. |
| `width` | `string` | `'fit-content'` | Any CSS width value. `fit-content` shrinks to the longest line with a floor so a short snippet still reads as a block; `100%` fills the parent. |
| `container` | `'card' \| 'section'` | `'card'` | Container presentation. `card` paints a border, radius, and background; `section` drops all three so the block blends into the surface it sits in. |
| `tokenizer` | `(code: string, language: string) => SyntaxToken[]` | - | Custom tokenizer for a language the built-in one does not cover. Tokens use absolute offsets. It changes paint only, never the displayed or copied text. |
| `highlightMode` | `'auto' \| 'ranges' \| 'spans'` | `'auto'` | How syntax tokens are painted. `auto` prefers the CSS Custom Highlight API and falls back to span elements. |
| `copyLabel` | `string` | `'Copy code'` | Accessible name and hover hint of the copy button before a copy. |
| `copiedLabel` | `string` | `'Copied'` | Name of the copy button and text of the polite announcement after a successful copy. |
| `codeLabel` | `string` | `'Code'` | Accessible name of the code viewport, and of a collapsible header that has no visible title or language label. |

## Events

| Name | Payload | Description |
| --- | --- | --- |
| `copy` | - | Emitted after the code string was written to the clipboard. A rejected write emits nothing. |

## Slots

| Name | Description |
| --- | --- |
| `default` | Inline code content for `Code`. `CodeBlock` takes its content from the `code` prop and renders no slot. |

## Exports

These are exported from `@astryx-vue/core/Code` beside `Code`, `CodeBlock`, and `SyntaxTheme`:

| Name | Signature | Description |
| --- | --- | --- |
| `tokenize` | `(code, language) => TokenLine[]` | Tokenize a string into one token array per line, with offsets relative to the line start. Returns nothing for an unknown language. |
| `tokenizeAsync` | `(code, language, signal?) => Promise<TokenLine[]>` | The same result, yielding to the main thread between chunks. An aborted signal returns the lines finished so far. |
| `flatTokensToLines` | `(tokens, code) => TokenLine[]` | Convert tokens with absolute offsets, as a custom tokenizer returns them, into line-relative tokens. |
| `applyHighlightRanges` | `(element, tokenLines) => () => void` | Paint tokens through the CSS Custom Highlight API and return the cleanup function. |
| `useCopyToClipboard` | `(options?) => { copy, isCopied }` | Copy-to-clipboard behavior with a transient copied flag. Re-copying restarts the reset timer, which is two seconds by default. |
| `SYNC_TOKENIZE_THRESHOLD` | `number` | Code length below which tokenization runs synchronously; longer code is tokenized in chunks. |
| `HIGHLIGHTED_TOKEN_TYPES` | `readonly string[]` | Token types the stylesheet already paints, so a custom tokenizer can reuse them. |
| `SyntaxTheme` | `component` | Sets `--astryx-code-syntax-*` from a `theme` prop. `githubDark` is the included dark preset. `defineSyntaxTheme` returns a definition unchanged. |

## CSS variables

The block reads these tokens, which the neutral theme defines:

| Name | Description |
| --- | --- |
| `--astryx-font-family-code` | Monospace font stack for inline code, the block, and the header. |
| `--astryx-text-code-size` | Font size of inline code and of an `md` block. |
| `--astryx-code-background` | Background of inline code. |
| `--astryx-code-block-background` | Background of the block and its sticky header. A `section` container sets it to transparent. |
| `--astryx-code-block-border` | Border of a `card` container, the header divider, and the line number rule. |
| `--astryx-code-block-focus` | Focus ring of the collapsible header control. |
| `--astryx-code-block-highlight-background` | Background of a line listed in `highlightLines`. |
| `--astryx-code-syntax-*` | Token colors: keyword, string, comment, number, function, type, variable, operator, constant, tag, attribute, property, and punctuation. |

## Native attributes

The root element of `Code` is a `<code>`, and the root element of `CodeBlock` is a `<pre>`.

The following go to that root element:

- HTML attributes.
- `aria-*` attributes.
- `data-*` attributes.
- `class`.
- `style`.

`class` and `style` are composed with the component's own, and a `width` in `style` wins over the `width` prop. The copy button, the code viewport, and the collapse region are internal elements with their own accessible names, so they are not addressed through the root.
