Masonry
Place variable-height items into the shortest column in data order. Useful for card and picture walls. DOM order stays consistent; moving between columns preserves child components.
Import
import { HuiMasonry, useBreakpoint, resolveResponsive } from '@nscode/handy-ui'
import type {
MasonryProps,
MasonryEmits,
MasonrySlots,
Breakpoint,
ResponsiveValue
} from '@nscode/handy-ui'
Examples
Variable-height cards and layout events
The item slot receives the data, original index and zero-based column. The layout event reports accumulated column heights after an actual layout change. Nonempty columns include the final vertical gap; the container height excludes that gap.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiMasonry, HuiSpace } from '@nscode/handy-ui'
const heights = ref<number[]>([])
const cards = [
{ id: 1, title: 'Project plan', height: 80 },
{ id: 2, title: 'Design', height: 130 },
{ id: 3, title: 'Test records', height: 100 },
{ id: 4, title: 'Release checklist', height: 160 },
{ id: 5, title: 'Instructions', height: 90 }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiMasonry :items="cards" :columns="3" item-key="id" @layout="heights = $event">
<template #item="{ item, index, column }">
<article class="card" :style="{ minHeight: `${item.height}px` }">
<strong>{{ item.title }}</strong>
<p>Item {{ index + 1 }}, column {{ column + 1 }}</p>
</article>
</template>
</HuiMasonry>
<span>Accumulated column heights: {{ heights.join(' / ') || 'Waiting for measurement' }}</span>
</HuiSpace>
</template>
<style scoped>
.card {
padding: var(--hui-spacing-4);
background: var(--hui-fill-color-light);
border-radius: var(--hui-border-radius);
}
.card p {
margin-bottom: 0;
}
</style>
Responsive columns
Default columns are { xs: 1, sm: 2, md: 3, lg: 4 }; xl inherits lg. Resolution selects the nearest configured breakpoint at or below the current breakpoint. If all configured breakpoints are larger, it selects the smallest configured one. Resize the browser to see the result; breakpoints follow the viewport.
<script setup lang="ts">
import { HuiMasonry } from '@nscode/handy-ui'
const cards = Array.from({ length: 9 }, (_, index) => ({
id: index,
height: 72 + (index % 4) * 28
}))
</script>
<template>
<HuiMasonry :items="cards" :columns="{ xs: 1, sm: 2, lg: 4 }" item-key="id">
<template #item="{ item }">
<div class="card" :style="{ height: `${item.height}px` }">Card {{ item.id + 1 }}</div>
</template>
</HuiMasonry>
</template>
<style scoped>
.card {
padding: var(--hui-spacing-3);
background: var(--hui-color-primary-bg);
border-radius: var(--hui-border-radius);
}
</style>
Horizontal and vertical gaps
A numeric gap applies to both directions. A pair is [horizontal, vertical], in pixels. Compare 8 with [24, 12].
<script setup lang="ts">
import { HuiMasonry, HuiSpace } from '@nscode/handy-ui'
const cards = [80, 120, 60, 100]
const gaps: Array<number | [number, number]> = [8, [24, 12]]
</script>
<template>
<HuiSpace direction="vertical" fill>
<div v-for="(gap, index) in gaps" :key="index">
<p>gap:{{ JSON.stringify(gap) }}</p>
<HuiMasonry :items="cards" :columns="2" :gap="gap">
<template #item="{ item }"
><div class="card" :style="{ height: `${item}px` }">{{ item }}px</div></template
>
</HuiMasonry>
</div>
</HuiSpace>
</template>
<style scoped>
.card {
padding: var(--hui-spacing-3);
background: var(--hui-fill-color-light);
border-radius: var(--hui-border-radius);
}
</style>
Appending items and stable keys
itemKey accepts a field name or function returning a stable unique identifier. Keys preserve child component state when items are appended or reordered. The default key is the index.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInput, HuiMasonry, HuiSpace } from '@nscode/handy-ui'
interface Card {
id: number
text: string
note: string
height: number
}
const cards = ref<Card[]>([
{ id: 1, text: 'First card', note: '', height: 90 },
{ id: 2, text: 'Second card', note: '', height: 130 }
])
let seed = 2
const key = (item: Card) => item.id
const append = () => {
seed += 1
cards.value.push({ id: seed, text: `New card ${seed}`, note: '', height: 80 + (seed % 4) * 24 })
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="append">Append card</HuiButton>
<HuiMasonry :items="cards" :columns="2" :item-key="key">
<template #item="{ item }">
<article class="card" :style="{ minHeight: `${item.height}px` }">
<p>{{ item.text }}</p>
<HuiInput
v-model="item.note"
placeholder="Type here, then append a card; the value stays"
/>
</article>
</template>
</HuiMasonry>
</HuiSpace>
</template>
<style scoped>
.card {
padding: var(--hui-spacing-3);
background: var(--hui-fill-color-light);
border-radius: var(--hui-border-radius);
}
</style>
Picture wall and growing content
Colored blocks represent pictures without external requests. Toggle the first height to trigger automatic ResizeObserver layout. Real image loading uses the same size observation.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMasonry, HuiSpace } from '@nscode/handy-ui'
const pictures = ref(
Array.from({ length: 8 }, (_, index) => ({ id: index, height: 80 + (index % 3) * 40 }))
)
const enlarge = () => {
pictures.value[0].height = pictures.value[0].height === 80 ? 200 : 80
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="enlarge">Toggle first picture height</HuiButton>
<HuiMasonry :items="pictures" :columns="3" :gap="[12, 20]" item-key="id">
<template #item="{ item }">
<figure class="picture" :style="{ height: `${item.height}px` }">
<figcaption>Picture {{ item.id + 1 }}</figcaption>
</figure>
</template>
</HuiMasonry>
</HuiSpace>
</template>
<style scoped>
.picture {
margin: 0;
display: flex;
align-items: end;
padding: var(--hui-spacing-3);
background: var(--hui-color-primary-bg);
color: var(--hui-text-color);
border-radius: var(--hui-border-radius);
}
</style>
Empty state
The empty slot stays in normal document flow without a fixed zero height. No extra text appears when the slot is omitted.
<script setup lang="ts">
import { HuiMasonry } from '@nscode/handy-ui'
const cards: string[] = []
</script>
<template>
<HuiMasonry :items="cards"
><template #empty
><p class="empty">No cards yet. Please check back later.</p></template
></HuiMasonry
>
</template>
<style scoped>
.empty {
margin: 0;
padding: var(--hui-spacing-6);
text-align: center;
color: var(--hui-text-color-secondary);
background: var(--hui-fill-color-light);
}
</style>
Breakpoint utilities
useBreakpoint() returns a readonly reactive breakpoint. resolveResponsive() makes the same resolution rules available to other layouts. All callers share four media-query listeners, which are removed after the last instance unmounts.
<script setup lang="ts">
import { computed } from 'vue'
import { HuiMasonry, HuiSpace, useBreakpoint, resolveResponsive } from '@nscode/handy-ui'
const breakpoint = useBreakpoint()
const columns = computed(() => resolveResponsive({ xs: 1, md: 3, xl: 5 }, breakpoint.value, 1))
const cards = [90, 130, 80, 110, 70]
</script>
<template>
<HuiSpace direction="vertical" fill>
<span>Current breakpoint: {{ breakpoint }}, resolved columns: {{ columns }}</span>
<HuiMasonry :items="cards" :columns="columns">
<template #item="{ item, index }"
><div class="card" :style="{ height: `${item}px` }">Item {{ index + 1 }}</div></template
>
</HuiMasonry>
</HuiSpace>
</template>
<style scoped>
.card {
padding: var(--hui-spacing-3);
background: var(--hui-fill-color-light);
border-radius: var(--hui-border-radius);
}
</style>
Props
| Prop | Description | Type | Default |
|---|---|---|---|
| items | Items in original data order | T[] | Required |
| columns | Fixed or responsive column count; fractions are floored, invalid values or values below 1 use 1 | ResponsiveValue<number> | { xs: 1, sm: 2, md: 3, lg: 4 } |
| gap | Gap in both directions or [horizontal, vertical]; negative and non-finite values use 0 | number | [number, number] | 16 |
| itemKey | Stable unique field name or function; invalid fields fall back to the index | string | ((item: T, index: number) => string | number) | Index |
Events
| Event | Arguments | Description |
|---|---|---|
| layout | columnHeights: number[] | Emitted after actual layout changes; nonempty columns include the final vertical gap; empty data emits [] |
Slots
| Slot | Arguments | Description |
|---|---|---|
| item | { item: T, index: number, column: number } | Data, original index and zero-based column. The initial column is 0 before measurement. Omit to show the item's text |
| empty | — | Content for empty data |
Methods
No component instance methods. Size changes trigger automatic layout.
Utilities
useBreakpoint
useBreakpoint(): Readonly<Ref<Breakpoint>>
Takes no arguments and returns a readonly ref for the viewport breakpoint. Call it synchronously inside component setup or script setup so lifecycle cleanup can be registered. A synchronous read of breakpoint.value during setup always returns lg, as does SSR. The actual breakpoint is applied after mounting. Read it reactively in templates, computed or watch; avoid taking a fixed snapshot during setup. Without matchMedia it stays lg.
Mounted consumers share four media-query listeners. A new consumer initializes only itself; media-query changes notify existing consumers. Listeners are removed after the last consumer unmounts.
resolveResponsive
resolveResponsive<T>(value: ResponsiveValue<T>, breakpoint: Breakpoint, fallback: T): T
| Parameter | Description |
|---|---|
| value | A value or breakpoint configuration; non-object values pass through |
| breakpoint | Current breakpoint, usually useBreakpoint().value |
| fallback | Returned when no breakpoint is configured in an object |
Returns the nearest configured value at or below the current breakpoint. If all configured breakpoints are larger, returns the smallest configured one. Explicit values such as 0 remain valid.
Types
import type { Ref } from 'vue'
type Breakpoint = 'xs' | 'sm' | 'md' | 'lg' | 'xl'
type ResponsiveValue<T> = T | Partial<Record<Breakpoint, T>>
interface MasonryProps<T = unknown> {
items: T[]
columns?: ResponsiveValue<number>
gap?: number | [number, number]
itemKey?: string | ((item: T, index: number) => string | number)
}
interface MasonryEmits {
layout: [columnHeights: number[]]
}
interface MasonrySlots<T> {
item?: (props: { item: T; index: number; column: number }) => unknown
empty?: () => unknown
}
const BREAKPOINT_MIN_WIDTH: Record<Breakpoint, number> = {
xs: 0,
sm: 640,
md: 768,
lg: 1024,
xl: 1280
}
function useBreakpoint(): Readonly<Ref<Breakpoint>>
function resolveResponsive<T>(value: ResponsiveValue<T>, breakpoint: Breakpoint, fallback: T): T