npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

vue-masonry-blade

v0.0.6

Published

Composable masonry and virtualization hooks powered by masonry-blade

Readme

vue-masonry-blade

GitHub License Module type: ESM build-validate codeql NPM Version NPM Unpacked Size npm package minimized gzipped size codecov

Набор composable-хуков Vue 3 для masonry-blade.

English README

Быстрый старт

Установка

Требуется vue@^3.5.0.

npm install vue-masonry-blade
pnpm add vue-masonry-blade
yarn add vue-masonry-blade

Экспорты

import {
	useMasonry,
	useMasonryMatrix,
	useVirtualMasonry,
	getPositionedStyle,
} from 'vue-masonry-blade';

Базовый пример

useMasonry() объединяет useMasonryMatrix() и виртуализацию из useVirtualMasonry().

<script setup lang="ts">
import { onMounted, ref, shallowRef } from 'vue';
import { getPositionedStyle, useMasonry } from 'vue-masonry-blade';

interface Meta {
	src: string;
}

const rootRef = ref<HTMLElement | null>(null);

const items = shallowRef([
	{ id: 1, width: 800, height: 600, meta: { src: '/images/1.jpg' } },
	{ id: 2, width: 800, height: 1100, meta: { src: '/images/2.jpg' } },
	{ id: 3, width: 800, height: 700, meta: { src: '/images/3.jpg' } },
]);

const columnCount = ref(4);
const gap = ref(12);
const overscanPx = ref(300);
const breakpoints = shallowRef({ 0: 1, 640: 2, 960: 3, 1280: 4 });

const { containerHeight, recreate, visibleItems, onCreated } = useMasonry<Meta>(
	rootRef,
	{
		columnCount,
		gap,
		overscanPx,
		breakpoints,
	},
);

onCreated((matrix) => {
	matrix.disableWorker();
});

onMounted(async () => {
	await recreate(items.value);
});
</script>

<template>
	<section
		ref="rootRef"
		:style="{ position: 'relative', height: `${containerHeight}px` }"
	>
		<article
			v-for="item in visibleItems"
			:key="item.id"
			:style="{
				...getPositionedStyle(item),
				position: 'absolute',
			}"
		>
			<img
				:src="item.meta?.src"
				:alt="''"
				:style="{ width: '100%', height: '100%', objectFit: 'cover' }"
			/>
		</article>
	</section>
</template>

Для пагинации или бесконечной подгрузки используйте append(items) вместо полной пересборки исходного массива.

items здесь намеренно хранится в shallowRef(...). Если использовать ref(...) или reactive(...), Vue обернет вложенные элементы в proxy, а такие значения нельзя передать в worker через structured clone. Это правило относится ко всем элементам, которые вы передаёте в append() / recreate() или вообще храните в исходной коллекции матрицы.

Nuxt / SSR

useMasonry() и useVirtualMasonry() зависят от DOM-измерений, поэтому в SSR-среде поддерево, которое использует эти хуки, должно рендериться только на клиенте. В Nuxt оборачивайте такую часть в ClientOnly или выносите использование хуков в client-only компонент.

<ClientOnly>
	<MasonryGallery />
</ClientOnly>

Composables

useMasonry()

Удобный orchestration-хук, который связывает useMasonryMatrix() и useVirtualMasonry() в один интерфейс.

const {
	matrix,
	matrixColumns,
	sourceItems,
	containerHeight,
	resolvedColumnCount,
	append,
	recreate,
	clear,
	sort,
	onCreated,
	visibleMatrix,
	visibleItems,
	rangeStart,
	rangeEnd,
	overscanPx,
} = useMasonry(rootRef, {
	gap,
	columnCount,
	breakpoints,
	overscanPx,
});

useMasonryMatrix()

Создаёт и управляет экземпляром MasonryMatrix. Подходит, когда нужен прямой контроль над append, recreate, sorting, breakpoints и состоянием worker'а.

const {
	matrix,
	matrixColumns,
	sourceItems,
	containerHeight,
	resolvedColumnCount,
	append,
	recreate,
	clear,
	sort,
	onCreated,
} = useMasonryMatrix(rootRef, gap, columnCount, breakpoints);

Хук держит состояние матрицы синхронизированным с шириной контейнера и пересоздаёт ее при изменении ширины, gap, числа колонок или breakpoints.

Через onCreated((matrix) => {}) можно подписаться на первое создание внутреннего экземпляра MasonryMatrix.

При изменении breakpoints необходимо заменять весь объект целиком, а не мутировать его на месте.

Для управления worker'ом при необходимости используйте matrix.value напрямую.

useVirtualMasonry()

Строит видимую часть матрицы и возвращает плоский отсортированный список для рендера.

const { visibleMatrix, visibleItems, rangeStart, rangeEnd, overscanPx } =
	useVirtualMasonry(rootRef, matrix, matrixColumns, {
		overscanPx: 300,
	});
  • visibleMatrix сохраняет структуру по колонкам.
  • visibleItems — отсортированный плоский массив видимых элементов

Утилиты

getPositionedStyle()

Преобразует вычисленный элемент матрицы в inline-стили.

const style = getPositionedStyle(item);

Возвращаемая форма:

{
	width: '...px',
	height: '...px',
	transform: 'translate(...px, ...px)'
}

Форма исходного элемента

Элементы, передаваемые в recreate(items) или append(items), должны иметь такой вид:

{
	id: string | number,
	width: number,
	height: number,
	meta?: unknown
}

width и height — это исходные размеры, которые используются для расчёта финального размера элемента внутри сетки.

Храните исходную коллекцию в shallowRef(...) или иным способом следите, чтобы элементы оставались plain-объектами, совместимыми со structured clone. В worker-режиме Vue proxy из ref(...) / reactive(...) не проходят structured clone и могут ломать append() / recreate().

Contributing

Смотрите CONTRIBUTING.md

Security

Смотрите SECURITY.md

License

Проект распространяется по лицензии MPL 2.0.

Ссылки