@k8ordo/ui

CodeBlock

サーバーでハイライトし、コピーのボタンを添えたコードブロックです。入口は@k8ordo/ui/code-blockです。

インポート

ハイライトはサーバーで済ませるので、shikiはブラウザに送られません。server-onlyをimportしているので、Client Componentから読み込むとビルドがエラーになります。

ts
import { CodeBlock } from '@k8ordo/ui/code-block';

使い方

tsx
export function Total({ items }: { items: Item[] }) {
  const done = items.filter((item) => item.done).length;
  return <p>{done} / {items.length}</p>;
}
tsx
<CodeBlock code={source} lang="tsx" />

ファイル名

titleを渡すと、見出しの行に言語名の代わりに表示します。見出しはfigureのfigcaptionになります。

total.tsx
export function Total({ items }: { items: Item[] }) {
  const done = items.filter((item) => item.done).length;
  return <p>{done} / {items.length}</p>;
}
tsx
<CodeBlock code={source} lang="tsx" title="total.tsx" />

行の印

marksは、1から数える行番号にhighlightかadd、removeを付けます。追加と削除は、色のほかに+と−でも示します。

ts
const done = items.filter((item) => item.done).length;
const rate = done / items.length;
const rate = items.length === 0 ? 0 : done / items.length;
tsx
<CodeBlock
  code={source}
  lang="ts"
  marks={{ 1: 'highlight', 2: 'remove', 3: 'add' }}
/>

注記

calloutsは、行の直後にその行の字下げにそろえて注記を置きます。配列を渡すと、書いた順に並びます。コピーされるのはcodeそのもので、印や注記は含まれません。

ts
const done = items.filter((item) => item.done).length;
const rate = done / items.length;
const rate = items.length === 0 ? 0 : done / items.length;
Guard the division when the list is empty
tsx
<CodeBlock
  callouts={{ 3: 'Guard the division when the list is empty' }}
  code={source}
  lang="ts"
/>

色とダークモード

色はk8oのブログと同じ固定の値で、デザイントークンは使いません。ライトはshikiのone-light、ダークはplasticです。色はlight-dark()で書いているので、.darkが切り替えるcolor-schemeに従います。外枠の線は無く、言語名かファイル名は同じ背景の上に小さなラベルとして置きます。shikiが知らない言語名のコードは、色を付けずに描きます。

Props

code
Type: string
Default: -
callouts?
Type: Readonly<Record<number, string | readonly string[]>>
Default: -
lang?
Type: string
Default: 'text'
marks?
Type: Readonly<Record<number, 'highlight' | 'add' | 'remove'>>
Default: -
title?
Type: string
Default: -
PropTypeDefault
codestring-
callouts?Readonly<Record<number, string | readonly string[]>>-
lang?string'text'
marks?Readonly<Record<number, 'highlight' | 'add' | 'remove'>>-
title?string-

継承する属性(内部で固定するものを除く): HTMLAttributes<HTMLElement>

ラベルやプレースホルダーなど、このコンポーネントが描く文言は、propsで指定しないと文言辞書から読まれます。差し替え方は次を見てください: コンポーネントの文言

k8ordo

Baselineに入った機能を、制限なく使うReactのライブラリ群。