Skip to contentKino
Skip to Content

Code block

Code in its colours, under a header that names the file or holds a tab for each one, with a Copy button. Lines can be numbered, highlighted, added or removed, and a long file shows its first lines until it is expanded.

npx shadcn add https://kinoui.com/r/code-block.json
Share on

Examples

import { Badge } from '@/components/ui/badge'import { formatMoney } from '@/lib/money'import type { Invoice } from './types'export function InvoiceRow({ invoice }: { invoice: Invoice }) {  const overdue = invoice.status === 'open' && invoice.due < today() (highlighted)  return (    <tr className='border-b last:border-0'>      <td className='py-2 font-medium'>{invoice.number}</td>      <td>{invoice.customer.name}</td>      <td className='text-end tabular-nums'>        {formatMoney(invoice.total, invoice.currency)}      </td>      <td>        <Badge variant={overdue ? 'destructive' : 'secondary'}>          {overdue ? 'Overdue' : invoice.status}        </Badge>      </td>    </tr>  )}

Files

One file shows its name in the header; several get a tab each, and Copy takes the file shown. highlighted marks the lines to read first.

pnpm dlx shadcn@latest add @kino/code-block

Package managers

A tab for each package manager. Hold the pick with value and onValueChange to keep every command on the page on the same one.

globals.css
:root {  --radius: 0.625rem;  --primary: oklch(0.205 0 0); (removed)  --primary: oklch(0.55 0.2 262); (added)  --primary-foreground: oklch(0.985 0 0);}

Changed lines

added and removed mark a change with a sign and a colour, as a diff does, while the code keeps its own colours.

app/api/invoices/route.ts
import { db } from '@/lib/db'import { requireUser } from '@/lib/auth'import { NextResponse } from 'next/server'import { z } from 'zod'const Query = z.object({  status: z.enum(['draft', 'open', 'paid', 'void']).optional(),  customer: z.string().optional(),  cursor: z.string().optional(),  limit: z.coerce.number().int().min(1).max(100).default(25),})export async function GET(request: Request) {  const user = await requireUser(request)  const params = Object.fromEntries(new URL(request.url).searchParams)  const query = Query.safeParse(params)  if (!query.success) {    return NextResponse.json({ error: query.error.flatten() }, { status: 400 })  }  const { status, customer, cursor, limit } = query.data  const invoices = await db.invoice.findMany({    where: {      workspaceId: user.workspaceId,      status,      customerId: customer,    },    orderBy: { createdAt: 'desc' },    take: limit + 1,    cursor: cursor ? { id: cursor } : undefined,    include: { customer: { select: { id: true, name: true } } },  })  const next = invoices.length > limit ? invoices.pop()?.id : undefined  return NextResponse.json({    invoices,    next,    // Totals are in minor units; the client formats them in the workspace's locale.    currency: user.workspace.currency,  })}

Long file

With collapsedLines, a longer file shows its first lines and fades out above a button that shows the rest. A file only a few lines longer shows in full.

route.ts
  const params = Object.fromEntries(new URL(request.url).searchParams)  const query = Query.safeParse(params) (highlighted)  if (!query.success) { (highlighted)    return NextResponse.json({ error: query.error.flatten() }, { status: 400 })  }

Excerpt

startLine numbers a few lines quoted from further down a file, and the marks count from it.

app/api/invoices/[id]/route.ts
import { db } from '@/lib/db'import { requireUser } from '@/lib/auth'import { NextResponse } from 'next/server'import { z } from 'zod'const Query = z.object({  status: z.enum(['draft', 'open', 'paid', 'void']).optional(),  customer: z.string().optional(),  cursor: z.string().optional(),  limit: z.coerce.number().int().min(1).max(100).default(25),})export async function GET(request: Request) {  const user = await requireUser(request)  const params = Object.fromEntries(new URL(request.url).searchParams)  const query = Query.safeParse(params)  if (!query.success) {    return NextResponse.json({ error: query.error.flatten() }, { status: 400 })  }  const { status, customer, cursor, limit } = query.data  const invoices = await db.invoice.findMany({    where: {      workspaceId: user.workspaceId,      status,      customerId: customer,    },    orderBy: { createdAt: 'desc' },    take: limit + 1,    cursor: cursor ? { id: cursor } : undefined,    include: { customer: { select: { id: true, name: true } } },  })  const next = invoices.length > limit ? invoices.pop()?.id : undefined  return NextResponse.json({    invoices,    next,    // Totals are in minor units; the client formats them in the workspace's locale.    currency: user.workspace.currency,  })}

Max height

Set --code-block-max-height and a long file scrolls inside the block, with a thin scrollbar, instead of collapsing.

Installation

npx shadcn@latest add https://kinoui.com/r/code-block.json
Files
lib/reduce-motion.tslib/scroll.tslib/refs.tslib/resize.tslib/swap.tsxlib/popup.tslib/glide.tsxcomponents/kino/tooltip.tsxlib/cut.tsxcomponents/kino/spinner.tsxcomponents/kino/button.tsxlib/announce.tsxcomponents/kino/copy-button.tsxlib/run-progress.tslib/highlight.tslib/pill.tscomponents/kino/tabs.tsxlib/syntax.tslib/code-lines.tsxlib/controllable.tscomponents/kino/code-block.tsx
Packages
@base-ui/reactclass-variance-authorityshiki

New to Kino? Installation covers what your project needs first and the @kino namespace.

API reference

Props

PropTypeDefaultDescription
filesCodeFile[]NoneEach file: its code, its language, a title, the startLine, and the lines highlighted, added or removed as numbers and ranges, such as [2, [5, 7]]. A label names the code for a screen reader where the title is the same as other code on the page.
valuestringNoneThe file shown, by its value, which is its title or its language unless given.
defaultValuestringNoneThe file shown at first.
onValueChange(value: string) => voidNoneCalled when a tab is picked.
lineNumbersbooleanfalseNumbers each line in a gutter that copying leaves out.
collapsedLinesnumberNoneHow many lines a longer file shows until expanded. Files no more than 3 lines longer show in full.
expandedbooleanNoneWhether a long file shows in full.
defaultExpandedbooleanfalseWhether it shows in full at first.
onExpandedChange(expanded: boolean) => voidNoneCalled when the Expand button is pressed.
labelstring'Files'The tabs’ name for a screen reader, such as “Package manager”.
tooltipPropsTooltipContent.PropsNoneProps for the Copy button’s tooltip, as the Copy button takes them.
onCopy(file: CodeFile) => voidNoneCalled when the Copy button is pressed, with the file it copies.

Data attributes

AttributeOnDescription
data-lineEach lineIts line number.
data-markEach marked linehighlighted, added or removed.

CSS variables

VariableSet it onDefaultDescription
--code-block-max-heightCodeBlock or abovenoneThe tallest the code gets before it scrolls.
--code-keyword, --code-string, --code-function, …:root and .darkKino’s paletteThe code’s colours, which the item adds to your global CSS. Each one is at least 4.5:1 on the block in light and dark.

Accessibility

  • The code is a region named after its file, which takes focus from the keyboard when it scrolls, so arrow keys can scroll it.
  • Tabs follow the tabs pattern: arrows move between files and the tab list has a name.
  • Line numbers and signs are hidden from screen readers and from what you copy; a marked line ends with its mark, such as “(added)”, for a screen reader.
  • Added and removed lines show a sign as well as a colour, and in forced colours a marked line keeps a bar at its start.
  • The Expand button says how many lines it shows and points at the code it expands; collapsing a block whose top has scrolled away brings it back into view, below its scroll-margin-top when a sticky header covers the top of the page.