# Masonry

> Photos or cards of different heights, packed into columns in their own order.

Page: https://uicontext.com/docs/components/masonry

Group: Primitives.

## When to use

Photos or cards of different heights, packed into columns in their own order. Use [Gallery](https://uicontext.com/docs/components/gallery.md) instead when the cards are records with fields to show.

## Usage

```ts
import { Masonry } from "./ui/uicontext/components/Masonry.ts"

interface Photo {
	readonly id: string
	readonly url: string
	readonly alt: string
	readonly width: number
	readonly height: number
}

export const Photos = <M>(h: Html.H<M>, photos: ReadonlyArray<Photo>) =>
	Masonry(h, {
		label: "Photos",
		items: photos.map((p) => ({ key: p.id, ratio: p.height / p.width })),
		item: (_, i) => h.img.attrs({ src: photos[i]!.url, alt: photos[i]!.alt }),
	})
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### A photo library

The example the page opens with: Masonry in “A photo library”.

```ts title="src/demo.ts" source="www/src/examples/masonry/demo.ts"
import type { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Masonry } from "./ui/uicontext/components/Masonry.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, corner, font, space } from "./ui/uicontext/components/tokens.stylex.ts"
import { picture } from "./pictures.ts"

const styles = stylex.create({
	wrap: { inlineSize: "100%" },
	card: { margin: 0, display: "grid", gridTemplateRows: "minmax(0, 1fr) auto", blockSize: "100%", overflow: "hidden", borderRadius: corner.card, backgroundColor: color.raised },
	image: { display: "block", inlineSize: "100%", blockSize: "100%", objectFit: "cover" },
	caption: { display: "grid", alignContent: "center", blockSize: 44, paddingInline: space.md, fontSize: font.sm, color: color.fg },
	name: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontWeight: 500 },
	by: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontSize: font.xs, color: color.muted },
})

const photos = [
	{ id: "p1", title: "Dawn over Lofoten", by: "Ines Duarte", w: 1200, h: 1600 },
	{ id: "p2", title: "Harbour, low tide", by: "Kenji Mori", w: 1600, h: 1000 },
	{ id: "p3", title: "Salt flats", by: "Ada Okafor", w: 1200, h: 1200 },
	{ id: "p4", title: "Lavender rows, Valensole", by: "Priya Raman", w: 1000, h: 1500 },
	{ id: "p5", title: "Rice terraces at noon", by: "Tomas Berg", w: 1600, h: 900 },
	{ id: "p6", title: "Fog in the pines", by: "Jo Lovelace", w: 1080, h: 1350 },
	{ id: "p7", title: "Dune ridge", by: "Rafael Costa", w: 1500, h: 1000 },
	{ id: "p8", title: "Glacier lagoon", by: "Ben Okafor", w: 1200, h: 1800 },
	{ id: "p9", title: "Orchard in bloom", by: "Mira Haas", w: 1400, h: 1050 },
	{ id: "p10", title: "Night market lanterns", by: "Lin Zhao", w: 1000, h: 1250 },
	{ id: "p11", title: "Cliff path, Algarve", by: "Ines Duarte", w: 1600, h: 1067 },
	{ id: "p12", title: "Tide pools", by: "Kenji Mori", w: 1200, h: 1500 },
]

// a photo library: pictures of every shape, each with its title and who took it
export const PhotoWall = <M>(h: Html.H<M>) =>
	h.div.attrs(sx(styles.wrap)).children(
		Masonry(h, {
			label: "Photos",
			items: photos.map((p) => ({ key: p.id, ratio: p.h / p.w, extra: 44 })),
			item: (_, i) => {
				const p = photos[i]!
				return h.figure.attrs(sx(styles.card)).children(
					h.img.attrs({ src: picture(p.w, p.h, i), alt: p.title, loading: "lazy", width: String(p.w), height: String(p.h), ...sx(styles.image) }),
					h.figcaption.attrs(sx(styles.caption)).children(h.span.attrs(sx(styles.name)).children(p.title), h.span.attrs(sx(styles.by)).children(p.by)),
				)
			},
		}),
	)
```

### Cards, at most three across

`extra` is the card's fixed part under its picture. `maxColumns` caps the columns for wider cards.

```ts title="src/recipes.ts" source="www/src/examples/masonry/recipes.ts"
import type { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Masonry } from "./ui/uicontext/components/Masonry.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { color, corner, font, space, stroke } from "./ui/uicontext/components/tokens.stylex.ts"
import { picture } from "./pictures.ts"

const styles = stylex.create({
	wrap: { inlineSize: "100%" },
	card: {
		display: "grid",
		gridTemplateRows: "minmax(0, 1fr) auto",
		blockSize: "100%",
		overflow: "hidden",
		borderWidth: stroke.hairline,
		borderStyle: "solid",
		borderColor: color.line,
		borderRadius: corner.card,
		backgroundColor: color.panel,
		color: color.fg,
		textDecoration: "none",
		outline: { default: "none", ":focus-visible": `2px solid ${color.focusRing}` },
		outlineOffset: 2,
	},
	image: { display: "block", inlineSize: "100%", blockSize: "100%", objectFit: "cover" },
	body: { display: "grid", alignContent: "start", gap: space.xxs, blockSize: 64, boxSizing: "border-box", paddingBlock: space.sm, paddingInline: space.md },
	name: { fontSize: font.sm, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
	meta: { fontSize: font.xs, color: color.muted, fontVariantNumeric: "tabular-nums" },
})

const recipes = [
	{ id: "r1", name: "Charred leeks, romesco", minutes: 35, serves: 4, w: 4, h: 5 },
	{ id: "r2", name: "Miso butter noodles", minutes: 20, serves: 2, w: 1, h: 1 },
	{ id: "r3", name: "Slow-roast tomatoes", minutes: 150, serves: 6, w: 3, h: 4 },
	{ id: "r4", name: "Lemon ricotta pancakes", minutes: 25, serves: 4, w: 4, h: 3 },
	{ id: "r5", name: "Lamb shoulder, flatbreads", minutes: 240, serves: 8, w: 2, h: 3 },
	{ id: "r6", name: "Green shakshuka", minutes: 30, serves: 2, w: 1, h: 1 },
	{ id: "r7", name: "Burnt basque cheesecake", minutes: 70, serves: 10, w: 4, h: 5 },
	{ id: "r8", name: "Crispy rice salad", minutes: 25, serves: 3, w: 16, h: 9 },
]

const time = (m: number) => (m < 60 ? `${m} min` : `${Math.floor(m / 60)} h${m % 60 === 0 ? "" : ` ${m % 60} min`}`)

// a recipe wall: whole cards are links, at most three across
export const RecipeWall = <M>(h: Html.H<M>) =>
	h.div.attrs(sx(styles.wrap)).children(
		Masonry(h, {
			label: "Recipes",
			maxColumns: 3,
			items: recipes.map((r) => ({ key: r.id, ratio: r.h / r.w, extra: 64 })),
			item: (_, i) => {
				const r = recipes[i]!
				return h.a.attrs({ href: `#${r.id}`, ...sx(styles.card) }).children(
					h.img.attrs({ src: picture(r.w * 100, r.h * 100, i + 2), alt: "", loading: "lazy", ...sx(styles.image) }),
					h.span.attrs(sx(styles.body)).children(h.span.attrs(sx(styles.name)).children(r.name), h.span.attrs(sx(styles.meta)).children(`${time(r.minutes)} · serves ${r.serves}`)),
				)
			},
		}),
	)
```

### Sample data

The examples above import these files.

```ts title="src/pictures.ts" source="www/src/examples/_shared/pictures.ts"
// Pictures drawn inline, so examples need no image files: a sky, a sun and two hills in a palette,
// at the photo's own width and height.

const palettes = [
	["#fde68a", "#f97316", "#7c2d12", "#431407"],
	["#bae6fd", "#38bdf8", "#0f766e", "#134e4a"],
	["#e9d5ff", "#a855f7", "#4c1d95", "#2e1065"],
	["#fecdd3", "#fb7185", "#9f1239", "#4c0519"],
	["#d9f99d", "#84cc16", "#365314", "#1a2e05"],
	["#e2e8f0", "#94a3b8", "#334155", "#0f172a"],
] as const

/** A landscape picture `width` × `height`, in palette `tone` (0–5). */
export const picture = (width: number, height: number, tone: number) => {
	const [sky, sun, near, far] = palettes[tone % palettes.length]!
	const w = width
	const h = height
	return `data:image/svg+xml,${encodeURIComponent(
		`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" preserveAspectRatio="xMidYMid slice"><rect width="${w}" height="${h}" fill="${sky}"/><circle cx="${w * 0.7}" cy="${h * 0.35}" r="${Math.min(w, h) * 0.14}" fill="${sun}"/><path d="M0 ${h * 0.72} Q${w * 0.3} ${h * 0.5} ${w * 0.6} ${h * 0.7} T${w} ${h * 0.62} V${h} H0Z" fill="${far}" fill-opacity="0.55"/><path d="M0 ${h * 0.86} Q${w * 0.4} ${h * 0.7} ${w} ${h * 0.84} V${h} H0Z" fill="${near}"/></svg>`,
	)}`
}
```

## API reference

**Options**

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` | — | What the wall holds, for screen readers: "Moodboard". |
| `items` (required) | `MasonryItem[]` | — | — |
| `item` (required) | `(item: MasonryItem, index: number) => View.Content` | — | Draws an item; it fills its box. |
| `maxColumns` | `1 \| 2 \| 3 \| 4` | `4` | 4 by default; fewer for wide cards. |
| `style` | `Style` | — | — |

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/masonry
```

With npm: `npx shadcn@latest add checkfu/uicontext/masonry`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/masonry`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/masonry`.

It writes these files:

- `src/ui/uicontext/components/Masonry.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/Masonry.ts](https://github.com/checkfu/uicontext/blob/main/src/Masonry.ts)
- [src/tokens.stylex.ts](https://github.com/checkfu/uicontext/blob/main/src/tokens.stylex.ts)

## Used in

- [SaaS dashboard](https://uicontext.com/blocks/saas-dashboard.md)
- [Chat](https://uicontext.com/blocks/ai-chat.md)
- [Task manager](https://uicontext.com/blocks/issue-tracker.md)
- [Company brain](https://uicontext.com/blocks/doc-workspace.md)
- [Workflow builder](https://uicontext.com/blocks/automation-builder.md)
- [Database](https://uicontext.com/blocks/tables.md)
- [CRM](https://uicontext.com/blocks/crm.md)
- [Analytics dashboard](https://uicontext.com/blocks/analytics.md)
- [Email](https://uicontext.com/blocks/email.md)
- [Scheduling](https://uicontext.com/blocks/scheduling.md)
- [Storefront](https://uicontext.com/blocks/storefront.md)
- [Helpdesk](https://uicontext.com/blocks/helpdesk.md)
- [Agent studio](https://uicontext.com/blocks/agent-studio.md)
- [Work](https://uicontext.com/blocks/work.md)
- [Team assistant](https://uicontext.com/blocks/team-assistant.md)
- [Team chat](https://uicontext.com/blocks/team-chat.md)
- [Bots](https://uicontext.com/blocks/bot-console.md)
- [Design](https://uicontext.com/blocks/design-tool.md)
- [Whiteboard](https://uicontext.com/blocks/whiteboard.md)

## Related

- [Button](https://uicontext.com/docs/components/button.md) (`button`): A button, and a link that looks like one, in every tone and three sizes.
- [Toggle](https://uicontext.com/docs/components/toggle.md) (`toggle`): A button that stays pressed, such as Bold or Pin.
- [Toggle Group](https://uicontext.com/docs/components/toggle-group.md) (`toggle-group`): Buttons that stay pressed and share one value, such as text styles.
- [Input](https://uicontext.com/docs/components/input.md) (`input`): Text inputs, selects and textareas in a labeled field with a hint and an error, and their styles for controls you lay out yourself.
- [Status](https://uicontext.com/docs/components/status.md) (`status`): Status badges and tags for runs and records.
- [Glyphs](https://uicontext.com/docs/components/glyphs.md) (`glyphs`): Small marks for status, priority, color and people.
