Code Display
Read-only code surfaces — a highlighted code block, a single-line snippet, a tabbed CLI command block and a unified/split diff.
Preview
npm install zod
npx shadcn@latest add button
<div class="flex w-full flex-col gap-4">
<x-ui.code-block-command npm="npm install zod" />
<x-ui.code-block-command npm="npx shadcn@latest add button" :show="['npm', 'pnpm', 'bun']" />
</div>
Installation
php artisan ui:add code-block-command
Note
This component ships an Alpine behavior module at
resources/js/ui/code-block-command.js. Import it once from your bundle so it registers on alpine:init:
import './code-block-command.js';
Registry contract
php artisan ui:add code-block-command
writes only the files below. The CLI validates each file hash before writing and asks before it replaces a local change, unless you pass --force.
-
resources/views/components/ui/code-block-command.blade.php -
resources/js/ui/code-block-command.js
- Registry dependencies
- None — installs on its own.
- Packages
-
composer: jml/brok:^0.2npm: alpinejs
Use with AI
A brief for your coding agent: install command, usage, props, guidance and the rules. Copy it, or open a prompt about this component in an assistant.
# Brok UI: Code Block Command (`code-block-command`)
A tabbed CLI command block that switches between npm, pnpm, yarn and bun, remembers the choice, and copies to the clipboard.
Brok UI is a Laravel Blade component registry. Installed components are plain Blade files the app owns.
## Install
```bash
php artisan ui:add code-block-command
```
## Usage
```blade
<div class="flex w-full flex-col gap-4">
<x-ui.code-block-command npm="npm install zod" />
<x-ui.code-block-command npm="npx shadcn@latest add button" :show="['npm', 'pnpm', 'bun']" />
</div>
```
## Props
- `npm` (mixed|null, default `null`)
- `pnpm` (mixed|null, default `null`)
- `yarn` (mixed|null, default `null`)
- `bun` (mixed|null, default `null`)
- `show` (mixed|null, default `null`)
## Use when
- Use for exact technical detail, code readability, diagnostics, and copyable reference material.
- Documenting an install or run command that differs per package manager.
- Letting a reader stay on their own package manager across a whole docs page.
## Avoid when
- Do not surface developer-specific patterns in end-user flows unless the task genuinely requires them.
- Showing a single command with no per-manager variant; code-block or code-line is enough.
- Switching between unrelated snippets; this control assumes the tabs say the same thing.
## Anti-patterns
- Exposing developer tooling in end-user flows without a task need
## Rules
- Use the `<brok:code-block-command>` tag (or `<x-ui.code-block-command>`) in Blade; do not rewrite the component.
- Prefer the documented props and variants over utility-class overrides; when a utility must win, use the `!` important modifier.
- Use semantic design tokens (`bg-primary`, `text-muted-foreground`), never raw colour utilities.
- Keep the `data-slot` attributes; they are the styling and test hooks.
## Links
- Docs: https://brokui.dev/docs/components/code-block-command
- Registry JSON (files, props, contract): https://brokui.dev/r/open/code-block-command.json
Working in Claude Code, Cursor or Codex? Give the agent the whole registry through the MCP server or the Brok UI skill.
API
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| npm | mixed | null | null | |
| pnpm | mixed | null | null | |
| yarn | mixed | null | null | |
| bun | mixed | null | null | |
| show | mixed | null | null |
Slots
default—
Data slots
Stable hooks for CSS overrides and browser tests.
Behavior
- Only the package managers given a command are rendered as tabs, and show picks the one selected first.
- The choice persists, so every command block on the page follows the last manager the reader picked.
- Copying copies the visible tab's command and announces the result in a polite live region.
- Installs a JavaScript behavior module when the registry item includes resources/js/ui files.
- Declares registry capability flags: a11y, interactive, responsive, rtl, darkMode, localized.
Guidance
Expose exact technical or diagnostic information.
Use when
- Use for exact technical detail, code readability, diagnostics, and copyable reference material.
- Documenting an install or run command that differs per package manager.
- Letting a reader stay on their own package manager across a whole docs page.
Avoid when
- Do not surface developer-specific patterns in end-user flows unless the task genuinely requires them.
- Showing a single command with no per-manager variant; code-block or code-line is enough.
- Switching between unrelated snippets; this control assumes the tabs say the same thing.
Use instead
- Plain-language product UI for nontechnical users
Anti-patterns
- Exposing developer tooling in end-user flows without a task need
- Anatomy
- Theming hooks
Accessibility
- Keyboard
- native
- Focus
managed
- The switcher is a real tablist: each tab carries aria-selected and roving tabindex, so arrow keys move between managers.
- The copy confirmation is announced through aria-live="polite" rather than only shown.
- Semantic HTML and a stable
data-slotattribute for styling and scripting hooks. - Focus-visible rings use the
ringtoken, so keyboard focus is always visible. - Disabled and invalid states are conveyed to assistive tech, not by color alone.
- Targets WCAG 2.2 AA; verify contrast in light, dark, admin and customer surfaces in the preview.
- Labels go through
__()and layout uses logical properties (ms-*,text-start), so it mirrors underdir="rtl"— flip the preview to RTL to confirm. - Dark mode uses the same semantic tokens under the
darkclass; high contrast follows forced-color system tokens.
Livewire
Add wire:ignore to the component root because its behavior owns rendered DOM.
<div wire:ignore>
<div class="flex w-full flex-col gap-4">
<x-ui.code-block-command npm="npm install zod" />
<x-ui.code-block-command npm="npx shadcn@latest add button" :show="['npm', 'pnpm', 'bun']" />
</div>
</div>
Validation
Validation support: native. Keep the error message connected with aria-describedby.
<form wire:submit="save" class="space-y-2">
<brok:code-block-command
wire:model="value"
:aria-invalid="$errors->has('value') ? 'true' : 'false'"
aria-describedby="value-error"
/>
@error('value')
<p id="value-error" role="alert">{{ $message }}</p>
@enderror
<brok:button type="submit" wire:loading.attr="disabled">
<span wire:loading.remove>Save</span>
<span wire:loading>Saving…</span>
</brok:button>
</form>
Source
The exact, editable files ui:add writes
into your app. Previews render this same code; there are no preview-only components.
@props([
'npm' => null,
'pnpm' => null,
'yarn' => null,
'bun' => null,
'show' => null,
])
@php
// Auto-derive pnpm/yarn/bun equivalents from a single npm command so callers
// can pass just `npm="npm install zod"`. Explicit per-manager props win.
$convert = function (string $cmd): array {
$cmd = trim($cmd);
if (preg_match('/^npm (install|i)\b/', $cmd)) {
$rest = trim(preg_replace('/^npm (install|i)\b/', '', $cmd));
$verb = $rest === '' ? 'install' : 'add';
$suffix = $rest === '' ? '' : ' '.$rest;
return ['pnpm' => trim("pnpm {$verb}{$suffix}"), 'yarn' => trim("yarn {$verb}{$suffix}"), 'bun' => trim("bun {$verb}{$suffix}")];
}
if (str_starts_with($cmd, 'npm run')) {
$rest = trim(substr($cmd, 7));
return ['pnpm' => trim("pnpm {$rest}"), 'yarn' => trim("yarn {$rest}"), 'bun' => trim("bun run {$rest}")];
}
if (str_starts_with($cmd, 'npx')) {
$rest = trim(substr($cmd, 3));
return ['pnpm' => "pnpm dlx {$rest}", 'yarn' => "yarn dlx {$rest}", 'bun' => "bunx {$rest}"];
}
return ['pnpm' => $cmd, 'yarn' => $cmd, 'bun' => $cmd];
};
$derived = $npm !== null ? $convert((string) $npm) : [];
$all = [
'npm' => $npm,
'pnpm' => $pnpm ?? ($derived['pnpm'] ?? null),
'yarn' => $yarn ?? ($derived['yarn'] ?? null),
'bun' => $bun ?? ($derived['bun'] ?? null),
];
$order = is_array($show) && $show !== [] ? $show : ['npm', 'pnpm', 'yarn', 'bun'];
$commands = [];
foreach ($order as $manager) {
if (! empty($all[$manager])) {
$commands[$manager] = (string) $all[$manager];
}
}
if ($commands === []) {
$commands = ['npm' => (string) ($npm ?? '')];
}
$managers = array_keys($commands);
$default = $managers[0];
$defaultCommand = $commands[$default];
$tabBase = 'relative -mb-px border-b-2 px-2 py-2 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-t-sm border-transparent text-muted-foreground hover:text-foreground aria-selected:border-primary aria-selected:text-foreground';
@endphp
<div
data-slot="code-block-command"
x-data="uiCodeBlockCommand({ commands: @js($commands), managers: @js($managers), default: @js($default) })"
{{ $attributes->merge(['class' => 'overflow-hidden rounded-lg border border-border bg-card text-foreground']) }}
>
{{-- Package-manager tabs --}}
<div role="tablist" aria-label="{{ __('Package manager') }}" class="flex items-center gap-1 border-b border-border px-2 pt-1">
@foreach ($managers as $manager)
<button
type="button"
role="tab"
@click="select(@js($manager))"
aria-selected="{{ $loop->first ? 'true' : 'false' }}"
x-bind:aria-selected="active === @js($manager) ? 'true' : 'false'"
x-bind:tabindex="active === @js($manager) ? 0 : -1"
class="{{ $tabBase }}"
>{{ $manager }}</button>
@endforeach
</div>
{{-- Command --}}
<div class="flex items-center gap-3 px-4 py-3">
<span class="select-none font-mono text-sm text-muted-foreground" aria-hidden="true">$</span>
<code class="min-w-0 flex-1 overflow-x-auto whitespace-nowrap font-mono text-sm text-foreground" x-text="command">{{ $defaultCommand }}</code>
<button
type="button"
@click="copy()"
x-bind:aria-label="copied ? @js(__('Copied')) : @js(__('Copy command'))"
class="inline-flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
>
<span aria-live="polite" class="sr-only" x-text="copied ? @js(__('Copied')) : ''"></span>
<svg x-show="!copied" class="size-4 shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
</svg>
<svg x-show="copied" x-cloak class="size-4 shrink-0 text-success" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M20 6 9 17l-5-5" />
</svg>
</button>
</div>
</div>
/**
* Code block command behaviour.
*
* Switches a CLI command between package managers (npm / pnpm / yarn / bun),
* persists the active choice in localStorage so it survives navigation, and
* copies the active command to the clipboard with a copy → check transition.
*
* Self-registers on `alpine:init` so import order does not matter — import this
* file once from your bundle (e.g. resources/js/ui/index.js).
*/
document.addEventListener('alpine:init', () => {
window.Alpine.data('uiCodeBlockCommand', (config = {}) => ({
managers: config.managers ?? [],
commands: config.commands ?? {},
active: config.default ?? (config.managers?.[0] ?? 'npm'),
copied: false,
_t: null,
init() {
// Restore the last package manager the visitor used, if it is one of
// the tabs this instance actually shows.
try {
const saved = localStorage.getItem('ui-package-manager');
if (saved && this.managers.includes(saved)) {
this.active = saved;
}
} catch (e) {
// localStorage can throw in private mode — ignore.
}
},
select(manager) {
if (!this.managers.includes(manager)) {
return;
}
this.active = manager;
try {
localStorage.setItem('ui-package-manager', manager);
} catch (e) {
// ignore
}
},
get command() {
return this.commands[this.active] ?? '';
},
async copy() {
const text = this.command;
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
} else {
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.focus();
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
}
this.copied = true;
clearTimeout(this._t);
this._t = setTimeout(() => {
this.copied = false;
}, 2000);
} catch (e) {
// Swallow — copy failure is non-fatal.
}
},
destroy() {
clearTimeout(this._t);
},
}));
});
Ownership & lifecycle
Owner, release state, review evidence and adoption for this item.
- Owner
- Platform UI (@JoshJML)
- Current version
-
1.0.4 - Status
- Stable
- License
-
open - Accessibility reviewed
- No review date recorded
- Last breaking change
- No date recorded
- Deprecation
- Not deprecated
- Contract
-
v6 - Foundation
-
≥ 1.0.0