Kit
Every component on this site reaches its shared controls, chips, and drawing helpers through one entry, site/.vitepress/kit, and a lint rule fails on an import that goes around it. The sections below render each piece the entry exports, live and in the site's own style, beside its source.
The site suite fails on an export that carries no declaration, so a piece reaches this page in the change that adds it. A declaration holds the piece's use and its examples, in a .catalog.tsx file beside the piece.
Chip
Sets a rule or a family in a small mono label, which becomes a link where it takes an address.
import { defineComponent, h } from 'vue'
import type { PropType } from 'vue'
import { externalAttrs } from '../../lib/shared/links'
type ChipVariant = 'family-chip' | 'rule-chip'
// Renders a chip as a link where `href` is set and as a span where it is not.
export const Chip = defineComponent({
name : 'Chip',
props : {
family : String,
href : String,
title : String,
variant : { required: true, type: String as PropType<ChipVariant> }
},
setup(props, { slots }) {
return () => h(
props.href ? 'a' : 'span',
{
href : props.href,
title : props.title,
'data-family' : props.family,
class : ['chip', props.variant],
...externalAttrs(props.href)
},
slots.default?.()
)
}
})
CopyButton
Copies a string to the clipboard from the corner of a block, its glyph and its label reporting the copy.
uv tool install proseimport { useClipboard } from '@vueuse/core'
import { defineComponent } from 'vue'
// Copies `source` to the clipboard, its glyph and its label reporting the copy
// for `copiedDuring` milliseconds.
export const CopyButton = defineComponent({
name : 'CopyButton',
props : {
copiedDuring : Number,
label : { required: true, type: String },
source : { required: true, type: String }
},
setup(props) {
const { copied, copy } = useClipboard({ copiedDuring: props.copiedDuring })
return () => {
const label = copied.value ? 'Copied' : props.label
return (
<button aria-label={label} class={['copy', { copied: copied.value }]} onClick={() => copy(props.source)} title={label} type="button">
<svg aria-hidden="true" class="glyph" fill="none" viewBox="0 0 24 24">
<rect height="4" rx="1" width="8" x="8" y="2" />
<path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2" />
{copied.value ? <path class="copy-tick" d="m9 14 2 2 4-4" /> : null}
</svg>
</button>
)
}
}
})
Disclosure
Opens and closes one block from one trigger, leaving its markup and its open state to the caller.
A disclosed note.
import * as collapsible from '@zag-js/collapsible'
import { normalizeProps, useMachine } from '@zag-js/vue'
import type { PropTypes } from '@zag-js/vue'
import { computed, defineComponent, useId } from 'vue'
import type { SlotsType } from 'vue'
export interface DisclosureScope {
content : PropTypes['element']
trigger : PropTypes['button']
}
// Binds one disclosure through the `collapsible` machine, leaving its markup
// to the slot and its open state to the caller.
export const Disclosure = defineComponent({
name : 'Disclosure',
props : { open: { required: true, type: Boolean } },
emits : { 'update:open': (open: boolean) => typeof open === 'boolean' },
slots : Object as SlotsType<{ default: DisclosureScope }>,
setup(props, { emit, slots }) {
const id = useId()
const service = useMachine(collapsible.machine, computed(() => ({
id,
onOpenChange : ({ open }: collapsible.OpenChangeDetails) => emit('update:open', open),
open : props.open
})))
const api = computed(() => collapsible.connect(service, normalizeProps))
return () => slots.default({
content : api.value.getContentProps(),
trigger : api.value.getTriggerProps()
})
}
})
DocHeading
Renders a section heading beside its permalink, for a section a component writes in place of Markdown.
A Section Heading
import { defineComponent } from 'vue'
import { PermalinkAnchor } from './PermalinkAnchor'
// Renders a section's `h2` beside its permalink.
export const DocHeading = defineComponent({
name : 'DocHeading',
props : {
id : { required: true, type: String },
title : { required: true, type: String }
},
setup(props) {
return () => (
<h2 id={props.id} tabindex="-1">
{props.title}{' '}
<PermalinkAnchor anchor={props.id} label={props.title} />
</h2>
)
}
})
FamilyChip
Names a rule family beside its drawn nib, reading the family of the current rule where none is passed.
import { computed, defineComponent } from 'vue'
import type { PropType } from 'vue'
import { useCurrentRule } from '../../lib/composables/route'
import { familyEmblem } from '../../lib/shared/emblems'
import * as registries from '../../lib/shared/registries'
import { NibBadge } from '../drawing/NibBadge'
import { Chip } from './Chip'
// Renders a family's chip, reading the current rule's family where `family`
// is unset, linked to the family's page unless `linked` is false.
export const FamilyChip = defineComponent({
name : 'FamilyChip',
props : {
family : String as PropType<registries.GlossaryFamily>,
linked : { default: true, type: Boolean }
},
setup(props) {
const rule = useCurrentRule()
const family = computed(() => props.family ?? rule.value?.family ?? null)
const emblem = computed(() => family.value && familyEmblem(family.value))
const href = computed(() => props.linked && family.value && family.value in registries.FAMILY_META
? `/rules/${family.value}/`
: undefined)
return () => {
const current = emblem.value
return current
? (
<Chip class="nib-ground" family={current.family} href={href.value} variant="family-chip">
{{
default: () => [
<NibBadge emblem={current} size={15.2} />,
<span>{current.name}</span>
]
}}
</Chip>
)
: null
}
}
})
Kicker
Sets the small uppercase line that opens a section.
Read on
Read on
Read on
import { defineComponent } from 'vue'
import type { PropType } from 'vue'
// Renders the small uppercase line that opens a section.
export const Kicker = defineComponent({
name : 'Kicker',
props : { variant: { default: 'plain', type: String as PropType<'plain' | 'rule' | 'wide'> } },
setup(props, { slots }) {
return () => <p class="kicker" data-variant={props.variant}>{slots.default?.()}</p>
}
})
Listbox
Picks one value from a short list, positioned against its trigger, leaving its markup to the caller.
import * as select from '@zag-js/select'
import { normalizeProps, useMachine } from '@zag-js/vue'
import type { PropTypes } from '@zag-js/vue'
import { computed, defineComponent, useId } from 'vue'
import type { PropType, PublicProps, SlotsType, VNodeChild } from 'vue'
interface ListboxOption {
id : string
}
interface ListboxProps<T extends ListboxOption> extends PublicProps {
label : string
modelValue : string
'onUpdate:modelValue'?: (value: string) => void
options : readonly T[]
}
export interface ListboxScope<T extends ListboxOption> {
content : PropTypes['element']
item : (option: T) => PropTypes['element']
positioner : PropTypes['element']
trigger : PropTypes['button']
}
type GenericListbox = new <T extends ListboxOption>(props: ListboxProps<T>) => {
$props : ListboxProps<T>
$slots : { default: (scope: ListboxScope<T>) => VNodeChild }
}
// Binds a single-choice listbox through the `select` machine, naming both the
// trigger and the list with `label` and leaving the markup to the slot.
export const Listbox = defineComponent({
name : 'Listbox',
props : {
label : { required: true, type: String },
modelValue : { required: true, type: String },
options : { required: true, type: Array as PropType<readonly ListboxOption[]> }
},
emits : { 'update:modelValue': (value: string) => typeof value === 'string' },
slots : Object as SlotsType<{ default: ListboxScope<ListboxOption> }>,
setup(props, { emit, slots }) {
const id = useId()
const collection = computed(() => select.collection({
items : [...props.options],
itemToString : option => option.id,
itemToValue : option => option.id
}))
const service = useMachine(select.machine, computed(() => ({
collection : collection.value,
id,
onValueChange : ({ value }: select.ValueChangeDetails) => emit('update:modelValue', value[0]!),
positioning : { placement: 'bottom-start' as const, sameWidth: false },
value : [props.modelValue]
})))
const api = computed(() => select.connect(service, normalizeProps))
return () => {
const { 'aria-labelledby': _content, ...content } = api.value.getContentProps()
const { 'aria-labelledby': _trigger, ...trigger } = api.value.getTriggerProps()
return slots.default({
content : { ...content, 'aria-label': props.label },
item : option => ({ ...api.value.getItemProps({ item: option }), tabIndex: -1 }),
positioner : api.value.getPositionerProps(),
trigger : { ...trigger, 'aria-label': props.label }
})
}
}
}) as unknown as GenericListbox
MiddleEllipsis
Shortens a path from its middle until it fits its box, keeping the end of the path readable.
import { defineComponent, ref, watch } from 'vue'
import { useSettledMeasure } from '../../lib/composables/use-settled-measure'
import { middleEllipsis } from '../../lib/shared/middle-ellipsis'
// Shortens `text` from its middle to fit its span, keeping `tail` characters
// after the ellipsis.
export const MiddleEllipsis = defineComponent({
name : 'MiddleEllipsis',
props : {
tail : { default: 3, type: Number },
text : { required: true, type: String }
},
setup(props) {
const el = ref<HTMLSpanElement>()
const display = ref(props.text)
function fit(): void {
const span = el.value
if (!span) return
const fits = (candidate: string): boolean => {
span.textContent = candidate
return span.scrollWidth <= span.clientWidth + 1
}
display.value = middleEllipsis(fits, props.tail, props.text)
// The probes above mutated the span directly, so restore the chosen text
// even when the ref value is unchanged and Vue skips the patch.
span.textContent = display.value
}
useSettledMeasure(el, fit)
watch(() => props.text, fit)
return () => <span class="overflow-hidden whitespace-nowrap" ref={el}>{display.value}</span>
}
})
nib
Holds the measures of the nib drawings and writes a badge as inert markup, for a loader or a Markdown rule where no component mounts.
import { h } from 'vue'
import type { VNode, VNodeChild } from 'vue'
import type { Emblem, Fit, Motif } from '../../lib/shared/emblems'
// Draws every motif with a 0.62-unit stroke repeated along the 45-degree
// diagonal at the offsets of its size, and displaces the large copies with
// turbulence, so a stroke crossing the diagonal widens like a broad nib's. A
// small drawing takes one 1.8-unit stroke, its heavy strokes 2.5 units.
export const NIB = {
jitter : { baseFrequency: 0.7, numOctaves: 2, scale: 0.35, seed: 4, seedStep: 17 },
large : [-0.55, -0.28, 0, 0.28, 0.55],
sizes : { large: 22 },
small : [-0.6, -0.3, 0, 0.3, 0.6],
stroke : { heavy: 2.5, nib: 0.62, small: 1.8 }
} as const
// Sets the round, unfilled stroke every drawing takes in the ink color.
export const STROKE = {
'fill' : 'none',
'stroke' : 'currentColor',
'stroke-linecap' : 'round',
'stroke-linejoin' : 'round'
} as const
type NibSize = 'large' | 'small'
// Returns the move of one nib copy along the diagonal, inside a drawing scaled
// by `fit` so the offset stays in grid units.
export function diagonal(fit: Fit, offset: number): string {
return `translate(${perScale(fit, offset)} ${perScale(fit, -offset)})`
}
// Scales `drawing` into the badge box `fit` sets, stroking it `units` wide at
// that scale.
export function fitted(fit: Fit, units: number, drawing: VNodeChild): VNode {
return h('g', { transform: fitTransform(fit) }, [h('g', { ...STROKE, 'stroke-width': perScale(fit, units) }, [drawing])])
}
export function fitTransform(fit: Fit): string {
return `translate(${fit.x} ${fit.y}) scale(${fit.scale})`
}
// Writes the markup `NibBadge` renders, for the inert HTML a loader or a
// markdown rule emits where no component mounts.
export function nibBadgeHtml(emblem: Emblem, px: number, label?: string): string {
const a11y = label ? `role="img" aria-label="${label}"` : 'aria-hidden="true"'
return `<svg class="nib-badge" width="${px}" height="${px}" viewBox="0 0 24 24" ${a11y}>`
+ `<use href="#${nibId(emblem.motif, nibSize(px))}"></use></svg>`
}
// Names each element the sprite declares for a motif, the two symbols a badge
// uses, the paths the nib copies repeat, and the filter that roughens them.
export function nibId(motif: Motif, part: 'jitter' | 'paths' | NibSize): string {
return `nib-${motif.label.toLowerCase()}-${part}`
}
export function nibSize(px: number): NibSize {
return px < NIB.sizes.large ? 'small' : 'large'
}
// Divides a length in grid units by the drawing's scale, so a stroke or an
// offset keeps its weight on the grid however far `fit` scales the drawing.
export function perScale(fit: Fit, units: number): number {
return Number((units / fit.scale).toFixed(4))
}
NibBadge
Draws one emblem from the sprite the page carries, hidden from assistive technology unless it takes a label.
import { computed, defineComponent } from 'vue'
import type { PropType } from 'vue'
import type { Emblem } from '../../lib/shared/emblems'
import { nibId, nibSize } from './nib'
// Draws an emblem's nib from the sprite, labeled as an image where `label` is
// set and hidden from assistive technology where it is not.
export const NibBadge = defineComponent({
name : 'NibBadge',
props : {
emblem : { required: true, type: Object as PropType<Emblem> },
label : String,
size : { required: true, type: Number }
},
setup(props) {
const href = computed(() => `#${nibId(props.emblem.motif, nibSize(props.size))}`)
return () => (
<svg
class="nib-badge"
width={props.size}
height={props.size}
viewBox="0 0 24 24"
role={props.label ? 'img' : undefined}
aria-label={props.label}
aria-hidden={props.label ? undefined : 'true'}
><use href={href.value} /></svg>
)
}
})
NibSprite
Holds the drawing of every emblem in one hidden block the layout mounts once, which each badge on the page reads.
import { defineComponent } from 'vue'
import { MOTIFS, strokesOf } from '../../lib/shared/emblems'
import type { Fit } from '../../lib/shared/emblems'
import * as nib from './nib'
const paths = (drawn: readonly string[]) => drawn.map(d => <path d={d} key={d} />)
const offsets = (fit: Fit, drawn: string, placed: readonly number[]) => placed.map(offset => (
<use href={`#${drawn}`} key={offset} transform={nib.diagonal(fit, offset)} />
))
// Declares every motif's paths, jitter filter, and sized symbols once per
// page, for each `NibBadge` to reference.
export const NibSprite = defineComponent({
name : 'NibSprite',
setup() {
return () => (
<svg aria-hidden="true" class="absolute size-0 overflow-hidden" focusable="false">
<defs>
{MOTIFS.flatMap((motif, at) => {
const drawn = nib.nibId(motif, 'paths')
const jitter = nib.nibId(motif, 'jitter')
return [
<g id={drawn} key={drawn}>{paths(strokesOf(motif))}</g>,
<filter height="140%" id={jitter} key={jitter} width="140%" x="-20%" y="-20%">
<feTurbulence
baseFrequency={nib.NIB.jitter.baseFrequency}
numOctaves={nib.NIB.jitter.numOctaves}
result="noise"
seed={nib.NIB.jitter.seed + at * nib.NIB.jitter.seedStep}
type="fractalNoise"
/>
<feDisplacementMap
in="SourceGraphic"
in2="noise"
scale={nib.NIB.jitter.scale}
xChannelSelector="R"
yChannelSelector="G"
/>
</filter>,
<symbol id={nib.nibId(motif, 'small')} key={`${drawn}-small`} overflow="visible" viewBox="0 0 24 24">
{motif.small
? nib.fitted(motif.small.fit, nib.NIB.stroke.small, [
paths(motif.small.lines),
motif.small.heavy?.map(d => (
<path d={d} key={d} stroke-width={nib.perScale(motif.small!.fit, nib.NIB.stroke.heavy)} />
)),
motif.small.dots?.map(([cx, cy, r]) => (
<circle cx={cx} cy={cy} fill="currentColor" key={`${cx} ${cy}`} r={r} stroke="none" />
))
])
: nib.fitted(motif.fit, nib.NIB.stroke.nib, offsets(motif.fit, drawn, nib.NIB.small))}
</symbol>,
<symbol id={nib.nibId(motif, 'large')} key={`${drawn}-large`} overflow="visible" viewBox="0 0 24 24">
<g filter={`url(#${jitter})`}>
{nib.fitted(motif.fit, nib.NIB.stroke.nib, offsets(motif.fit, drawn, nib.NIB.large))}
</g>
</symbol>
]
})}
</defs>
</svg>
)
}
})
paint
Reads the timing a stylesheet declares and waits on the next paint, for a script that moves in step with a transition.
200// Reads a custom property `tokens.css` declares off the root element, which is
// empty where the property is absent.
const rootProperty = (name: string): string =>
getComputedStyle(document.documentElement).getPropertyValue(name).trim()
// Reads a CSS time such as `0.4s` or `400ms`, or the first of a list of them,
// as milliseconds.
export function millis(time: string): number {
return parseFloat(time) * (time.split(',')[0]!.trim().endsWith('ms') ? 1 : 1000)
}
// Resolves two frames later, after the browser has painted the current
// DOM, so a class re-added on the next line fires its transition rather
// than batching away with the removal.
export function nextPaint(): Promise<void> {
return new Promise(resolve => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
})
}
// Reads the curve a card's morph eases on.
export function morphEase(): string {
return rootProperty('--prose-ease-morph')
}
// Reports whether the reader has set the device to reduce motion.
export function reducesMotion(win: Window = window): boolean {
return win.matchMedia('(prefers-reduced-motion: reduce)').matches
}
// Reads the squiggle-draw duration, returning 0 where the custom property is
// absent.
export function ruleDrawMs(): number {
return Number(rootProperty('--prose-rule-draw-ms'))
}
// Writes `place` onto `el` with its transition dropped for that one write
// where `snap` is set, through `data-snap`, so the element appears in place
// rather than traveling there.
export function snapInPlace(el: HTMLElement, snap: boolean, place: () => void): void {
if (snap) el.dataset.snap = ''
place()
if (!snap) return
el.getBoundingClientRect()
delete el.dataset.snap
}
PermalinkAnchor
Renders the link to a heading that the page styles beside each heading, named for the heading it opens.
kit
import { defineComponent } from 'vue'
// Renders the permalink VitePress styles beside a heading.
export const PermalinkAnchor = defineComponent({
name : 'PermalinkAnchor',
props : {
anchor : { required: true, type: String },
label : { required: true, type: String }
},
setup(props) {
return () => <a class="header-anchor" href={`#${props.anchor}`} aria-label={`Permalink to “${props.label}”`}>{''}</a>
}
})
Popup
Opens a card against a trigger on a click, a tap, or a key press and takes focus into it, or against an element the caller names where one listener serves many anchors, passively where the card follows a hover.
import { whenever } from '@vueuse/core'
import * as popover from '@zag-js/popover'
import { mergeProps, normalizeProps, useMachine } from '@zag-js/vue'
import type { PropTypes } from '@zag-js/vue'
import { computed, defineComponent, h, ref, Teleport, Transition, useId, watch } from 'vue'
import type { PropType, SlotsType } from 'vue'
type Placement = NonNullable<NonNullable<popover.Props['positioning']>['placement']>
export interface PopupTriggerScope {
props : PropTypes['element']
}
// Clicks a trigger that is not a native button from the keys a button takes.
function pressTrigger(event: KeyboardEvent): void {
if (event.key !== 'Enter' && event.key !== ' ') return
event.preventDefault()
;(event.currentTarget as HTMLElement).click()
}
// Shows a card through the `popover` machine, teleported to the body once it
// first opens. The `trigger` slot binds the element a click, a tap, Enter, or
// Space toggles it from, focus moves into the card on opening, and Escape
// closes it and returns focus to the trigger. A caller delegating its own
// events passes `open` and the `anchor` element the card points at, and hears
// each dismissal through `dismiss`, whereas `passive` leaves focus where it is
// for a card that follows a hover.
export const Popup = defineComponent({
name : 'Popup',
inheritAttrs : false,
props : {
anchor : { default: undefined, type: Object as PropType<HTMLElement | null> },
gutter : { default: 8, type: Number },
label : { required: true, type: String },
open : { default: undefined, type: Boolean },
overflowPadding : { default: 8, type: Number },
passive : { default: false, type: Boolean },
placement : { default: 'bottom-start', type: String as PropType<Placement> },
theme : { required: true, type: String }
},
emits : ['dismiss'],
slots : Object as SlotsType<{ default: Record<string, never>, trigger: PopupTriggerScope }>,
setup(props, { attrs, emit, slots }) {
const id = useId()
const anchorId = `popover:${id}:anchor-element`
const service = useMachine(popover.machine, computed(() => ({
autoFocus : !props.passive,
finalFocusEl : () => props.anchor ?? null,
id,
ids : props.anchor === undefined || props.passive ? undefined : { trigger: anchorId },
onOpenChange : ({ open }: popover.OpenChangeDetails) => { if (!open) emit('dismiss') },
open : props.open,
positioning : {
getAnchorRect : props.anchor === undefined ? undefined : () => props.anchor?.getBoundingClientRect() ?? null,
gutter : props.gutter,
overflowPadding : props.overflowPadding,
placement : props.placement
},
restoreFocus : !props.passive
})))
const api = computed(() => popover.connect(service, normalizeProps))
const shown = computed(() => props.open ?? api.value.open)
const opened = ref(false)
whenever(shown, () => { opened.value = true }, { flush: 'sync', immediate: true })
watch(() => props.anchor, () => api.value.reposition())
// Names the anchor as the machine's trigger, which takes Tab out of the card
// to the tabbable after the anchor and leaves a press on the anchor to `toggle`.
watch(() => props.passive ? null : props.anchor, (anchor, previous) => {
previous?.removeAttribute('id')
anchor?.setAttribute('id', anchorId)
}, { flush: 'sync' })
return () => {
const { 'aria-labelledby': _named, hidden: _hidden, ...content } = api.value.getContentProps()
const { type: _type, ...trigger } = api.value.getTriggerProps()
return [
slots.trigger?.({ props: { ...trigger, onKeydown: pressTrigger, role: 'button' } }),
opened.value && h(Teleport, { to: 'body' }, [
<div {...mergeProps(api.value.getPositionerProps(), attrs)} data-popup={props.theme}>
<Transition
enterActiveClass="duration-140 ease-emphasized transition-translate-and-opacity motion-reduce:transition-none"
enterFromClass="-translate-y-4 opacity-0"
leaveActiveClass="duration-140 ease-emphasized transition-translate-and-opacity motion-reduce:transition-none"
leaveToClass="-translate-y-4 opacity-0"
>
{{
default: () => (
shown.value && (
<div {...content} aria-label={props.label} class="z-10000">
{slots.default?.({})}
<div {...api.value.getArrowProps()}><div {...api.value.getArrowTipProps()} /></div>
</div>
)
)
}}
</Transition>
</div>
])
]
}
}
})
ScrollRegion
Gives an element that scrolls a tab stop, so a keyboard scrolls it at any width.
prose --check src/
import { defineComponent, h } from 'vue'
import type { PropType } from 'vue'
import { SCROLL_STOP } from '../../lib/shared/constants'
// Renders an element that scrolls with a tab stop of its own, so a keyboard
// scrolls it whether or not its content overflows at the width the page loads at.
export const ScrollRegion = defineComponent({
name : 'ScrollRegion',
props : {
as : { default: 'div', type: String as PropType<'aside' | 'div' | 'pre' | 'table'> },
html : { default: undefined, type: String }
},
setup(props, { slots }) {
const attrs = { ...SCROLL_STOP, class: 'focus-visible:focus-ring focus-visible:-outline-offset-1' }
return () => props.html === undefined
? h(props.as, attrs, slots.default?.())
: h(props.as, { ...attrs, innerHTML: props.html })
}
})
Slider
Binds one thumb to a value on a track the caller draws, so several thumbs can share one track.
import * as slider from '@zag-js/slider'
import { normalizeProps, useMachine } from '@zag-js/vue'
import type { PropTypes } from '@zag-js/vue'
import { computed, defineComponent, useId } from 'vue'
import type { SlotsType } from 'vue'
export interface SliderScope {
thumb : Omit<PropTypes['element'], 'aria-labelledby' | 'style'>
}
// Binds one thumb to the `slider` machine against the track element `control`
// names, so thumbs on one track hold independent values and may cross. The
// slot places the thumb, and a press that moves it reports through `change`
// before `commit` reports the release.
export const Slider = defineComponent({
name : 'Slider',
props : {
control : { required: true, type: String },
label : { required: true, type: String },
max : { required: true, type: Number },
min : { required: true, type: Number },
modelValue : { required: true, type: Number }
},
emits : {
change : (value: number) => typeof value === 'number',
commit : () => true
},
slots : Object as SlotsType<{ default: SliderScope }>,
setup(props, { emit, slots }) {
const id = useId()
const service = useMachine(slider.machine, computed(() => ({
'aria-label' : [props.label],
id,
ids : { control: props.control },
max : props.max,
min : props.min,
onValueChange : ({ value }: slider.ValueChangeDetails) => emit('change', value[0]!),
onValueChangeEnd : () => emit('commit'),
thumbAlignment : 'center' as const,
value : [props.modelValue]
})))
const api = computed(() => slider.connect(service, normalizeProps))
return () => {
const { 'aria-labelledby': _labelledBy, style: _style, ...thumb } = api.value.getThumbProps({ index: 0 })
return slots.default({ thumb })
}
}
})
Tabs
Selects one panel from a tab list on a click, a hover, or a focus, leaving its markup to the caller.
prose format
prose check
import * as tabs from '@zag-js/tabs'
import { mergeProps, normalizeProps, useMachine } from '@zag-js/vue'
import type { PropTypes } from '@zag-js/vue'
import { computed, defineComponent, useId } from 'vue'
import type { PropType, PublicProps, SlotsType, VNodeChild } from 'vue'
type Orientation = NonNullable<tabs.Props['orientation']>
interface TabsProps<T extends string> extends PublicProps {
label : string
modelValue : T
'onUpdate:modelValue'?: (value: T) => void
orientation ?: Orientation
}
export interface TabsScope<T extends string> {
content : (value: T) => PropTypes['element']
list : PropTypes['element']
trigger : (value: T) => PropTypes['button']
}
type GenericTabs = new <T extends string>(props: TabsProps<T>) => {
$props : TabsProps<T>
$slots : { default: (scope: TabsScope<T>) => VNodeChild }
}
// Binds a tab list through the `tabs` machine, leaving its markup to the slot,
// whose triggers each select on click, on hover, and on focus.
export const Tabs = defineComponent({
name : 'Tabs',
props : {
label : { required: true, type: String },
modelValue : { required: true, type: String },
orientation : String as PropType<Orientation>
},
emits : { 'update:modelValue': (value: string) => typeof value === 'string' },
slots : Object as SlotsType<{ default: TabsScope<string> }>,
setup(props, { emit, slots }) {
const id = useId()
const service = useMachine(tabs.machine, computed(() => ({
id,
onValueChange : ({ value }: tabs.ValueChangeDetails) => emit('update:modelValue', value),
orientation : props.orientation,
translations : { listLabel: props.label },
value : props.modelValue
})))
const api = computed(() => tabs.connect(service, normalizeProps))
return () => slots.default({
content : value => api.value.getContentProps({ value }),
list : api.value.getListProps(),
trigger : value => {
const select = (): void => api.value.setValue(value)
return mergeProps(api.value.getTriggerProps({ value }), { onFocus: select, onMouseenter: select })
}
})
}
}) as unknown as GenericTabs
Tool
Links to a tool by its registry slug, drawing its icon beside its name.
import { computed, defineComponent } from 'vue'
import { externalAttrs } from '../../lib/shared/links'
import { lookup } from '../../lib/shared/lookup'
import { data as tools } from '../../lib/shared/tools.data'
import { ToolIcon } from './ToolIcon'
// Links to a tool by its registry slug, drawing its icon beside its name.
export const Tool = defineComponent({
name : 'Tool',
props : {
slug : { required: true, type: String }
},
setup(props) {
const entry = computed(() => lookup(tools.entries, props.slug, 'Tool'))
return () => (
<a class="tool-mark" href={entry.value.href} title={entry.value.name} {...externalAttrs(entry.value.href)}>
<code><ToolIcon class="mr-3 inline-block size-0-78em align-sub-0-08em" slug={props.slug} />{entry.value.name}</code>
</a>
)
}
})
ToolIcon
Draws a tool icon alone by its registry slug, hidden from assistive technology.
import { computed, defineComponent } from 'vue'
import { lookup } from '../../lib/shared/lookup'
import { data as tools } from '../../lib/shared/tools.data'
// Draws a tool's icon alone by its registry slug, hidden from assistive technology.
export const ToolIcon = defineComponent({
name : 'ToolIcon',
props : {
slug : { required: true, type: String }
},
setup(props) {
const icon = computed(() => lookup(tools.entries, props.slug, 'ToolIcon').icon)
return () => <svg aria-hidden="true" innerHTML={icon.value.body} viewBox={icon.value.viewBox} />
}
})