Sections & blocks›Figure

core

Figure

A captioned container for images, code, tables and diagrams, with sizing and alignment

Source

import Markdoc from '@markdoc/markdoc';
const { Tag } = Markdoc;
import {
	createContentModelSchema,
	bodyOnly,
	createComponentRenderable,
	renderNodes,
} from '../lib/index.js';
import { isMediaNode } from './common.js';

const sizeValues = ['small', 'medium', 'large', 'full'] as const;
const alignValues = ['left', 'center', 'right'] as const;

export const figureSections = { caption: 'description' } as const;
export const figureFrameTarget = 'self' as const;

export const figureSchema = {
	byField: 'body',
	rows: { mixed: {} },
	fallback: {
		type: 'ImageObject',
		properties: { image: 'contentUrl', caption: 'caption' },
	},
} as const;

export const figure = createContentModelSchema({
	schema: figureSchema,
	sections: figureSections,
	frameTarget: figureFrameTarget,
	attributes: {
		size: {
			type: String,
			required: false,
			matches: sizeValues.slice(),
			description: 'Display width of the figure',
		},
		align: {
			type: String,
			required: false,
			matches: alignValues.slice(),
			description: 'Horizontal alignment of the figure',
		},
		caption: {
			type: String,
			required: false,
			description: 'Caption text displayed below the figure',
		},
	},
	contentModel: bodyOnly(),
	transform(resolved, attrs, config) {
		const children = renderNodes(resolved.body, config).toArray();

		const mediaOnly = (p: any): any[] | undefined => {
			if (!Markdoc.Tag.isTag(p) || p.name !== 'p') return undefined;
			const kids = p.children ?? [];
			const media = kids.filter((c: any) => isMediaNode(c));
			const rest = kids.filter(
				(c: any) => !isMediaNode(c) && !(typeof c === 'string' && c.trim() === ''),
			);
			return media.length > 0 && rest.length === 0 ? media : undefined;
		};
		const holdsMedia = (n: any): boolean =>
			isMediaNode(n) || (Markdoc.Tag.isTag(n) && (n.children ?? []).some(holdsMedia));

		const captionContent = attrs.caption || undefined;
		const captionParagraph = captionContent
			? undefined
			: children.find((n: any) => Markdoc.Tag.isTag(n) && n.name === 'p' && !holdsMedia(n));
		const captionTag = captionContent
			? new Tag('figcaption', {}, [captionContent])
			: captionParagraph
				? new Tag('figcaption', {}, [captionParagraph])
				: undefined;

		const imgs: InstanceType<typeof Tag>[] = [];
		const body: any[] = [];
		let mixed = false;
		for (const node of children) {
			if (node === captionParagraph) continue;
			if (isMediaNode(node)) {
				imgs.push(node as InstanceType<typeof Tag>);
				body.push(node);
				continue;
			}
			const media = mediaOnly(node);
			if (media) {
				imgs.push(...media);
				body.push(...media);
				continue;
			}
			if (typeof node === 'string' && node.trim() === '') continue;
			body.push(node);
			mixed = true;
		}

		const sizeMeta = attrs.size ? new Tag('meta', { content: attrs.size }) : undefined;
		const alignMeta = attrs.align ? new Tag('meta', { content: attrs.align }) : undefined;
		const bodyMeta = mixed ? new Tag('meta', { content: 'mixed' }) : undefined;
		const childNodes: any[] = [...body];
		if (bodyMeta) childNodes.push(bodyMeta);
		if (captionTag) childNodes.push(captionTag);

		return createComponentRenderable({
			rune: 'figure',
			tag: 'figure',
			properties: {
				size: sizeMeta,
				align: alignMeta,
				body: bodyMeta,
			},
			refs: {
				caption: captionTag,
				...(imgs.length > 0 ? { image: imgs[0] } : {}),
			},
			children: childNodes,
		});
	},
});

View packages/runes/src/tags/figure.ts on GitHub

A captioned container. A figure holds an image most often, but it accepts any block content (a code block, a table, a diagram, another rune) and captions it, with sizing and alignment controls. To set an image beside a passage of text, use mediatext; to present a screenshot or product shot in a framed viewport with decorative chrome, use showcase.

How Markdown is read

Everything in the body is kept, in the order you wrote it.

You writeIt becomes
An image, a video, or a placeholder: / icon: imageThe figure's media; an image in a paragraph of its own is unwrapped, so it sits directly in the figure
The first paragraph that holds no image, when caption is not setThe caption, shown last, below the content
Anything else (a code block, a table, a list, a nested rune, another paragraph)Kept as written

With caption attribute

Set the caption directly on the rune.

{% figure caption="A coral reef teeming with life beneath turquoise waters" size="large" align="center" %}
![Coral reef](https://assets.refrakt.md/figure-coral-reef.jpg)
{% /figure %}
<figure data-rune="figure" data-rune-fields="{&quot;size&quot;:&quot;large&quot;,&quot;align&quot;:&quot;center&quot;}" typeof="ImageObject">
  <img src="https://assets.refrakt.md/figure-coral-reef.jpg" alt="Coral reef" data-name="image" property="contentUrl">
  <figcaption data-name="caption" property="caption">A coral reef teeming with life beneath turquoise waters</figcaption>
</figure>
Coral reef
A coral reef teeming with life beneath turquoise waters
<figure class="rf-figure rf-figure--large rf-figure--center" typeof="ImageObject" data-size="large" data-align="center" data-elevation="flat" data-rune="figure" data-density="compact">
  <img src="https://assets.refrakt.md/figure-coral-reef.jpg" alt="Coral reef" data-name="image" property="contentUrl" class="rf-figure__image" />
  <figcaption data-name="caption" property="caption" class="rf-figure__caption" data-section="description">A coral reef teeming with life beneath turquoise waters</figcaption>
</figure>

With paragraph caption

If no caption attribute is provided, the first paragraph inside the rune is used as the caption.

{% figure size="medium" %}
![Hot springs](https://assets.refrakt.md/figure-hot-springs.jpg)

Steam rising from volcanic hot springs in the Icelandic highlands.
{% /figure %}
<figure data-rune="figure" data-rune-fields="{&quot;size&quot;:&quot;medium&quot;}" typeof="ImageObject">
  <img src="https://assets.refrakt.md/figure-hot-springs.jpg" alt="Hot springs" data-name="image" property="contentUrl">
  <figcaption data-name="caption" property="caption">
    <p>Steam rising from volcanic hot springs in the Icelandic highlands.</p>
  </figcaption>
</figure>
Hot springs

Steam rising from volcanic hot springs in the Icelandic highlands.

<figure class="rf-figure rf-figure--medium rf-figure--center" typeof="ImageObject" data-size="medium" data-align="center" data-elevation="flat" data-rune="figure" data-density="compact">
  <img src="https://assets.refrakt.md/figure-hot-springs.jpg" alt="Hot springs" data-name="image" property="contentUrl" class="rf-figure__image" />
  <figcaption data-name="caption" property="caption" class="rf-figure__caption" data-section="description">
    <p>Steam rising from volcanic hot springs in the Icelandic highlands.</p>
  </figcaption>
</figure>

Captioning code, tables and diagrams

A figure captions whatever it holds. Use it to caption a code block, a snippet, a table, or a diagram.

{% figure caption="The request handler and its retry policy" %}
```ts
export async function handler(req: Request) {
	return fetch(req, { retry: 3 });
}
```

| Option  | Default |
|---------|---------|
| `retry` | `3`     |
{% /figure %}
<figure data-rune="figure" data-rune-fields="{&quot;body&quot;:&quot;mixed&quot;}">
  <div class="rf-codeblock">
    <pre data-language="ts">
      <code data-language="ts">export async function handler(req: Request) {
	return fetch(req, { retry: 3 });
}
</code>
    </pre>
  </div>
  <div class="rf-table-wrapper">
    <table>
      <thead>
        <tr>
          <th>Option</th>
          <th>Default</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            <code>retry</code>
          </td>
          <td>
            <code>3</code>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
  <figcaption data-name="caption">The request handler and its retry policy</figcaption>
</figure>
export async function handler(req: Request) {
	return fetch(req, { retry: 3 });
}
OptionDefault
retry3
The request handler and its retry policy
<figure class="rf-figure rf-figure--default rf-figure--center" data-size="default" data-align="center" data-elevation="flat" data-rune="figure" data-density="compact">
  <div class="rf-codeblock">
    <pre data-language="ts"><code data-language="ts">export async function handler(req: Request) {
	return fetch(req, { retry: 3 });
}
</code></pre>
  </div>
  <div class="rf-table-wrapper">
    <table>
      <thead>
        <tr>
          <th>Option</th>
          <th>Default</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            <code>retry</code>
          </td>
          <td>
            <code>3</code>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
  <figcaption data-name="caption" class="rf-figure__caption" data-section="description">The request handler and its retry policy</figcaption>
</figure>

Codegroup is the other way to label code: it puts a title bar above the block, where figure puts a caption below it. Use codegroup when the label is a filename and figure when it describes what the reader is looking at.

Structured data

A figure whose body is only media publishes an ImageObject, with the image as contentUrl and the caption as caption. Once it holds anything else, it publishes no schema.org type at all: its caption then describes more than the image, so calling the figure an ImageObject would be a false claim. refrakt inspect figure shows the row, and the selection rule as by field body.

Elevation & frame

A figure is a frame around its image, so it sets frameTarget: "self" (surface model): frame chrome lands on the figure itself. elevation floats the figure as a box (box-shadow); frame-shadow is the image's silhouette drop-shadow; frame-aspect crops it to a ratio.

{% figure elevation="floating" frame-aspect="4/3" caption="Framed at 4/3 with a lifted figure" %}
![Coral reef](https://assets.refrakt.md/figure-coral-reef.jpg)
{% /figure %}
<figure data-rune="figure" typeof="ImageObject" elevation="floating">
  <img src="https://assets.refrakt.md/figure-coral-reef.jpg" alt="Coral reef" data-name="image" property="contentUrl">
  <figcaption data-name="caption" property="caption">Framed at 4/3 with a lifted figure</figcaption>
  <meta data-field="frame-aspect" content="4/3">
</figure>
Coral reef
Framed at 4/3 with a lifted figure
<figure class="rf-figure rf-figure--default rf-figure--center" typeof="ImageObject" data-size="default" data-align="center" data-elevation="floating" data-rune="figure" data-density="compact" style="--frame-aspect: 4/3">
  <img src="https://assets.refrakt.md/figure-coral-reef.jpg" alt="Coral reef" data-name="image" property="contentUrl" class="rf-figure__image" />
  <figcaption data-name="caption" property="caption" class="rf-figure__caption" data-section="description">Framed at 4/3 with a lifted figure</figcaption>
</figure>

Attributes

AttributeTypeRequiredDescription
size"small" | "medium" | "large" | "full"—Display width of the figure
align"left" | "center" | "right"—Horizontal alignment of the figure
captionstring—Caption text displayed below the figure

Universal attributes

bg

The background layer: image, video, gradient, flat overlay wash and legibility scrim, in a single injected layer behind the rune's content.

AttributeTypeRequiredDescription
bgstring—Background preset applied to this block
bg-fromstring—Gradient start colour — a semantic token name (→ var(--rf-color-*))
bg-gradient"to-t" | "to-b" | "to-l" | "to-r" | "to-tr" | "to-br" | "to-bl" | "to-tl"—Gradient direction (bounded named set)
bg-gradient-type"linear" | "radial" | "conic"—Gradient type
bg-tostring—Gradient end colour — a semantic token name
bg-viastring—Optional middle gradient stop — a semantic token name
scrim"top" | "bottom" | "left" | "right" | "none"—Scrim direction (heaviest edge); presence turns the scrim on, "none" opts out of the default cover scrim
scrim-blur"none" | "sm" | "md" | "lg"—Frost scrim blur amount
scrim-strength"sm" | "md" | "lg"—Gradient scrim strength
scrim-tone"dark" | "light"—Whether the scrim darkens (for light text) or lightens (for dark text)
scrim-type"gradient" | "frost"—Scrim treatment: gradient (default) or frost (backdrop blur)
elevation

How far the rune sits off the page, from sunken to overlay. The theme decides what each step looks like.

AttributeTypeRequiredDescription
elevation"sunken" | "flush" | "flat" | "raised" | "floating" | "overlay" | "none" | "sm" | "md" | "lg"—Surface depth, from sunken to overlay. Deprecated: none, sm, md and lg (read as flat, raised, raised and floating)
frame

Surface chrome: a named preset from the theme registry with inline `frame-*` overrides layered on top.

AttributeTypeRequiredDescription
framestring—Named frame preset presenting this block's media surface
frame-anchorstring—Crop focal point when the guest is cut (object-position)
frame-aspectstring—Aspect ratio of the framed media, e.g. "16/9"
frame-displace"top" | "bottom" | "end" | "bottom-end" | "top-end" | "both"—Edge/corner the framed guest moves toward
frame-displace-mode"peek" | "bleed"—How displacement renders: `peek` (default) translates the guest visually inside its frame target; `bleed` uses negative margin on the media zone so following layout pulls up — extends past a section like a hero without leaving a gap above
frame-offset"none" | "sm" | "md" | "lg" | "xl" | "2xl" | "3xl" | "4xl"—Displacement distance (non-linear named scale: sm…xl ride the block-spacing tokens, 2xl/3xl/4xl step up to section-spacing for bleed-mode displacements that clear a section edge)
frame-overflow"clip" | "bleed"—How the frame handles a guest whose content is wider than it: `clip` (default) keeps it inside the rounded frame; `bleed` runs an overflowing guest out to the layout edge on a narrow viewport so it reads as cropped by the screen (a bleed host only — hero/feature)
frame-oversizestring—How far the guest exceeds its slot (scale factor)
frame-placestring—Guest-box alignment in the slot (e.g. "left top")
frame-shadow"none" | "sm" | "md" | "lg"—Silhouette drop-shadow strength for the framed media
inset

Internal padding override.

AttributeTypeRequiredDescription
inset"flush" | "tight" | "default" | "loose" | "breathe"—Inner padding of this block
motion

Scroll-reveal entrance. You choose its character; the theme decides how it moves.

AttributeTypeRequiredDescription
reveal"none" | "fade" | "slide" | "scale" | "blur"—Scroll-reveal entrance character (none|fade|slide|scale|blur); the theme owns the choreography
staggerboolean—Cascade this block's items in as it reveals (no-op on single-child runes)
prominence

Header emphasis. Scales a rune's header, or its featured quotation; the theme decides the type size for each step.

AttributeTypeRequiredDescription
prominence"quiet" | "normal" | "prominent" | "display" | "marquee"—Emphasis of a page-section header or a featured quotation (only on runes that have one)
spacing

Block-level rhythm override.

AttributeTypeRequiredDescription
spacing"flush" | "tight" | "default" | "loose" | "breathe"—Vertical spacing above and below this block
substrate

Generated pattern fills behind the content, drawn by the theme.

AttributeTypeRequiredDescription
substrate"dots" | "grid" | "lines" | "cross" | "checker" | "none"—Generated surface pattern
substrate-fill"inherit" | "inset"—Surface fill the pattern sits on (full colour stays with tint)
substrate-opacity"sm" | "md" | "lg"—Pattern ink strength
substrate-size"sm" | "md" | "lg"—Pattern cell size
substrate-target"self" | "media"—Which surface the pattern fills (overrides the rune/theme default)
tint

Per-rune colour override: a named tint from the theme registry, with inline per-token overrides layered on top.

AttributeTypeRequiredDescription
tintstring—Color tint preset applied to this block
tint-mode"auto" | "dark" | "light"—Whether the tint adapts to auto, dark, or light mode
width

The track a block rune occupies.

AttributeTypeRequiredDescription
width"compact" | "narrow" | "content" | "wide" | "full"—Maximum width constraint for this block
Not availableWhy
dropcap, readingthis rune declares no prose body