Skip to content

Portable Text

Sanity's Portable Text as HTML through astro-portabletext, with headings that carry ids, links, images and code blocks.

Native .astro · no React · MIT · free, no account

The reading room opens at nine on weekdays and at ten on Saturdays. Bring a pencil: pens stay in the lockers by the door.

Ordering items

Order up to five boxes a day in the online catalogue. They arrive at your desk within forty minutes.

Photographs

Phones are fine without flash. For prints, ask at the desk.

hours.ts
const opening = { weekdays: "09:00", saturday: "10:00" };

Getting here

Five minutes from the central station, by the canal.

Install

Terminal
npx shadcn@latest add https://www.themes.dev/astro/r/portable-text.json

The CLI needs a components.json (from npx shadcn init), which also writes the tokens these files use. It adds astro-portabletext. It also installs Table of contents, Code block, which it uses. No CLI? Copy the files below to the same paths.

Files

src/kit/components/PortableText.astroAstro
---// Sanity's Portable Text as HTML, through astro-portabletext (the renderer Sanity recommends for Astro), with our// parts for headings (with ids for <Toc>), links, images and code. Wrap it in <Prose> for the type.// <PortableText value={post.body} />// Images: the GROQ projection should give each image block { src, alt, width?, height? }, as the post model's query// does: body[]{ ..., _type == "image" => { "src": asset->url, alt, "width": asset->metadata.dimensions.width,// "height": asset->metadata.dimensions.height } }.import { PortableText as Render } from 'astro-portabletext';import Heading from './pt/Heading.astro';import Link from './pt/Link.astro';import PtImage from './pt/Image.astro';import PtCode from './pt/Code.astro'; interface Props {  value: unknown[];}const { value } = Astro.props;// One slug counter per render, shared with headingsFromPortableText() through the order of the blocks.(Astro.locals as Record<string, unknown>).kitSlugs = new Map<string, number>();--- <Render  value={value as never}  components={{    block: { h2: Heading, h3: Heading, h4: Heading },    mark: { link: Link },    type: { image: PtImage, code: PtCode },  }}/>
src/kit/components/pt/Heading.astroAstro
---// A Portable Text heading with an id, so <Toc> and shared links can point at it. Same slugs as// headingsFromPortableText(): the n-th "Pricing" on a page gets "pricing-n".import type { Block } from 'astro-portabletext/types';import { blockText, uniqueSlug } from '../../lib/headings'; interface Props {  node: Block;}const { node } = Astro.props;const locals = Astro.locals as Record<string, unknown>;const seen = (locals.kitSlugs ??= new Map()) as Map<string, number>;const id = uniqueSlug(blockText(node as never), seen);const Tag = (node.style ?? 'h2') as 'h2' | 'h3' | 'h4';--- <Tag id={id}><slot /></Tag>
src/kit/components/pt/Link.astroAstro
---// A link mark. Only http(s), mailto, tel and relative links are rendered: anything else (javascript:, data:) from the// CMS becomes "#". Links to other sites get rel="noopener"; they open in the same tab (people decide that themselves).import type { Mark } from 'astro-portabletext/types'; interface Props {  node: Mark<{ href?: string }>;}const raw = (Astro.props.node.markDef?.href ?? '').trim();const base = Astro.site ?? Astro.url;let url: URL | undefined;try {  url = new URL(raw, base);} catch {}const safe = !!raw && !!url && ['http:', 'https:', 'mailto:', 'tel:'].includes(url.protocol);const href = safe ? raw : '#';const external = safe && /^https?:$/.test(url!.protocol) && url!.origin !== new URL(base).origin;--- <a href={href} rel={external ? 'noopener' : undefined}><slot /></a>
src/kit/components/pt/Image.astroAstro
---// An image block: { src, alt, width?, height?, caption? } from your GROQ projection. Without a size the browser// can't reserve space, so project asset->metadata.dimensions (the post model's query does).import type { TypedObject } from 'astro-portabletext/types'; interface Props {  node: TypedObject & { src?: string; alt?: string; width?: number; height?: number; caption?: string };}const { src, alt = '', width, height, caption } = Astro.props.node;--- {  src && (    <figure>      <img src={src} alt={alt} width={width} height={height} loading="lazy" decoding="async" />      {caption && <figcaption>{caption}</figcaption>}    </figure>  )}
src/kit/components/pt/Code.astroAstro
---// A code block from Sanity's code input ({ code, language, filename }), highlighted at build time.import type { TypedObject } from 'astro-portabletext/types';import CodeBlock from '../CodeBlock.astro'; interface Props {  node: TypedObject & { code?: string; language?: string; filename?: string };}const { code = '', language, filename } = Astro.props.node;--- <CodeBlock code={code} lang={language} filename={filename} />