8000 feat: @jimp/layout, a flexbox-style layout renderer for OG images by hipstersmoothie · Pull Request #1559 · jimp-dev/jimp · GitHub
[go: up one dir, main page]

Skip to content

feat: @jimp/layout, a flexbox-style layout renderer for OG images - #1559

Merged
hipstersmoothie merged 8 commits into
mainfrom
sesh/jimp-layout-for-og-images
Nov 25, 2026
Merged

hipstersmoothie merged 8 commits into
mainfrom
sesh/jimp-layout-for-og-images

Conversation

@hipstersmoothie
@hipstersmoothie hipstersmoothie commented Nov 25, 2026 •
Copy link
Copy Markdown
Collaborator

Adds @jimp/layout, a declarative layout renderer for Open Graph cards, social banners and badges, built entirely on Jimp. You describe a tree of boxes, text and images, it's laid out like a subset of CSS flexbox, and render draws it. There's no browser, SVG or WASM step, so it runs anywhere Jimp does (Node, browsers, workers, Deno, Bun).

An Open Graph card rendered with @jimp/layout

Rendered by packages/docs/scripts/layout-guide-images.mjs from the guide's code, 1200 × 630, in about 45 ms (fonts and avatar loaded beforehand).

import { Jimp } from "jimp";
import { render } from "@jimp/layout";

const card = await render(
  {
    type: "box",
    padding: 72,
    justify: "space-between",
    background: { type: "linear", angle: 135, stops: ["#1b1840", "#3a2d7a"] },
    font: regular,
    color: "white",
    children: [header, body, tags],
  },
  { width: 1200, height: 630, Jimp },
);

What's in it

@jimp/layout (new package, not in the jimp bundle)

  • render(tree, { Jimp, width?, height?, background? }) returns an image of the Jimp class you pass in. layout(tree, options) returns the computed boxes without drawing anything.
  • There are three node types: box, text and image. Each is a flat object, validated with zod (strict, so a typo like justifyContent throws, and the error includes the path to the node).
  • Flex subset:
    • direction, gap, padding, margin;
    • justify (start/center/end/space-between/around/evenly) and align/alignSelf (start/center/end/stretch);
    • grow/shrink (with min/max freezing) and wrap: true for multi-line rows or columns;
    • fixed, % and auto sizes, min/max sizes and aspectRatio;
    • position: "absolute" with top/right/bottom/left.
  • CSS's automatic minimum size: flex items don't shrink below their content. Text in a row stays at least as wide as its longest word, images keep their size, and boxes fit their children. minWidth: 0 opts out, and overflow: "hidden" boxes can always shrink.
  • Box styles: background (a colour, or a linear/radial gradient sized to the box), borderWidth/borderColor, radius (uniform or per corner), shadow (one or several), opacity and overflow: "hidden" (which clips to the rounded corners).
  • Text: font, fontSize, color (a colour or gradient), lineHeight, letterSpacing and textAlign, all inherited from ancestor boxes, plus maxLines, which truncates with an ellipsis (…, or ... when the font lacks the glyph). Works with loadTTF and bitmap fonts.
  • Images: src is a Jimp image or anything Jimp.read takes. fit is fill/cover/contain, images keep their aspect ratio when only one dimension is set, and a radius rounds them (for avatars).
  • Box/Text/Image components plus a small JSX runtime: @jimp/layout/jsx-runtime and jsx-dev-runtime, about 30 lines, no React. Your own components are plain functions. key is accepted and ignored. null/false/empty strings are skipped.

@jimp/plugin-draw: drawRect gains strokeAlign: "center" | "inside" | "outside". "inside" gives a CSS border: the outline stays inside the box, and the inner corners are strokeWidth tighter. It's drawn as the exact ring between two rounded rects with evenodd, so there are no stroker artefacts at tight corners. "center" remains the default, so existing output is unchanged. It has tests, docs, a playground control and a README entry.

Docs (JSX first; every example also has an Objects tab, and the tabs stay in sync across pages)

  • New guide, "Open Graph Images" (guides/og-images). It covers JSX setup (tsconfig or a per-file pragma, and how to run it in Node) and builds the card above from small components (Card, Header, Body, Tags) in four steps, each with its rendered image. It then shows how to serve the card with Response.
  • New render() reference page (under Drawing):
    • every node type and prop, and minimum sizes;
    • a JSX section: setup, the rules for children, and your own components;
    • examples with images: a badge, layout() positions, an absolutely positioned background photo, and wrapped tags;
    • differences from CSS and validation errors.
  • The drawRect page, the drawing concept page and the jimp README now mention strokeAlign and @jimp/layout.
  • I checked every code sample in both styles: it typechecks, runs, and reproduces the image next to it pixel for pixel. The images come from packages/docs/scripts/layout-guide-images.mjs. Code is formatted to fit its column, so nothing scrolls sideways.

Design decisions

  • No new drawing primitives beyond strokeAlign. Everything else was already in existing plugins, so layout composes those instead of duplicating them:
    • Rounded rects and gradient fills use drawRect.
    • Box shadows draw boxShadow (plugin-border) on a transparent box-sized image, then composite it. Its defaults and its CSS-style blur (σ = blur/2) carry over.
    • Rounded clipping, for overflow: "hidden" and image radii, renders into a layer and applies roundCorners.
    • Opacity renders into a layer and composites it with opacitySource.
    • Images use cover/contain/resize.
    • The only gap was a CSS-style inside border, so that became an option on the existing drawRect rather than a new method.
  • Plugin methods are imported directly (methods.drawRect(image, …), as plugin-shadow does) instead of called on the instance. So render works with a createJimp build that has none of those plugins, and Jimp is only needed to construct images (and to read string or buffer sources).
  • Text uses only the public measuring APIs. Width is measureText, height is measureTextHeight at the wrap width, and drawing is print with the same maxWidth, so wrapping always matches. maxLines binary-searches the longest prefix plus ellipsis that still fits.
  • Pixel snapping: layout is computed in floats, then each node's edges are rounded (as Yoga does) so neighbours still touch. Text is wrapped at the unrounded width, so rounding can never add a line break.
  • Root fills the image unless it has its own size. Without width/height, the image is sized to the tree (useful for badges).
  • Differences from CSS, all documented:
    • Boxes default to direction: "column", as in React Native.
    • Wrapped lines are packed at the start (like align-content: flex-start) and share gap; there's no align-content or separate row/column gaps.
    • Nodes paint in tree order, including absolutely positioned ones, like SVG. That way a background image listed first stays behind the text.
    • Shadows show through transparent backgrounds, as with boxShadow.
  • Layout is a separate opt-in package, depending on core, types, utils, plugin-draw, plugin-print, plugin-border, plugin-cover, plugin-contain, plugin-resize and zod. There are no new third-party dependencies; the lockfile diff is workspace links only.

Tests

  • layout.test.ts (69 tests, Node and browser): layout maths with a synthetic 10 px monospace bitmap font. It covers sizing, percentages, min/max, padding/margins, rows and columns, every justify/align value, grow/shrink/freezing, automatic minimum sizes, aspectRatio, wrap, absolute positioning, text wrapping and maxLines, inheritance, images, validation errors and the components.
  • render.test.ts (15, Node and browser): pixel assertions for backgrounds, inside borders, gradient direction, opacity, clipping, shadow placement, paint order and images.
  • render.node.test.ts (8): image snapshots via @jimp/test-utils/image-snapshot of the OG card, box styles, image fit, an avatar, text alignment/gradients/letter spacing, wrapped tags with an aspectRatio image, and bitmap fonts. One more test checks that the JSX-built card is pixel-identical to the object-built one.
  • jsx.test.tsx: JSX builds the same tree as objects (fragments, arrays, key, null/false, interpolated text), and custom components with children work.
  • plugin-draw: 7 new strokeAlign tests.
  • Fixtures: ASCII + … subsets of Inter Regular/Bold (OFL), generated by packages/layout/scripts/subset-fonts.sh, which is the same approach as plugin-print's script.

Locally, root pnpm build, pnpm lint and pnpm test all pass (87/87 turbo tasks). So do pnpm test:browser for @jimp/layout, pnpm build in packages/docs (astro check reports 0 errors), and pnpm install --frozen-lockfile.

Left out / follow-ups

  • flex-basis, order, z-index, align-content, separate row/column gaps, and per-side border widths/colours.
  • Inline rich text: mixed fonts, colours or weights within one paragraph. Each text node is a single style today; it would need span support in print.
  • Inset shadows, and clipping shadows to outside the box as CSS does.
  • @jimp/layout isn't in the generated TypeDoc type reference: starlight-typedoc is configured for the jimp package only, and adding a second instance touches the shared astro config. The render() page documents every prop by hand instead.
  • A live playground or demo on the docs site; the guide uses committed images.
  • Yoga, as an optional engine for full browser fidelity. I decided against making it the default because it's WebAssembly and this package is meant to be pure JS. The layout and drawing are already separate, so an optional @jimp/layout-yoga add-on could swap it in later without changing the API.
  • Not published to npm.

🤖 Generated with Claude Code

hipstersmoothie and others added 7 commits November 24, 2026 16:02
`strokeAlign: "inside"` keeps a rectangle's outline within it, like a
CSS border, with inner corners `strokeWidth` tighter. `"outside"` puts it
all around the rectangle. Both are drawn as the exact ring between two
rounded rectangles; `"center"` stays the default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8000
Lays out a tree of boxes, text and images in rows and columns (a subset
of CSS flexbox written in TypeScript) and draws it with Jimp, for Open
Graph cards, banners and badges. Text is measured with measureText and
measureTextHeight, and drawn with print. Boxes are drawn with drawRect,
boxShadow and roundCorners. Includes Box/Text/Image components and a JSX
runtime at @jimp/layout/jsx-runtime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The guide builds an OG card with @jimp/layout step by step; its images
are rendered by scripts/layout-guide-images.mjs from the guide's code.
render() documents every node type and prop. drawRect gains strokeAlign
in its page, the drawing concept and the playground.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- wrap: true starts a new line (or column) for children that don't fit.
  Each line flexes, justifies and stretches on its own; gap separates
  lines too, and lines are packed at the start.
- aspectRatio gives a node's height from its width or the other way
  round, set or stretched, and overrides an image's own ratio.
- Like CSS's automatic minimum size, flex items don't shrink below their
  content: text in a row stays as wide as its longest word, images keep
  their size and boxes fit what's in them. minWidth/minHeight: 0 opts
  out, and overflow: hidden boxes can always shrink. This replaces the
  shrink: 0 default for images.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
key is allowed on any element so code written for React type checks; it's
ignored. Empty strings are skipped like null and false, so
{subtitle && <Text>{subtitle}</Text>} adds no empty line. The README leads
with JSX.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The guide and the render() page show each example as JSX and as plain
objects in synced tabs. The render() page gains a JSX section (setup,
children rules, your own components) and images for the badge and
wrapped-tags examples. Code is formatted to fit its column without
scrolling. Every example was type checked, run, and compared pixel for
pixel with the images beside it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With "jsx": "preserve" (Astro's default), @jsxImportSource alone falls
back to the classic runtime and React.createElement.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@hipstersmoothie
hipstersmoothie merged commit e24cf30 into main Nov 25, 2026
7 checks passed
@hipstersmoothie
hipstersmoothie deleted the sesh/jimp-layout-for-og-images branch November 25, 2026 02:17
@hipstersmoothie hipstersmoothie added the minor Increment the minor version when merged label Nov 25, 2026
@hipstersmoothie
Copy link
Copy Markdown
Collaborator Author

🚀 PR was released in v2.2.0 🚀

@hipstersmoothie hipstersmoothie added the released This issue/pull request has been released. label Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

minor Increment the minor version when merged released This issue/pull request has been released.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

0