Getting startedComponentsDesign tokensThemingTheme synthesizerFrameworksAccessibilityUtilitiesServer renderingBrowser supportContributingChangelogApp ShellAspect GridAuth ShellCenterContainerDashboard GridFloat BarInsetMasonryPage HeaderPage LayoutResizableResponsive SwitcherSectionSettings LayoutSplit PaneStatus BarStickyToolbarAnchor NavBottom NavBreadcrumbBreadcrumb MenuCommand BarDrawerFooterLinkMenubarNavigation MenuPage IndicatorPaginationRailScroll IndicatorScroll SpyScroll To TopSidebarSkip LinkStepper NavTabsTop BarTree ViewAccordionAspect RatioAvatarAvatar GroupCardCarouselCollapsibleColor SwatchCTA BannerDividerEmpty StateFeature CardIconImageImage CompareImage HotspotsInfinite ScrollLightboxMarqueeQR CodeScroll AreaSkeletonSpinnerStackVideoVirtual ListActivity HeatmapAnimated NumberBadgeBar ListChartClockComparisonCountdown TimerData GridDescription ListDiffGaugeJSON TreeKanbanLevel MeterListMeterSparklineStatStepperTagTimelineUptimeValue CardWaveformBlockquoteCode BlockCode GroupGradient TextHighlightKbdKeyboard MapMarkdownNumber FormatProseTerminalTextTime AgoTruncateTypewriterButtonButton GroupCalendarCheckboxChipColor PickerComboboxCopy ButtonDate PickerDate Range PickerField ListFieldsetFile UploadFormHotkeyIcon ButtonImage CropperInline EditInputInput GroupKnobLabelMasked InputMulti SelectNumber InputPassword InputPin InputRadio GroupRange SliderRatingSearchSegmented ControlSelectSignature PadSliderSortable ListSwitch GroupTag InputTextareaTheme ToggleTime PickerToggleTransfer ListTree SelectAlertAnnouncementBannerCommand PaletteConfirmConnection StatusContext MenuConversationDialogDropdown MenuHover CardLoading OverlayNotification PanelPopoverProgressSheetToastTooltip
ARC UIARC Radiant Components
v4.9DocsComponentsTokensSynthesizer
Getting startedFrameworksServer renderingDesign tokensThemingTheme synthesizerTypographyUtilitiesAll componentsAccessibilityBrowser supportChangelogContributingStatsApp ShellAspect GridAuth ShellCenterContainerDashboard GridFloat BarInsetMasonryPage HeaderPage LayoutResizableResponsive SwitcherSectionSettings LayoutSplit PaneStatus BarStickyToolbarAnchor NavBottom NavBreadcrumbBreadcrumb MenuCommand BarDrawerFooterLinkMenubarNavigation MenuPage IndicatorPaginationRailScroll IndicatorScroll SpyScroll To TopSidebarSkip LinkStepper NavTabsTop BarTree ViewAccordionAspect RatioAvatarAvatar GroupCardCarouselCollapsibleColor SwatchCTA BannerDividerEmpty StateFeature CardIconImageImage CompareImage HotspotsInfinite ScrollLightboxMarqueeQR CodeScroll AreaSkeletonSpinnerStackVideoVirtual ListActivity HeatmapAnimated NumberBadgeBar ListChartClockComparisonCountdown TimerData GridDescription ListDiffGaugeJSON TreeKanbanLevel MeterListMeterSparklineStatStepperTagTimelineUptimeValue CardWaveformBlockquoteCode BlockCode GroupGradient TextHighlightKbdKeyboard MapMarkdownNumber FormatProseTerminalTextTime AgoTruncateTypewriterButtonButton GroupCalendarCheckboxChipColor PickerComboboxCopy ButtonDate PickerDate Range PickerField ListFieldsetFile UploadFormHotkeyIcon ButtonImage CropperInline EditInputInput GroupKnobLabelMasked InputMulti SelectNumber InputPassword InputPin InputRadio GroupRange SliderRatingSearchSegmented ControlSelectSignature PadSliderSortable ListSwitch GroupTag InputTextareaTheme ToggleTime PickerToggleTransfer ListTree SelectAlertAnnouncementBannerCommand PaletteConfirmConnection StatusContext MenuConversationDialogDropdown MenuHover CardLoading OverlayNotification PanelPopoverProgressSheetToastTooltip

Code Block

Shows source code in a framed block with a copy button, and colors it when shiki is installed.

ComponentsCode Block
typographyhybrid
<arc-code-block>

Overview

CodeBlock shows source code in a framed block. The header has a title (`label`, in the body font), an optional `filename` in monospace, the `language` as a small tag, and an icon-only copy button that copies the code and shows a green check for a moment. Code goes in through the `code` property. There is no default slot. Code renders line by line whether or not it's highlighted, so every reading aid works without the highlighter: `line-numbers` adds a gutter, `highlight="2,4-6"` emphasizes lines, `diff` (or `language="diff"`) tints added and removed lines, `wrap` soft-wraps long lines, and `max-lines` collapses a tall block behind a "Show all" button. None of this reaches the clipboard. The copy button copies `code` exactly as given. **Shell blocks.** Set `prompt` to put a `$` (or your own prompt, such as `#`) before each command. Continuation lines after a trailing backslash and blank lines get none, and the prompt can't be selected or copied. Shell highlighting tells the parts of a command apart: a wrapper like `sudo` is muted, the command is bold, its subcommand takes the accent, and paths, URLs and image references read as values. For variants of one command (npm, pnpm and yarn, or two editions of a product), put the blocks in an [arc-code-group](/docs/components/code-group) to get one block with tabs. **Highlighting is opt-in.** CodeBlock is the one component in ARC UI with a heavy dependency: shiki and its grammars, about 12 MB installed (shiki 4.4.3 and its `@shikijs` packages, 8.7 MB of it grammars). So shiki is an *optional peer dependency*, and the main barrel doesn't re-export CodeBlock. A bundler resolves the dynamic imports of everything it can reach, so a barrel export would have put shiki in everyone's install. Import CodeBlock by its own subpath and install shiki alongside: ``` npm install shiki @shikijs/langs ``` ```js import '@arclux/arc-ui/code-block'; ``` Without shiki, CodeBlock still renders: the header, the copy button, the reading aids and the code all work. The code isn't colored, and the console says so once. With shiki, the colors fade in when the grammar loads and no line moves. `@arclux/arc-ui/register` doesn't register CodeBlock either, so import the subpath. The code shows without JavaScript, but copying needs JavaScript and a secure context (HTTPS). Copy failures are caught, so on HTTP or in a restricted environment the button fails without throwing errors.

Guidelines

Do

  • Give a block a `label` when it's one of several on a page, so readers can tell them apart
  • Use `prompt` for commands a reader will paste into a terminal, and leave it off for scripts and output
  • Use arc-code-group for variants of one command, not a stack of near-identical blocks
  • Use `highlight` to point at the lines the surrounding text talks about
  • Set `max-lines` on long samples in running text

Don't

  • Don't put content between the tags. There is no default slot, so use the `code` prop
  • Don't type a `$` into the code. It ends up in the reader's clipboard, so use `prompt`
  • Don't use `wrap` where indentation matters to the reader, such as Python or YAML, unless the lines are short
  • Don't use CodeBlock for inline code. Use arc-text variant="code"
  • Don't count on copy working everywhere. It needs HTTPS and a user gesture

Features

  • Shell colors also set apart flags, variables and operators
  • Wrapped lines align after the gutter and the prompt
  • `max-lines` fades the cut-off edge, and its button reads "Show all N lines"
  • A `window` variant with a title bar and a line count, and a `basic` variant with no chrome

Preview

Shell, with a prompt
Line numbers and emphasis
Diff, collapsed to five lines
Window
Basic

Usage

Its events and state need JavaScript, so use the Web Component or a framework wrapper for those.

<arc-code-block language="bash" label="Install" prompt></arc-code-block>
<arc-code-block language="js" filename="app.js" line-numbers highlight="2"></arc-code-block>

<script type="module">
  import '@arclux/arc-ui/code-block';
  const [install, app] = document.querySelectorAll('arc-code-block');
  install.code = 'npm install @arclux/arc-ui';
  app.code = "import '@arclux/arc-ui/register';\ndocument.body.classList.add('ready');";
</script>

API

languagestring''
Language identifier (e.g. js, css, bash). Shown in uppercase in the header and used to pick the highlighter grammar.
labelstring''
A plain title for the header in the body font, such as "Pulsar for NVIDIA". Shown before the filename when both are set. Also the tab name inside an arc-code-group.
filenamestring''
A filename for the header, in monospace. When label is also set it follows the label, muted.
codestring''
The code to display. Copied as-is by the copy button: no prompts, no line numbers.
promptstringnull
Shows a prompt before each command line, never selectable and never copied. Set with no value for $, or give the character (#, >, PS>). Continuation lines after a trailing backslash and blank lines get none.
highlightstring''
Lines to emphasize, 1-based: a comma-separated list of numbers and ranges such as 2,4-6.
variant'default' | 'window' | 'basic''default'
Visual variant. default shows the standard layout with an optional header and status bar. window adds a macOS-style title bar with colored orbs and a centered title. basic strips all chrome for a compact display.
lineNumbersbooleanfalse
Shows line numbers in a gutter that is not selected or copied.
diffbooleanfalse
Tints lines that start with + as added and - as removed, on top of the block's own language. Always on for language="diff".
wrapbooleanfalse
Soft-wraps long lines instead of scrolling them. Wrapped text stays aligned after the line number and prompt.
maxLinesnumber0
Collapses a longer block to this many lines, with a fade and a button to show the rest.

Events

arc-toggle
Fired when a collapsed block is expanded or collapsed again. detail.value is true when expanded.

See also