Carousel Composer
alphav0.5.0Multi-item media post composer — drag in photos and videos, reorder them on a rail, alt text and upload status per item; image editing is an add-on.
Context
The authoring counterpart to the media-carousel viewer. The base owns the collection concerns — file intake (drop + multiple browse, MIME-inferred, an optional exact MIME allow-list and video length limit), the ordered MediaCarouselItem model (controlled or uncontrolled), the @dnd-kit reorderable thumbnail rail, the main preview, per-image alt text, host-owned upload status / progress / retry, and a poster frame + duration for each video. A video item's output is always the original file — nothing in the folder re-encodes video. Image editing is NOT in the base: the feature item `carousel-composer-editing` (into `features/editing/`) supplies an edit panel built on media-editor and is passed in through the `editing` prop, so a plain install pulls no media-editor or Konva; a host can also inject its own panel. Edits flatten on apply, so the rail and preview are always publish-ready; export() is pull-only. Intake is upload-only (`"library"` is ignored). Output is shaped to feed media-carousel. Primary downstream consumer: content-composer's post media slot (mediaCarouselSlot substrate), which wires the editing add-on.
Installation
pnpm dlx shadcn@latest initpnpm dlx shadcn@latest add @ilinxa/carousel-composerAdd -fixtures for dummy data:
pnpm dlx shadcn@latest add @ilinxa/carousel-composer-fixturespnpm dlx shadcn@latest add @ilinxa/carousel-composer-editingImage editing through media-editor — the edit panel, re-edit of earlier edits and typed readers for the edit fields, wired in through the editing prop.
CLI can't resolve @ilinxa? The namespace is listed in the official shadcn registry directory, so current CLIs need no configuration. If yours can't resolve it (older or pinned versions, self-hosted mirrors), register it manually in components.json:
"registries": {
"@ilinxa": "https://ui.ilinxa.com/r/{name}.json"
}Preview
Seeded from remote URLs (CMS re-edit). Select a thumb, drag to reorder, press Edit on any item. Videos can be previewed, reordered and removed, but not edited.
Demo source
"use client"; import * as React from "react";import { Tabs, TabsContent, TabsTrigger } from "@/components/ui/tabs";import { SwipeTabsList } from "@/components/site/swipe-tabs-list";import { Button, buttonVariants } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger,} from "@/components/ui/dialog";import { CarouselComposer } from "./carousel-composer";import type { CarouselComposerHandle, CarouselComposerLabelsInput, MediaCarouselItem,} from "./types";import { PLATFORM_SAFE_MIME } from "./types";import { carouselEditing } from "./features/editing";import { arabicLabels, dummyCarouselItems, dummyPanItems, dummyStatusItems, turkishLabels,} from "./dummy-data"; function Status({ children }: { children: React.ReactNode }) { return ( <p className="mt-3 font-mono text-xs text-muted-foreground">{children}</p> );} function EmptyTab() { const [count, setCount] = React.useState(0); return ( <div className="mx-auto max-w-md"> <CarouselComposer onChange={(items) => setCount(items.length)} editing={carouselEditing} enableAltText acceptMime={PLATFORM_SAFE_MIME} maxVideoSeconds={30} editorProps={{ enabledTools: ["crop", "filters", "adjust", "text"] }} /> <Status> Drop or browse photos + videos. {count} item{count === 1 ? "" : "s"}. </Status> </div> );} function SeededTab() { return ( <div className="mx-auto max-w-md"> <CarouselComposer defaultValue={dummyCarouselItems} editing={carouselEditing} editorProps={{ enabledTools: ["crop", "filters", "adjust"] }} /> <Status> Seeded from remote URLs (CMS re-edit). Select a thumb, drag to reorder, press Edit on any item. Videos can be previewed, reordered and removed, but not edited. </Status> </div> );} function ControlledTab() { const [items, setItems] = React.useState<MediaCarouselItem[]>([]); const ref = React.useRef<CarouselComposerHandle>(null); const [exported, setExported] = React.useState<number | null>(null); return ( <div className="mx-auto max-w-md"> <CarouselComposer ref={ref} value={items} onChange={setItems} /> <div className="mt-3 flex flex-wrap gap-2"> <Button size="sm" onClick={async () => { const out = await ref.current?.export(); setExported(out?.length ?? 0); }} > Export (publish) </Button> <Button size="sm" variant="ghost" onClick={() => ref.current?.reset()}> Reset </Button> </div> <Status> Controlled: {items.length} item{items.length === 1 ? "" : "s"} ·{" "} {items.filter((i) => i.kind === "image").length} photo /{" "} {items.filter((i) => i.kind === "video").length} video {exported !== null ? ` · last export → ${exported} items` : ""} </Status> </div> );} function MaxTab() { const [warn, setWarn] = React.useState<string | null>(null); return ( <div className="mx-auto max-w-md"> <CarouselComposer maxItems={3} defaultValue={dummyCarouselItems.slice(0, 2)} onMaxItemsExceeded={(attempted, max) => setWarn(`Tried ${attempted}, cap is ${max}.`) } /> <Status> Cap is 3. {warn ?? "Add more until the tile disappears."} </Status> </div> );} function StatusTab() { const [items, setItems] = React.useState<MediaCarouselItem[]>(dummyStatusItems); const [retries, setRetries] = React.useState(0); return ( <div className="mx-auto max-w-md"> <CarouselComposer value={items} onChange={setItems} onRetry={(item) => { setRetries((n) => n + 1); setItems((cur) => cur.map((it) => it.id === item.id ? { ...it, status: "uploading", progress: 0.1, error: undefined } : it, ), ); }} /> <Status> Host-owned upload state: item 1 is uploading at 40 %, item 2 failed. Select item 2 and press Retry ({retries} retries). </Status> </div> );} function AltVideoTab() { return ( <div className="mx-auto max-w-md"> <CarouselComposer defaultValue={dummyCarouselItems} enableAltText="all" /> <Status> enableAltText="all": select the video (item 3) and describe it; the preview video is named by that text. </Status> </div> );} function PanTab() { const ref = React.useRef<CarouselComposerHandle>(null); const [log, setLog] = React.useState("—"); const [crops, setCrops] = React.useState<string[]>([]); return ( <div className="mx-auto max-w-md"> <CarouselComposer ref={ref} defaultValue={dummyPanItems} defaultAspect="1:1" aspectOptions={["1:1", "4:5", "1.91:1"]} enablePan editing={carouselEditing} editorProps={{ enabledTools: ["crop", "filters", "adjust"] }} onCropOffsetChange={(id, o) => setLog(`${id} → ${o.x.toFixed(2)}, ${o.y.toFixed(2)}`)} /> <div className="mt-3"> <Button size="sm" onClick={async () => { const out = (await ref.current?.export()) ?? []; setCrops( out.map((it, i) => it.crop ? `#${i + 1} ${it.crop.width}x${it.crop.height} @${it.crop.x},${it.crop.y}` : `#${i + 1} no crop`, ), ); }} > Export </Button> </div> <Status> Drag the wide or tall photo inside the frame, or focus it and use the arrow keys (Shift = 20 %). The rail thumb follows. Pan, then Edit and Done: the framing survives the edit and the offset clears. onCropOffsetChange: {log} {crops.length ? ` · ${crops.join(" · ")}` : ""} </Status> </div> );} function ReorderTab() { const ref = React.useRef<CarouselComposerHandle>(null); const [log, setLog] = React.useState("—"); // The narrowest thumb (9:16) and a native RTL mount; the rail reads direction at mount, so // either switch remounts the composer. const [narrow, setNarrow] = React.useState(false); const [rtl, setRtl] = React.useState(false); return ( <div className="mx-auto max-w-md" dir={rtl ? "rtl" : undefined}> <CarouselComposer key={`${narrow}-${rtl}`} ref={ref} defaultValue={dummyCarouselItems} defaultAspect={narrow ? "9:16" : undefined} aspectOptions={narrow ? ["9:16"] : undefined} reorderButtons onMove={(id, d) => setLog(`${id} ${d > 0 ? "+" : ""}${d}`)} /> <div className="mt-3 flex flex-wrap gap-2"> <Button size="sm" onClick={() => ref.current?.moveItem("seed-1", 1)}> handle.moveItem(seed-1, +1) </Button> <Button size="sm" variant="outline" aria-pressed={narrow} onClick={() => setNarrow((v) => !v)}> Shared aspect 9:16 </Button> <Button size="sm" variant="outline" aria-pressed={rtl} onClick={() => setRtl((v) => !v)}> Mount under dir=rtl </Button> </div> <Status> Tab to a thumb: a move earlier / later pair appears on focus (logical direction, works in RTL). onMove: {log} </Status> </div> );} function EscapeTab() { const [open, setOpen] = React.useState(false); const [editing, setEditing] = React.useState(false); return ( <div className="mx-auto max-w-md"> <Dialog open={open} onOpenChange={setOpen}> {/* A real trigger: closing returns focus to it instead of <body>. */} <DialogTrigger className={buttonVariants({ size: "sm" })}> Open carousel in a dialog </DialogTrigger> <DialogContent className="max-w-lg"> <DialogTitle>Post media</DialogTitle> <DialogDescription>Add, reorder and edit the media for this post.</DialogDescription> <CarouselComposer defaultValue={dummyCarouselItems.slice(0, 2)} editing={carouselEditing} onEditingChange={setEditing} editorProps={{ enabledTools: ["crop", "filters", "adjust"] }} /> </DialogContent> </Dialog> <Status> Press Edit, then Escape while the editor loads or Done is exporting: the dialog stays open. When idle, Escape closes it as before. Editing now: {String(editing)}. </Status> </div> );} function LocaleTab({ dir, locale, labels, note,}: { dir: "ltr" | "rtl"; locale: string; labels: CarouselComposerLabelsInput; note: string;}) { return ( <div className="mx-auto max-w-md" dir={dir} lang={locale}> <CarouselComposer defaultValue={dummyCarouselItems.map((it) => it.kind === "video" ? { ...it, duration: 75 } : it, )} locale={locale} labels={labels} enableAltText /> <Status>{note}</Status> </div> );} function AspectTab() { const ref = React.useRef<CarouselComposerHandle>(null); const [log, setLog] = React.useState<string[]>([]); const [crops, setCrops] = React.useState<string[]>([]); return ( <div className="mx-auto max-w-md"> <CarouselComposer ref={ref} defaultValue={dummyCarouselItems} editing={carouselEditing} defaultAspect="original" aspectOptions={["original", "1:1", "4:5", "1.91:1"]} onAspectChange={(a) => setLog((l) => [...l.slice(-2), a])} editorProps={{ enabledTools: ["crop", "filters", "adjust"] }} /> <div className="mt-3 flex flex-wrap gap-2"> <Button size="sm" onClick={async () => { const out = (await ref.current?.export()) ?? []; setCrops( out.map((it, i) => it.crop ? `#${i + 1} ${it.crop.width}x${it.crop.height} @${it.crop.x},${it.crop.y}` : `#${i + 1} no crop`, ), ); }} > Export </Button> </div> <Status> Select item 1 to switch the shared aspect; every thumb, the preview and the editor follow. onAspectChange: {log.length ? log.join(" → ") : "—"} {crops.length ? ` · ${crops.join(" · ")}` : ""} </Status> </div> );} export default function CarouselComposerDemo() { const [tab, setTab] = React.useState("seeded"); return ( <Tabs value={tab} onValueChange={setTab} className="w-full"> <SwipeTabsList> <TabsTrigger value="empty">Empty</TabsTrigger> <TabsTrigger value="seeded">Seeded (re-edit)</TabsTrigger> <TabsTrigger value="controlled">Controlled + export</TabsTrigger> <TabsTrigger value="max">Max 3</TabsTrigger> <TabsTrigger value="aspect">Aspect switch</TabsTrigger> <TabsTrigger value="status">Upload status</TabsTrigger> <TabsTrigger value="alt-video">Alt for videos</TabsTrigger> <TabsTrigger value="pan">Pan</TabsTrigger> <TabsTrigger value="reorder">Reorder buttons</TabsTrigger> <TabsTrigger value="escape">Escape guard</TabsTrigger> <TabsTrigger value="tr">Türkçe</TabsTrigger> <TabsTrigger value="ar">العربية (RTL)</TabsTrigger> </SwipeTabsList> <TabsContent value="empty" className="pt-4"> <EmptyTab /> </TabsContent> <TabsContent value="seeded" className="pt-4"> <SeededTab /> </TabsContent> <TabsContent value="controlled" className="pt-4"> <ControlledTab /> </TabsContent> <TabsContent value="max" className="pt-4"> <MaxTab /> </TabsContent> <TabsContent value="aspect" className="pt-4"> <AspectTab /> </TabsContent> <TabsContent value="status" className="pt-4"> <StatusTab /> </TabsContent> <TabsContent value="alt-video" className="pt-4"> <AltVideoTab /> </TabsContent> <TabsContent value="pan" className="pt-4"> <PanTab /> </TabsContent> <TabsContent value="reorder" className="pt-4"> <ReorderTab /> </TabsContent> <TabsContent value="escape" className="pt-4"> <EscapeTab /> </TabsContent> <TabsContent value="tr" className="pt-4"> <LocaleTab dir="ltr" locale="tr" labels={turkishLabels} note="Turkish labels and tr-locale formatting. Turkish writes digits the same way as English, so the video length still reads 1:15." /> </TabsContent> <TabsContent value="ar" className="pt-4"> <LocaleTab dir="rtl" locale="ar-EG" labels={arabicLabels} note="Arabic labels, right-to-left rail, Arabic-Indic digits." /> </TabsContent> </Tabs> );} Usage
When to use
Reach for CarouselComposer when an author needs to assemble one or more media items into an ordered set — an Instagram-style feed post, an album, a product gallery, or chat attachments. It mixes photos and videos in a single rail, reorders by drag-and-drop, and can edit images through the optional editing add-on. For a single hero image/video, use media-editor directly; to display a finished set, use media-carousel.
Basic example
import { CarouselComposer, PLATFORM_SAFE_MIME, type MediaCarouselItem } from "@/components/carousel-composer";
export function PostMedia() {
const [items, setItems] = React.useState<MediaCarouselItem[]>([]);
return (
<CarouselComposer
value={items}
onChange={setItems}
maxItems={10}
acceptMime={PLATFORM_SAFE_MIME} // no WebM
maxVideoSeconds={60}
enableAltText
/>
);
}Image editing (add-on)
Editing is a separate registry item, so a plain install pulls no media-editor or Konva. Install @ilinxa/carousel-composer-editing and pass it in; without it there is no Edit button. canEditItem decides per item (videos are never edited — their output is the original file).
import { carouselEditing, type CarouselEditorProps } from "@/components/carousel-composer/features/editing";
const editorProps: CarouselEditorProps = { enabledTools: ["crop", "filters", "adjust"] };
<CarouselComposer
value={items}
onChange={setItems}
editing={carouselEditing}
editorProps={editorProps}
canEditItem={(item) => item.status !== "uploading"}
/>One shared aspect, any ratio
Every item shares the carousel's aspect — the preview, the rail thumbs, the edit panel and an edit's export follow it. aspectOptions shows a switch while item 1 is selected; enablePan lets the author drag a photo inside the frame (its cropOffset); export() gives each image the crop for the aspect — centred unless panned — so every item can be uploaded at it.
<CarouselComposer
value={items}
onChange={setItems}
aspect={aspect} // "original" | "1:1" | "4:5" | "1.91:1" | any "W:H" | "auto" | "free"
onAspectChange={setAspect}
aspectOptions={["original", "1:1", "4:5", "1.91:1"]}
enablePan // drag / arrow keys move the item's cropOffset
enableAltText="all" // videos get a description too
reorderButtons // move earlier / later, shown on hover or focus
onEditingChange={setEditing} // keep your dialog open while editing
editing={carouselEditing}
/>
const items = await ref.current.export(); // each image: crop = { x, y, width, height }
ref.current.moveItem(id, 1); // the same move without UIUpload status
Upload on add and write the state onto the item — the carousel shows a progress indicator, the error with a Retry, and announces each status change politely. Controlled hosts set it in value; uncontrolled hosts call ref.current.updateItem(id, patch).
const patch = (id, p) => setItems((prev) => prev.map((it) => (it.id === id ? { ...it, ...p } : it)));
async function upload(item) {
patch(item.id, { status: "uploading", progress: 0, error: undefined });
try {
const { url } = await api.upload(item.blob, { onProgress: (progress) => patch(item.id, { progress }) });
patch(item.id, { status: "uploaded", url });
} catch (e) {
patch(item.id, { status: "error", error: e.message });
}
}
<CarouselComposer value={items} onChange={setItems} onItemAdd={upload} onRetry={upload} />Labels and locale
Every string is in labels; strings that carry a value are functions. errors and drag merge key by key.
<CarouselComposer
locale="tr"
labels={{
dropzoneTitle: "Fotoğraf ve videoları buraya sürükleyin",
dropzoneHint: (max) => `veya en fazla ${max} dosya bırakın`,
maxReached: (max) => `En fazla ${max} öğe eklenebilir`,
itemAria: ({ position, total, kind }) => `${total} öğeden ${position}., ${kind === "video" ? "video" : "fotoğraf"}`,
errors: { videoTooLong: ({ maxSeconds }) => `Video en fazla ${maxSeconds} sn olabilir.` },
}}
/>Pull-only export
Edits flatten into each item on Done, so the rail and preview always show publish-ready media. Call ref.current.export() at publish time to get the committed ordered array (an open, unapplied edit is excluded — gate your publish button while editing).
Notes
- Intake is file-based — the file's MIME type decides
imagevsvideo, so there are no photo/video capture tabs."library"insourcesis ignored. - All items share one aspect (Instagram behaviour).
aspectdefaults to"auto"(derived from item 1); override with a fixedCarouselAspectRatio. - A video gets a JPEG poster frame (
posterAt, default 0.5 s;falsefor none) and a duration badge; the video itself is never re-encoded. - Object URLs created during intake / edit (items and posters) are revoked on remove, replace, reset, and unmount.
Features
- Multi-file intake — drag-and-drop dropzone + multiple Browse, mixed image + video (MIME-inferred, no capture-mode tabs)
- Type checks — `accept` kinds plus an exact `acceptMime` allow-list (also the file input's accept); `PLATFORM_SAFE_MIME` refuses WebM; `maxVideoSeconds` from the file's duration
- Ordered MediaCarouselItem model — add / remove / reorder / select; controlled `value` wins every render
- Reorderable thumbnail rail (@dnd-kit horizontal sortable) with pointer + keyboard reorder, a dedicated drag handle and labelled drag announcements
- Main preview of the selected item (image cover-fit; video on a media-overlay mat)
- Alt text (`enableAltText`, `maxAltLength`) — images by default; `"all"` or a per-item function describes videos too (the preview video is named by it); carried on the item through onChange
- Pan inside the shared frame (`enablePan`) — drag or arrow keys move an image's `cropOffset`; preview, rail thumb and `export()`'s `crop` follow it (`onCropOffsetChange`)
- Non-drag reorder (`reorderButtons`) — a move earlier / later pair per thumb (shown on thumb hover or when focused, logical in RTL, announced), `onMove`, handle `moveItem`
- Escape guard — while an edit panel reports busy (`onBusyChange`; the add-on reports its load and save) Escape never reaches a host dialog; `onEditingChange` lets a host gate its own dialog
- Host-owned upload status — `status` / `progress` / `error` on the item, a progress indicator on thumb and preview, Retry via `onRetry`, polite announcements on status changes, handle `updateItem`
- Video poster frame (JPEG `posterBlob` at `posterAt`) and a duration badge (`formatDuration` / `locale`); the video itself is never re-encoded
- Image editing as an opt-in add-on (`editing` prop, `@ilinxa/carousel-composer-editing`) — no Edit button and no media-editor in the install without it; `canEditItem` decides per item
- Shared aspect across the carousel (Instagram behaviour) — any media-editor crop aspect (named, `"original"` = item 1's ratio, `"W:H"` such as `"1.91:1"`); `"auto"` snaps item 1 to the nearest option; controlled (`aspect` + `onAspectChange`) or `defaultAspect`; an `aspectOptions` switch on item 1; preview, rail thumbs and the edit panel follow it, an edit exports at it, and `export()` reports each image's centred `crop`
- Imperative handle — getItems / export / addFiles / removeItem / moveItem / updateItem / select / openEditor / reset; pull-only export()
- Every string in `labels` (functions where a value varies); media-overlay tokens; logical (RTL-safe) layout
- Per-file type + size validation; maxItems cap (default 10, Instagram parity)
- Object-URL lifecycle managed (items and posters revoked on remove / replace / reset / unmount)