Code block
Code with a title, line numbers, a copy button, and the colours of the tokens a tokenizer found.
Previews are drawn in the theme you made.
Edit itTokens and line numbers #
export const total = 3 // items
export const done = "yes"import { CodeBlock, CodeBlockSlots, Recipes } from 'foldkit-mixins-ui'
import { example } from '../../gallery/example.js'
const SOURCE = 'export const total = 3 // items\nexport const done = "yes"'
// Highlighting is the caller's: pass the tokens a tokenizer found as offsets
// into the code (`foldkit-richtext-code-shiki` finds them), and each is drawn
// with its `kind`, which the theme colours. The text of the block is the code.
export default example({
title: 'Tokens and line numbers',
slots: CodeBlockSlots,
recipe: Recipes.CodeBlock,
view: ({ style, h }) =>
CodeBlock.view(
{
code: SOURCE,
title: 'totals.ts',
lineNumbers: true,
tokens: [
{ from: 0, to: 6, kind: 'syntax-keyword' },
{ from: 7, to: 12, kind: 'syntax-keyword' },
{ from: 19, to: 20, kind: 'syntax-operator' },
{ from: 21, to: 22, kind: 'syntax-number' },
{ from: 23, to: 31, kind: 'syntax-comment' },
{ from: 32, to: 38, kind: 'syntax-keyword' },
{ from: 39, to: 44, kind: 'syntax-keyword' },
{ from: 52, to: 57, kind: 'syntax-string' },
],
style,
},
h,
),
})In your application: recipe goes to forSlots, and the body of view is the call. example is this site’s harness.
The copy button #
npm install foldkit-plusimport { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { CodeBlock, CodeBlockSlots, Recipes } from 'foldkit-mixins-ui'
import { copyText } from 'foldkit-primitives/dom'
import { example } from '../../gallery/example.js'
const Model = Schema.Struct({ copied: Schema.Boolean })
// `Copied` and `CopyFailed` are what `copyText`'s Command answers.
const Message = defineMessageUnion({
PressedCopy: { code: Schema.String },
Copied: {},
CopyFailed: { message: Schema.String },
})
// The button sends what `onCopy` makes of the code; `update` runs `copyText`
// from `foldkit-primitives` and draws `copied: true` once it answers.
export default example({
title: 'The copy button',
slots: CodeBlockSlots,
recipe: Recipes.CodeBlock,
state: {
Model,
Message,
init: () => ({ model: { copied: false } }),
update: (model, message) =>
Message.match(message, {
PressedCopy: ({ code }) => ({ model, commands: [copyText(code)] }),
Copied: () => ({ model: model.copied ? model : { copied: true } }),
CopyFailed: () => ({ model }),
}),
},
view: ({ style, model, onMessage, h }) =>
CodeBlock.view(
{
code: 'npm install foldkit-plus',
language: 'sh',
copy: {
copied: model.copied,
onCopy: code => onMessage(Message.PressedCopy({ code })),
},
style,
},
h,
),
})In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.
A diff #
export const view = (model: Model) =>
h.p([], [model.name])
h.p([h.Class("name")], [model.name])
h.small([], [model.role])import { CodeBlock, CodeBlockSlots, Recipes } from 'foldkit-mixins-ui'
import { example } from '../../gallery/example.js'
// A diff is the lines, each marked `added` or `removed`, and a gutter that
// says so in place of a number. Each mark tints the whole row.
const lines = [
{ text: 'export const view = (model: Model) =>', change: ' ' },
{ text: ' h.p([], [model.name])', change: '-' },
{ text: ' h.p([h.Class("name")], [model.name])', change: '+' },
{ text: ' h.small([], [model.role])', change: '+' },
]
export default example({
title: 'A diff',
slots: CodeBlockSlots,
recipe: Recipes.CodeBlock,
view: ({ style, h }) =>
CodeBlock.view(
{
code: lines.map(line => line.text).join('\n'),
title: 'profile.ts',
gutter: line => lines[line - 1]?.change ?? ' ',
marks: lines.flatMap((line, index) =>
line.change === ' '
? []
: [{ line: index + 1, kind: line.change === '+' ? 'added' : 'removed' }],
),
style,
},
h,
),
})In your application: recipe goes to forSlots, and the body of view is the call. example is this site’s harness.
Focus on a line #
const update = (model: Model, message: Message) =>
Message.match(message, {
Typed: ({ text }) => ({ model: { ...model, text } }),
Cleared: () => ({ model: { ...model, text: "" } }),
})import { CodeBlock, CodeBlockSlots, Recipes } from 'foldkit-mixins-ui'
import { example } from '../../gallery/example.js'
const SOURCE = [
'const update = (model: Model, message: Message) =>',
' Message.match(message, {',
' Typed: ({ text }) => ({ model: { ...model, text } }),',
' Cleared: () => ({ model: { ...model, text: "" } }),',
' })',
].join('\n')
// An excerpt starts at its own line (`startLine`), and every mark counts from
// it: the line a walkthrough is about is `highlight`, the rest `dim`.
export default example({
title: 'Focus on a line',
slots: CodeBlockSlots,
recipe: Recipes.CodeBlock,
view: ({ style, h }) =>
CodeBlock.view(
{
code: SOURCE,
title: 'update.ts',
lineNumbers: true,
startLine: 24,
marks: [
{ line: 24, kind: 'dim' },
{ line: 25, kind: 'dim' },
{ line: 26, kind: 'highlight' },
{ line: 27, kind: 'dim' },
{ line: 28, kind: 'dim' },
],
style,
},
h,
),
})In your application: recipe goes to forSlots, and the body of view is the call. example is this site’s harness.
Diagnostics #
function greet() {
const name = "Ada"name is never read
let greeting = "Hello"prefer const
return greeting
}import { Option } from 'effect'
import { Badge, CodeBlock, CodeBlockSlots, Recipes } from 'foldkit-mixins-ui'
import { example } from '../../gallery/example.js'
const Tag = Recipes.Badge.style({ size: 'sm' })
const problems = new Map([
[2, { kind: 'error', text: 'name is never read' }],
[3, { kind: 'warning', text: 'prefer const' }],
])
// A checker's findings: each line it flagged is marked by severity, and
// `lineAction` puts the finding at the line's end, here a Badge.
export default example({
title: 'Diagnostics',
slots: CodeBlockSlots,
recipe: Recipes.CodeBlock,
view: ({ style, h }) =>
CodeBlock.view(
{
code: 'function greet() {\n const name = "Ada"\n let greeting = "Hello"\n return greeting\n}',
title: 'greet.ts',
lineNumbers: true,
marks: Array.from(problems, ([line, problem]) => ({ line, kind: problem.kind })),
lineAction: line =>
Option.map(Option.fromUndefinedOr(problems.get(line)), problem =>
Badge.view(
{
text: problem.text,
tone: problem.kind === 'error' ? 'danger' : 'warning',
style: Tag,
},
h,
),
),
style,
},
h,
),
})In your application: recipe goes to forSlots, and the body of view is the call. example is this site’s harness.
Collapsed #
{ id: 1, name: "Item 1" },
{ id: 2, name: "Item 2" },
{ id: 3, name: "Item 3" },
{ id: 4, name: "Item 4" },
{ id: 5, name: "Item 5" },
{ id: 6, name: "Item 6" },
{ id: 7, name: "Item 7" },
{ id: 8, name: "Item 8" },
{ id: 9, name: "Item 9" },
{ id: 10, name: "Item 10" },
{ id: 11, name: "Item 11" },
{ id: 12, name: "Item 12" },
{ id: 13, name: "Item 13" },
{ id: 14, name: "Item 14" },import { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { CodeBlock, CodeBlockSlots, Recipes } from 'foldkit-mixins-ui'
import { example } from '../../gallery/example.js'
const SOURCE = Array.from(
{ length: 14 },
(_, index) => ` { id: ${index + 1}, name: "Item ${index + 1}" },`,
).join('\n')
const Model = Schema.Struct({ expanded: Schema.Boolean })
const Message = defineMessageUnion({ Toggled: {} })
// `collapsed` clips the block to its first lines under a fade and draws a
// button for the rest; every line stays in the page, so a find or a copy
// reaches all of it. Whether the block is open is the application's: the
// button's Message flips `expanded`, and the block then offers to close.
export default example({
title: 'Collapsed',
slots: CodeBlockSlots,
recipe: Recipes.CodeBlock,
state: {
Model,
Message,
init: () => ({ model: { expanded: false } }),
update: model => ({ model: { expanded: !model.expanded } }),
},
view: ({ style, model, onMessage, h }) =>
CodeBlock.view(
{
code: SOURCE,
title: 'items.ts',
lineNumbers: true,
collapsed: {
lines: 5,
expanded: model.expanded,
onToggle: onMessage(Message.Toggled()),
},
style,
},
h,
),
})In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.
Choosing lines #
const a = 1
const b = 2
const c = a + b
console.log(c)import { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { CodeBlock, CodeBlockSlots, Recipes } from 'foldkit-mixins-ui'
import { example } from '../../gallery/example.js'
const SOURCE = 'const a = 1\nconst b = 2\nconst c = a + b\nconsole.log(c)'
const Model = Schema.Struct({ selected: Schema.Array(Schema.Number) })
const Message = defineMessageUnion({ Toggled: { line: Schema.Number } })
// `onLineSelect` makes each line's number a button. Which lines are chosen is
// the application's: it marks them `selected`, which presses their buttons.
export default example({
title: 'Choosing lines',
slots: CodeBlockSlots,
recipe: Recipes.CodeBlock,
state: {
Model,
Message,
init: () => ({ model: { selected: [3] } }),
update: (model, { line }) => ({
model: {
selected: model.selected.includes(line)
? model.selected.filter(each => each !== line)
: [...model.selected, line],
},
}),
},
view: ({ style, model, onMessage, h }) =>
CodeBlock.view(
{
code: SOURCE,
title: 'sum.ts',
onLineSelect: line => onMessage(Message.Toggled({ line })),
marks: model.selected.map(line => ({ line, kind: 'selected' })),
style,
},
h,
),
})In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.
Long lines #
[12:04:01] GET /api/projects/7f3c2a/members?include=roles,invitations&page=1 200 34ms
[12:04:02] POST /api/projects/7f3c2a/invitations {"email":"grace@example.com","role":"editor"} 201 58msimport { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { Button, CodeBlock, CodeBlockSlots, Recipes } from 'foldkit-mixins-ui'
import { example } from '../../gallery/example.js'
import { stack } from '../../snippets/layout.js'
const Toggle = Recipes.Button.style({ variant: 'outline', size: 'sm' })
const LOG = [
'[12:04:01] GET /api/projects/7f3c2a/members?include=roles,invitations&page=1 200 34ms',
'[12:04:02] POST /api/projects/7f3c2a/invitations {"email":"grace@example.com","role":"editor"} 201 58ms',
].join('\n')
const Model = Schema.Struct({ wrap: Schema.Boolean })
const Message = defineMessageUnion({ Toggled: {} })
// A long line scrolls sideways; `wrap` folds it inside the frame instead.
export default example({
title: 'Long lines',
slots: CodeBlockSlots,
recipe: Recipes.CodeBlock,
state: {
Model,
Message,
init: () => ({ model: { wrap: false } }),
update: model => ({ model: { wrap: !model.wrap } }),
},
view: ({ style, model, onMessage, h }) =>
stack(h, [
Button.view(
{
label: 'Wrap lines',
pressed: model.wrap,
onClick: onMessage(Message.Toggled()),
style: Toggle,
},
h,
),
CodeBlock.view({ code: LOG, language: 'log', wrap: model.wrap, style }, h),
]),
})In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.
No header bar #
pnpm add foldkit-mixins-uiimport { CodeBlock, CodeBlockSlots, Recipes } from 'foldkit-mixins-ui'
import { example } from '../../gallery/example.js'
// `header: 'float'` drops the bar: the copy button pins to the code's corner,
// for a command a reader only copies.
export default example({
title: 'No header bar',
slots: CodeBlockSlots,
recipe: Recipes.CodeBlock,
pins: { header: 'float' },
view: ({ style, h }) =>
CodeBlock.view({ code: 'pnpm add foldkit-mixins-ui', language: 'sh', copy: {}, style }, h),
})In your application: recipe goes to forSlots, and the body of view is the call. example is this site’s harness.
Always dark #
$ pnpm build
✓ 214 modules transformed.
dist/index.js 48.2 kB │ gzip: 15.1 kBimport { CodeBlock, CodeBlockSlots, Recipes } from 'foldkit-mixins-ui'
import { example } from '../../gallery/example.js'
// `scheme: 'dark'` keeps a terminal dark on a light page: the theme's own
// dark half, tokens and all, inside the block.
export default example({
title: 'Always dark',
slots: CodeBlockSlots,
recipe: Recipes.CodeBlock,
pins: { scheme: 'dark' },
view: ({ style, h }) =>
CodeBlock.view(
{
code: '$ pnpm build\n✓ 214 modules transformed.\ndist/index.js 48.2 kB │ gzip: 15.1 kB',
title: 'Terminal',
tokens: [
{ from: 0, to: 1, kind: 'syntax-punctuation' },
{ from: 13, to: 14, kind: 'syntax-string' },
],
copy: {},
style,
},
h,
),
})In your application: recipe goes to forSlots, and the body of view is the call. example is this site’s harness.
Written live #
step 1: done
step 2: done
step 3: done
step 4: doneimport { Schema } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import { Button, CodeBlock, CodeBlockSlots, Recipes } from 'foldkit-mixins-ui'
import { example } from '../../gallery/example.js'
import { stack } from '../../snippets/layout.js'
const Write = Recipes.Button.style({ variant: 'outline', size: 'sm' })
// A body that scrolls: `extend` gives it a height of its own.
const Short = Recipes.CodeBlock.extend({
base: { body: { maxBlockSize: '9rem', overflowY: 'auto' } },
})
const Model = Schema.Struct({ lines: Schema.Number })
const Message = defineMessageUnion({ Wrote: {} })
// Code an agent is writing grows at the end. `CodeBlock.follow` in `mixins`
// keeps the end in view while the reader is there; scroll up and it waits.
export default example({
title: 'Written live',
slots: CodeBlockSlots,
recipe: Short,
state: {
Model,
Message,
init: () => ({ model: { lines: 4 } }),
update: model => ({ model: { lines: model.lines + 1 } }),
},
view: ({ style, model, onMessage, h }) =>
stack(h, [
CodeBlock.view(
{
code: Array.from({ length: model.lines }, (_, index) => `step ${index + 1}: done`).join(
'\n',
),
title: 'agent.log',
lineNumbers: true,
mixins: CodeBlock.follow,
style,
},
h,
),
Button.view({ label: 'Write a line', onClick: onMessage(Message.Wrote()), style: Write }, h),
]),
})In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.
A mark of your own #
const retries = 3
const timeout = 5_000 // TODO: read from config
export { retries, timeout }import { Style } from 'foldkit-mixins'
import { CodeBlock, CodeBlockSlots, Recipes } from 'foldkit-mixins-ui'
import { example } from '../../gallery/example.js'
import { t } from '../../snippets/theme.js'
// A mark of your own is a kind the recipe does not know: `extend` gives the
// line a tint for it, read from `data-mark` as the shipped marks are.
const Reviewed = Recipes.CodeBlock.extend({
base: {
line: Style.states({ todo: { background: t.info.subtle, fontStyle: 'italic' } }, 'data-mark'),
},
})
export default example({
title: 'A mark of your own',
slots: CodeBlockSlots,
recipe: Reviewed,
view: ({ style, h }) =>
CodeBlock.view(
{
code: 'const retries = 3\nconst timeout = 5_000 // TODO: read from config\nexport { retries, timeout }',
lineNumbers: true,
marks: [{ line: 2, kind: 'todo' }],
style,
},
h,
),
})In your application: recipe goes to forSlots, and the body of view is the call. example is this site’s harness.
Usage
Each example above is a module of its own, shown whole and run as shown, over the theme module Create a theme writes. The page hands it the style picked above.
Keyboard and accessibility
- The block is a
figureholding apreand itscode; the text is the code exactly, so a screen reader reads what is copied. - The copy button is a
buttonoftype="button": Tab reaches it, Enter and Space press it. It is drawn only whencopyis given. - A copy is announced in a
role="status"region beside the button, not by moving focus.