Command palette

@yasinsensoy/web

Web · Components

Gallery

Image and video gallery: a grid, Pinterest-style masonry or Google Photos-style rows; grouping by date or your own criterion, iOS-like long-press multi-selection and a full-screen viewer.

17 exports

Live example

Import

import { Gallery, Lightbox, mediaType, formatDuration } from "@yasinsensoy/web";

mediaType

function

Type of the item: inferred from the URL extension when type is omitted.

mediaType(item: Pick<MediaItemFields, "src" | "type">): GalleryMediaType

Formats a duration as 1:05 or 1:02:05.

formatDuration(seconds: number): string

Examples

formatDuration(65) // "1:05"
formatDuration(3725) // "1:02:05"

GalleryAction

interface

An action in the selection bar (e.g. Share, Delete).

NameTypeDescription
labelstringButton text.
icon?IconPropIcon: a name or an element.
tone?"neutral" | "danger"If "danger", it appears red.
onClick(items: GalleryItem[], clear: () => void) => unknownCalled with the selected items. If it returns a Promise, the button shows loading until it settles. Call clear() to end the selection.

How a selected item is shown.

type GallerySelectionStyle = "shrink" | "ring" | "dim"

Classes added to the parts of Gallery.

NameTypeDescription
item?stringEach item box (e.g. rounded-none).
header?stringGroup title.
selectionBar?stringSelection bar.

Gallery pagination options: the look of pagination.

Extends: Pick<PaginationProps, "variant" | "siblings" | "boundaries" | "firstLast" | "jumper" | "summary" | "responsive" | "size" | "activeVariant" | "align" | "label" | "className" | "classNames">

NameTypeDefaultDescription
sticky?booleanfalsePage buttons stick to the bottom of the visible area: on a long page you * can change pages without scrolling to the end. The selection bar sits * above the buttons. *

GalleryProps

interface

Props of the Gallery component.

Extends: Omit<ComponentProps<"div">, "children" | "onSelect" | "onLoad">

NameTypeDefaultDescription
itemsreadonly GalleryItem[]Items. If they are grouped, give them sorted in group order (e.g. by date).
layout?GalleryLayout"grid"Layout: "grid" equal squares, "masonry" Pinterest-style columns (ratios kept, added to the shortest column), "rows" Google Photos / Flickr-style rows (each row fills the full width).
columns?numberFixed column count. If omitted, it fits the width by itemWidth.
itemWidth?number200Target item width in grid and masonry (px); determines the column count.
minColumns?number3` for grid, `2` for masonryMinimum column count when columns is not given; the grid look is kept on phones too.
rowHeight?number200Target row height in the rows layout (px). On narrow screens it shrinks to as little as a third of the width.
aspectRatio?number1Cell ratio in the grid (width / height).
gap?number4Gap between items (px).
groupBy?GalleryGroupBy | ((item: GalleryItem, index: number) => string)Grouping: "day" | "month" | "year" by the item's date field ("Today", "Yesterday", "Tuesday, October 28"…), or a function returning a group name from the item. Consecutive items with the same name form a group. Define the function outside the component; a new function on every render recomputes all groups.
groupLabel?(key: string, info: { count: number; start: number; }) => ReactNodeGroup title. If omitted, the date or group name is written.
stickyHeaders?booleantrueGroup titles stay stuck on top while scrolling. If there is a fixed bar at the top of the page, give its height with stickyOffset.
stickyOffset?number | string0Distance of the sticky title from the top (px or a CSS value).
selectable?booleanfalseMulti-selection. On touch, a long press starts selection (like iOS Photos); sliding without lifting the finger selects the ones in between. In selection mode a tap selects/deselects and a sideways swipe selects by dragging. On desktop click the circle in the corner, select one by one with Ctrl/⌘, a range with Shift, or drag with the mouse to select an area. Ctrl/⌘ + A selects all, Esc clears. To see an item large while selecting, press the zoom button in the corner (or Enter); the full-screen view opens and selection continues there with the circle in the top bar. Selection made in full screen is reflected in the gallery.
selected?readonly string[]Ids of the selected items when controlled.
defaultSelected?readonly string[]Initially selected ones when uncontrolled.
onSelectedChange?(selected: string[]) => voidWith the ids when the selection changes.
selectionStyle?GallerySelectionStyle"shrink"Look of a selected item: "shrink" shrinks with rounded corners (iOS, Google Photos), "ring" a frame, "dim" darkens.
selectionActions?readonly GalleryAction[]Actions in the selection bar. See GalleryAction.
selectionBar?booleantrueA sticky selection bar at the bottom while there is a selection.
hoverEffect?"zoom" | "lift" | "none""zoom"On mouse hover: "zoom" the image grows, "lift" it lifts.
effect?EffectPropEffect or effects of the tiles (e.g. "shine", ["tilt", "glow"]); works together with hoverEffect. If omitted, UIProvider appearance.defaults.gallery.effect. See BuiltinEffect.
appear?"fade" | "scale" | "none""fade"Appearance when the image loads: "fade", "scale" (growing) or "none".
rounded?booleantrueRounded corners.
videoPreview?"hover" | "visible" | "none""hover"Preview for videos: "hover" plays muted on mouse hover, "visible" plays when visible on screen (for phone feeds), "none". A light preview video can be given for the preview.
videoFrames?booleantrueFor videos without a cover image (thumbnail, poster), the first frame is extracted in the browser and used as the cover: only the start of the video is downloaded, the frame is turned into a small image and cached; videos coming on screen are processed in turn (at most 3 at a time). When disabled, only a play icon is shown. Having the server generate a poster once is always cheaper.
titles?"hover" | "always"Show item titles below the box: "hover" or "always".
overlay?(item: GalleryItem, index: number) => ReactNodeExtra content drawn on top of the box (e.g. a like count badge).
renderItem?(item: GalleryItem, context: GalleryRenderContext) => ReactNodeRender the inside of the box yourself (e.g. a document card, an audio file, custom badges). Selection, drag selection, keyboard, status indicator and full screen work as before; the built-in rendering comes via context.children. Don't do heavy work so it stays fast with many items; define the function outside the component.
onRetry?(item: GalleryItem, index: number) => voidWhen an item with status="error" is tapped (e.g. restart the upload). If given, "Try again" appears on the tile.
lightbox?boolean | LightboxOptionstrueFull-screen view opened on click. false disables it; an object gives LightboxOptions ({ mode: "vertical", download: true }).
onItemClick?(item: GalleryItem, index: number, event: MouseEvent<HTMLElement>) => voidWhen an item is clicked (outside selection mode). If you call event.preventDefault(), the full-screen view does not open.
onLoadMore?() => unknownFetches the next items. If it returns a Promise, skeleton boxes appear at the bottom until it settles. Called while hasMore is true.
hasMore?booleanfalseThere are more items to fetch.
loadMore?"scroll" | "button""scroll"When the next items arrive: "scroll" automatically near the end (infinite scroll), "button" with a "Show more" button.
loading?booleanLoading: a skeleton grid if there are no items, skeleton boxes at the bottom if there are.
pageSize?numberPagination: this many items per page with page buttons at the bottom. If total is given, items is only the current page (server pagination).
page?numberPage when controlled (starts at 1).
defaultPage?number1Initial page when uncontrolled.
onPageChange?(page: number) => voidWhen the page changes.
total?numberTotal item count for server pagination.
pagination?GalleryPaginationOptionsLook of the page buttons (with pageSize): e.g. { variant: "compact", firstLast: true, summary: true, jumper: true }. See PaginationProps.
height?number | stringHeight of the gallery's own scroll area (px or a CSS value). If omitted, it scrolls with the page (or the nearest scrolling container).
overscan?number800Distance pre-rendered above and below the visible area (px).
empty?ReactNodeContent shown when there are no items.
label?string"Galeri"Screen reader name.
classNames?GalleryClassNamesClasses added to the parts. See GalleryClassNames.

Gallery layout.

type GalleryLayout = "grid" | "masonry" | "rows"

An action button in the full-screen view (e.g. Like, Delete, Share).

NameTypeDescription
labelstringName of the button; for screen readers and the tooltip.
iconIconPropIcon: a name or an element.
tone?"neutral" | "danger"If "danger", it appears red.
onClick(item: GalleryItem, index: number) => unknownCalled with the current item on click. If it returns a Promise, the button shows loading until it settles.

Lightbox view options; Gallery's lightbox prop takes them too.

NameTypeDefaultDescription
mode?"horizontal" | "vertical""horizontal"Transition direction: "horizontal" swipes sideways (like photo apps), "vertical" swipes up like Instagram Reels / TikTok; videos play when they come on screen.
loop?booleanfalseGo from end to start (and start to end) with the buttons and keys.
thumbnails?booleantrueThumbnail strip at the bottom (horizontal only, wide screens).
zoom?booleantrueZoom for images: with two fingers, by double tapping/clicking and with Ctrl + wheel; in horizontal and vertical mode. When zoomed in, pan with a finger.
preload?number1Number of items prepared in advance on each side of the visible one. Images download in the background and the first seconds of videos load; transitions don't wait.
download?booleanfalseDownload button.
share?boolean | ((item: GalleryItem, index: number) => ShareContent)false` (when enabled, the item's URL and title)Share button. On phones the system share sheet opens; in browsers that don't support it (most desktops) the link is copied to the clipboard and the button says "Link copied". If a function is given, it returns the content to share (e.g. the page URL instead of the image itself): share={(item) => ({ url: \/photo/${item.id}\, title: item.alt })}.
fullscreen?booleanfalseGoes straight to the browser's full screen when opened: the address bar and tabs are hidden too. Leaving full screen (Esc or the phone's back gesture) also closes the viewer; the full screen button is not shown. If the browser doesn't allow it (e.g. iPhone Safari), it opens inside the window.
fullscreenButton?booleantrueFull screen button in the top bar (the F key toggles too). Visible in supporting browsers while fullscreen is off.
slideshow?boolean | numberfalse` (4000 ms when enabled)Slideshow button. If a number is given, the duration of each item (ms); videos advance when they end.
captions?booleantrueShow the title and description at the bottom.
videoFrames?booleantrueFor videos without a cover image, the first frame is extracted in the browser and used as the cover in the thumbnail strip and the player. See VideoFrameImage.
actions?readonly LightboxAction[]Extra action buttons. See LightboxAction.

LightboxProps

interface

Props of the Lightbox component.

NameTypeDefaultDescription
itemsreadonly GalleryItem[]Items to show.
open?booleanIs it open when controlled?
defaultOpen?booleanfalseIs it initially open when uncontrolled?
onOpenChange?(open: boolean) => voidWhen it opens or closes.
index?numberIndex of the shown item when controlled.
defaultIndex?number0Initial index when uncontrolled.
onIndexChange?(index: number) => voidWith the new index when the item changes.
onReachEnd?() => voidCalled when nearing the last items; to fetch the next page in infinite lists. When new items are added to items, it continues where it left off.
originRect?(index: number) => DOMRect | null | undefinedOn-screen position of the thumbnail the image grows out of / returns to on open and close. Gallery gives it itself; in your own grid return (index) => element.getBoundingClientRect().
onRatio?(item: GalleryItem, ratio: number) => voidReports the measured aspect ratio (e.g. for the gallery layout).
label?string"Galeri"Screen reader name of the window.
selectable?booleanfalseSelection: a circle in the top bar that selects the current item, the selected count and a mark on thumbnails. Gallery gives it itself while selectable; while selecting in the gallery you can see the item large and continue selecting here.
selected?readonly string[]Ids of the selected items (id, or src if missing).
onSelectedChange?(selected: string[]) => voidWith the ids when the selection changes.
mode?"horizontal" | "vertical""horizontal"Transition direction: "horizontal" swipes sideways (like photo apps), "vertical" swipes up like Instagram Reels / TikTok; videos play when they come on screen.
loop?booleanfalseGo from end to start (and start to end) with the buttons and keys.
thumbnails?booleantrueThumbnail strip at the bottom (horizontal only, wide screens).
zoom?booleantrueZoom for images: with two fingers, by double tapping/clicking and with Ctrl + wheel; in horizontal and vertical mode. When zoomed in, pan with a finger.
preload?number1Number of items prepared in advance on each side of the visible one. Images download in the background and the first seconds of videos load; transitions don't wait.
download?booleanfalseDownload button.
share?boolean | ((item: GalleryItem, index: number) => ShareContent)false` (when enabled, the item's URL and title)Share button. On phones the system share sheet opens; in browsers that don't support it (most desktops) the link is copied to the clipboard and the button says "Link copied". If a function is given, it returns the content to share (e.g. the page URL instead of the image itself): share={(item) => ({ url: \/photo/${item.id}\, title: item.alt })}.
fullscreen?booleanfalseGoes straight to the browser's full screen when opened: the address bar and tabs are hidden too. Leaving full screen (Esc or the phone's back gesture) also closes the viewer; the full screen button is not shown. If the browser doesn't allow it (e.g. iPhone Safari), it opens inside the window.
fullscreenButton?booleantrueFull screen button in the top bar (the F key toggles too). Visible in supporting browsers while fullscreen is off.
slideshow?boolean | numberfalse` (4000 ms when enabled)Slideshow button. If a number is given, the duration of each item (ms); videos advance when they end.
captions?booleantrueShow the title and description at the bottom.
videoFrames?booleantrueFor videos without a cover image, the first frame is extracted in the browser and used as the cover in the thumbnail strip and the player. See VideoFrameImage.
actions?readonly LightboxAction[]Extra action buttons. See LightboxAction.

Type of a gallery item.

type GalleryMediaType = "image" | "video"

Status on the server: "uploading" (percentage via progress), "processing" (e.g. the video is being transcoded), "error" failed. Not given for a ready item.

type GalleryItemStatus = "uploading" | "processing" | "error"

GalleryItem

interface

An item of Gallery and Lightbox.

NameTypeDescription
id?stringUnique id; used for selection. If omitted, src is used.
srcstringFull-size image or video URL (opens in the full-screen view).
thumbnail?stringThumbnail shown in the grid. Give it to avoid downloading large files in the grid; if omitted, src is used for images and poster for videos.
type?GalleryMediaTypeType. If omitted, inferred from the URL extension (.mp4, .webm, .mov → video).
width?numberOriginal width and height (px). Only their ratio is used; if given, masonry and rows render correctly before the images load and the page doesn't shift. If omitted, the ratio is measured when the image loads.
height?numberOriginal height (px). See width.
alt?stringAlternative text of the image; for screen readers and search engines.
title?ReactNodeTitle; shown on top and in the caption in full screen.
description?ReactNodeDescription; shown at the bottom in full screen.
poster?stringCover image of the video.
preview?stringShort, light preview video played on mouse hover. If omitted, src is played muted.
duration?numberDuration of the video (seconds); shown in the corner like 1:24.
date?Date | string | numberDate; used for grouping with groupBy="day" | "month" | "year".
placeholder?stringColor shown until the image loads (e.g. the image's dominant color #8a9bb0) or a small blurred image (data:image/...).
srcSet?stringDifferent sizes of the image (<img srcset>); used in full screen.
disabled?booleanCannot be selected.
status?GalleryItemStatusStatus on the server. If given, a progress ring, "Processing" or an error is shown on the tile and the item doesn't open in full screen (it can be selected; e.g. to delete failed ones). While uploading, a local preview of the file (URL.createObjectURL) can be given as src.
progress?numberProgress while status="uploading", 0–1. If omitted, it spins indeterminately.
statusText?ReactNodeYour own text shown next to the status (e.g. "Compressing…", the error reason).

Built-in grouping: by day, month or year of the item's date field.

type GalleryGroupBy = "day" | "month" | "year"