Sections & blocks›Embed

core

Embed

Embed external content like videos, tweets, and code demos

Source

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

const aspectType = ['16:9', '4:3', '1:1', 'auto'] as const;

interface ProviderInfo {
	provider: string;
	embedUrl: string;
	type: string;
}

function detectProvider(url: string): ProviderInfo {
	try {
		const parsed = new URL(url);
		const host = parsed.hostname.replace('www.', '');

		if (host === 'youtube.com' || host === 'youtu.be') {
			let videoId = '';
			if (host === 'youtu.be') {
				videoId = parsed.pathname.slice(1);
			} else {
				videoId = parsed.searchParams.get('v') || '';
			}
			return {
				provider: 'youtube',
				embedUrl: videoId ? `https://www.youtube-nocookie.com/embed/${videoId}` : url,
				type: 'video',
			};
		}

		if (host === 'vimeo.com') {
			const videoId = parsed.pathname.slice(1);
			return {
				provider: 'vimeo',
				embedUrl: `https://player.vimeo.com/video/${videoId}`,
				type: 'video',
			};
		}

		if (host === 'twitter.com' || host === 'x.com') {
			return {
				provider: 'twitter',
				embedUrl: url,
				type: 'tweet',
			};
		}

		if (host === 'codepen.io') {
			const embedUrl = url.replace('/pen/', '/embed/');
			return {
				provider: 'codepen',
				embedUrl,
				type: 'codepen',
			};
		}

		if (host === 'open.spotify.com') {
			const embedUrl = url.replace('open.spotify.com/', 'open.spotify.com/embed/');
			return {
				provider: 'spotify',
				embedUrl,
				type: 'spotify',
			};
		}
	} catch {
		// Invalid URL — fall through to generic
	}

	return {
		provider: 'generic',
		embedUrl: url,
		type: 'generic',
	};
}

export const embedSchema = {
	type: 'VideoObject',
	properties: { title: 'name', url: 'contentUrl', embedUrl: 'embedUrl' },
} as const;

export const embed = createContentModelSchema({
	schema: embedSchema,
	attributes: {
		url: { type: String, required: true, description: 'URL of the content to embed' },
		type: { type: String, required: false, description: 'Override auto-detected embed type' },
		aspect: {
			type: String,
			required: false,
			matches: aspectType.slice(),
			description: 'Aspect ratio of the embed frame',
		},
		title: { type: String, required: false, description: 'Accessible title for the embed iframe' },
	},
	contentModel: {
		type: 'sequence',
		fields: [{ name: 'fallback', match: 'any', optional: true, greedy: true }],
	},
	transform(resolved, attrs, config) {
		const url = attrs.url ?? '';
		const detected = detectProvider(url);
		const aspect = attrs.aspect ?? '16:9';
		const iframeTitle = (attrs.title as string) || 'Embedded content';

		const [w, h] = aspect.split(':').map(Number);
		const paddingPercent = h && w ? (h / w) * 100 : 56.25;

		const urlMeta = new Tag('meta', { content: url });
		const titleMeta = new Tag('meta', { content: attrs.title ?? '' });
		const embedUrlMeta = new Tag('meta', { content: detected.embedUrl });

		const providerMeta = new Tag('meta', { content: detected.provider });

		const fallback = renderNodes(resolved.fallback, config).wrap('div');
		const fallbackDiv = fallback.tag('div');

		const children: any[] = [];
		let wrapperDiv: InstanceType<typeof Tag> | undefined;
		if (detected.embedUrl) {
			const iframe = new Tag(
				'iframe',
				{
					src: detected.embedUrl,
					title: iframeTitle,
					frameborder: '0',
					allow:
						'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture',
					allowfullscreen: '',
					loading: 'lazy',
				},
				[],
			);
			wrapperDiv = new Tag('div', { style: `padding-bottom: ${paddingPercent}%` }, [iframe]);
			children.push(wrapperDiv);
		}
		children.push(fallback.next());

		return createComponentRenderable({
			rune: 'embed',
			tag: 'figure',
			properties: {
				provider: providerMeta,
				title: titleMeta,
				url: urlMeta,
				embedUrl: embedUrlMeta,
			},
			refs: {
				wrapper: wrapperDiv,
				fallback: fallbackDiv,
			},
			children,
		});
	},
});

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

Embed external content from popular platforms. URLs are automatically detected and converted to the appropriate embed format. Supports YouTube, Vimeo, Twitter/X, CodePen, and Spotify.

Basic usage

Pass a URL and optional title to embed content from a supported provider.

{% embed url="https://www.youtube.com/watch?v=dQw4w9WgXcQ" title="Example video" /%}
<figure data-rune="embed" data-rune-fields="{&quot;provider&quot;:&quot;youtube&quot;,&quot;title&quot;:&quot;Example video&quot;,&quot;url&quot;:&quot;https://www.youtube.com/watch?v=dQw4w9WgXcQ&quot;,&quot;embedUrl&quot;:&quot;https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ&quot;}" typeof="VideoObject">
  <div style="padding-bottom: 56.25%" data-name="wrapper">
    <iframe src="https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ" title="Example video" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" loading="lazy"></iframe>
  </div>
  <div data-name="fallback"></div>
  <meta property="name" content="Example video">
  <meta property="contentUrl" content="https://www.youtube.com/watch?v=dQw4w9WgXcQ">
  <meta property="embedUrl" content="https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ">
</figure>
<figure class="rf-embed" typeof="VideoObject" data-provider="youtube" data-elevation="flat" data-rune="embed" data-density="compact">
  <div style="padding-bottom: 56.25%" data-name="wrapper" class="rf-embed__wrapper">
    <iframe src="https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ" title="Example video" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" loading="lazy"></iframe>
  </div>
  <div data-name="fallback" class="rf-embed__fallback"></div>
  <meta property="name" content="Example video" />
  <meta property="contentUrl" content="https://www.youtube.com/watch?v=dQw4w9WgXcQ" />
  <meta property="embedUrl" content="https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ" />
</figure>

With fallback content

Children become fallback content displayed when the embed cannot load.

{% embed url="https://example.com/video" %}
Video could not be loaded. [Watch on the original site](https://example.com/video).
{% /embed %}
<figure data-rune="embed" data-rune-fields="{&quot;provider&quot;:&quot;generic&quot;,&quot;title&quot;:&quot;&quot;,&quot;url&quot;:&quot;https://example.com/video&quot;,&quot;embedUrl&quot;:&quot;https://example.com/video&quot;}" typeof="VideoObject">
  <div style="padding-bottom: 56.25%" data-name="wrapper">
    <iframe src="https://example.com/video" title="Embedded content" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" loading="lazy"></iframe>
  </div>
  <div data-name="fallback">
    <p>
      Video could not be loaded.
      <a href="https://example.com/video">Watch on the original site</a>
      .
    </p>
  </div>
  <meta property="contentUrl" content="https://example.com/video">
  <meta property="embedUrl" content="https://example.com/video">
</figure>

Video could not be loaded. Watch on the original site.

<figure class="rf-embed" typeof="VideoObject" data-provider="generic" data-elevation="flat" data-rune="embed" data-density="compact">
  <div style="padding-bottom: 56.25%" data-name="wrapper" class="rf-embed__wrapper">
    <iframe src="https://example.com/video" title="Embedded content" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" loading="lazy"></iframe>
  </div>
  <div data-name="fallback" class="rf-embed__fallback">
    <p>
      Video could not be loaded. 
      <a href="https://example.com/video">Watch on the original site</a>
      .
    </p>
  </div>
  <meta property="contentUrl" content="https://example.com/video" />
  <meta property="embedUrl" content="https://example.com/video" />
</figure>

Supported providers

ProviderExample URL
YouTubehttps://www.youtube.com/watch?v=... or https://youtu.be/...
Vimeohttps://vimeo.com/...
Twitter/Xhttps://twitter.com/.../status/...
CodePenhttps://codepen.io/.../pen/...
Spotifyhttps://open.spotify.com/...
GenericAny other URL (rendered as iframe)

Attributes

AttributeTypeRequiredDescription
urlstring✓URL of the content to embed
typestring—Override auto-detected embed type
aspect"16:9" | "4:3" | "1:1" | "auto"—Aspect ratio of the embed frame
titlestring—Accessible title for the embed iframe

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)
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)
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
framethis rune declares neither a `frameTarget` nor a media section
prominencethis rune has no page-section header or featured quotation