Image Drop
A slot for one image that becomes the picture when one lands: it squashes, springs back, and a line of light draws around the picture with a glow outside it in the accent and brand colours that lingers a moment, then fades. Drag the paired chip onto it, drop a file from the desktop, or click to pick one. A new picture dropped on a full slot replaces the old one.
Installation
npx shadcn@latest add https://ui.mattdowney.com/r/image-drop.jsonUsage
import { ImageDrop, ImageDropChip, ImageDropSlot } from "@/components/motion/image-drop"Examples
Default
Drag the chip onto the slot, or drop or pick an image file. Let go anywhere else and the chip springs home. Drop a file on the full slot to replace the picture. Clear it with its corner button and the chip comes back.
Cover photo
size="fill" takes the container's box, so a wide slot works for a cover or a canvas. The line of light follows the slot's shape and corner. Drag the sample picture in, or drop your own: a file stays in the browser and is never uploaded.
API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| src*ImageDropChip | string | None | The picture the chip carries. It becomes the slot's picture when it lands. |
| altImageDropChip, ImageDropSlot | string | None | On the chip, what the picture shows. On the slot, alt text for any landed picture, which wins over the chip's. |
| labelImageDropChip | string | "Use this image" | The chip's accessible name. Enter or Space on the chip places it in the slot. |
| sizeImageDropSlot | "sm" | "md" | "lg" | "fill" | "md" | Square at 80, 104 or 160px, or fill to take the container's box. |
| labelImageDropSlot | string | "Drop an image or browse" | The line in the empty slot, and its file input's accessible name. |
| acceptImageDropSlot | string | "image/*" | What a dropped or picked file may be, in the file input's own syntax. |
| maxSizeImageDropSlot | number | None | The largest file it takes, in bytes. |
| glowImageDropSlot | boolean | true | On landing, a line of light draws around the picture with a glow outside it in the accent and brand colours, lingers a moment and fades. It needs about 200px of room around the slot. Always off under reduced motion. |
| stillImageDropSlot | boolean | false | Land and clear without moving: the picture simply appears. |
| defaultSrcImageDropSlot | string | None | A picture already in the slot, shown still. |
| onDropImageDropSlot | (landing: ImageDropLanding) => void | None | A picture landed. Gets src, alt, and file when it came from the desktop or the picker; a file's src is an object URL the slot lets go when cleared. |
| onRejectImageDropSlot | (rejection: ImageDropRejection) => void | None | A file was turned away, with why: type or size. |
| onClearImageDropSlot | () => void | None | The slot was cleared with its corner button. |
| disabledImageDropSlot | boolean | false | Takes no chip and no file. |
| src*ImageDropChipstringThe picture the chip carries. It becomes the slot's picture when it lands. |
| altImageDropChip, ImageDropSlotstringOn the chip, what the picture shows. On the slot, alt text for any landed picture, which wins over the chip's. |
| labelImageDropChipstring = "Use this image"The chip's accessible name. Enter or Space on the chip places it in the slot. |
sizeImageDropSlot"sm" | "md" | "lg" | "fill" = "md"Square at 80, 104 or 160px, or fill to take the container's box. |
| labelImageDropSlotstring = "Drop an image or browse"The line in the empty slot, and its file input's accessible name. |
| acceptImageDropSlotstring = "image/*"What a dropped or picked file may be, in the file input's own syntax. |
| maxSizeImageDropSlotnumberThe largest file it takes, in bytes. |
| glowImageDropSlotboolean = trueOn landing, a line of light draws around the picture with a glow outside it in the accent and brand colours, lingers a moment and fades. It needs about 200px of room around the slot. Always off under reduced motion. |
| stillImageDropSlotboolean = falseLand and clear without moving: the picture simply appears. |
| defaultSrcImageDropSlotstringA picture already in the slot, shown still. |
onDropImageDropSlot(landing: ImageDropLanding) => voidA picture landed. Gets src, alt, and file when it came from the desktop or the picker; a file's src is an object URL the slot lets go when cleared. |
onRejectImageDropSlot(rejection: ImageDropRejection) => voidA file was turned away, with why: type or size. |
| onClearImageDropSlot() => voidThe slot was cleared with its corner button. |
| disabledImageDropSlotboolean = falseTakes no chip and no file. |
"use client"
import {
createContext,
useContext,
useEffect,
useLayoutEffect,
useRef,
useState,
type ComponentProps,
type DragEvent,
type RefObject,
} from "react";
import { IconX as X } from "@tabler/icons-react";
import { cn } from "@/registry/lib/utils";
import { playGlow, readNum } from "./image-drop-glow"
import "./image-drop.css"
/** What landed in the slot. `file` is set when it came from the desktop or the picker. */
export type ImageDropLanding = { src: string; alt: string; file?: File };
/** Why a file was turned away. */
export type ImageDropRejection = { file: File; reason: "type" | "size" };
type SlotHandle = {
el: HTMLElement;
/** Takes a landing now: empty, or full (a new picture replaces the old). */
open: () => boolean;
setOver: (on: boolean) => void;
land: (landing: ImageDropLanding, fromChip: boolean, byKey?: boolean) => void;
};
type ChipHandle = { respawn: () => void };
// Each half registers itself through a setter: a value read from context may
// not be written to directly (react-hooks/immutability).
type Pair = {
slot: RefObject<SlotHandle | null>;
chip: RefObject<ChipHandle | null>;
setSlot: (handle: SlotHandle | null) => void;
setChip: (handle: ChipHandle | null) => void;
};
const PairContext = createContext<Pair | null>(null);
function prefersReduced() {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
/** Whether `file` matches the file input's own `accept` syntax, as Dropzone reads it. */
function accepts(file: File, accept?: string) {
if (!accept?.trim()) return true;
const name = file.name.toLowerCase();
const type = file.type.toLowerCase();
return accept.split(",").some((raw) => {
const rule = raw.trim().toLowerCase();
if (!rule) return false;
if (rule.startsWith(".")) return name.endsWith(rule);
const [family, subtype] = rule.split("/");
if (subtype === "*") return type.startsWith(`${family}/`);
return type === rule;
});
}
/** Timers that all die together on unmount. */
function makeTimers() {
const ids = new Set<number>();
return {
after(ms: number, fn: () => void) {
const id = window.setTimeout(() => {
ids.delete(id);
fn();
}, ms);
ids.add(id);
},
clear() {
ids.forEach((id) => window.clearTimeout(id));
ids.clear();
},
};
}
/**
* Pairs one ImageDropSlot with the ImageDropChip that can be dragged onto it.
* Lays its two parts out in a row; pass a className to arrange them otherwise.
*/
export function ImageDrop({ className, ...props }: ComponentProps<"div">) {
const [pair] = useState<Pair>(() => {
const slot: RefObject<SlotHandle | null> = { current: null };
const chip: RefObject<ChipHandle | null> = { current: null };
return {
slot,
chip,
setSlot: (handle) => {
slot.current = handle;
},
setChip: (handle) => {
chip.current = handle;
},
};
});
return (
<PairContext value={pair}>
<div
data-slot="image-drop"
className={cn("flex items-center gap-(--spacing-rhythm-peer)", className)}
{...props}
/>
</PairContext>
);
}
/* The chip's drag, bound imperatively: every pointermove writes --dx and --dy
straight to the chip's style, since a re-render per frame would break 1:1
tracking. Settings are read when they are needed, so a live retune works
between drops. */
function createChipDrag(chip: HTMLElement, pair: Pair | null, src: () => ImageDropLanding, setLanded: (on: boolean) => void) {
const timers = makeTimers();
let dragging = false;
let settling = false;
let landed = false;
let pointerId: number | null = null;
let startX = 0;
let startY = 0;
// The JS mirror of --dx and --dy. It must reset with the CSS vars, or the
// chip teleports on the next grab.
let dx = 0;
let dy = 0;
let lastX = 0;
let lastT = 0;
let over = false;
function setVars(x: number, y: number, tilt: number | null, lift: number | null) {
chip.style.setProperty("--dx", x.toFixed(1) + "px");
chip.style.setProperty("--dy", y.toFixed(1) + "px");
if (tilt !== null) chip.style.setProperty("--tilt", tilt.toFixed(2) + "deg");
if (lift !== null) chip.style.setProperty("--lift", String(lift));
}
function slot() {
return pair?.slot.current ?? null;
}
// Hit test: the chip's centre inside the slot's box.
function overSlot() {
const s = slot();
if (!s || !s.open()) return false;
const c = chip.getBoundingClientRect();
const z = s.el.getBoundingClientRect();
const cx = c.left + c.width / 2;
const cy = c.top + c.height / 2;
return cx >= z.left && cx <= z.right && cy >= z.top && cy <= z.bottom;
}
function setOver(on: boolean) {
if (on === over) return;
over = on;
slot()?.setOver(on);
}
function land(byKey = false) {
settling = true;
landed = true;
chip.classList.add("is-fading");
setLanded(true);
slot()?.land(src(), true, byKey);
}
function onPointerDown(e: PointerEvent) {
if (dragging || settling || e.button !== 0) return;
dragging = true;
pointerId = e.pointerId;
try {
chip.setPointerCapture(e.pointerId);
} catch {}
startX = e.clientX - dx;
startY = e.clientY - dy;
lastX = e.clientX;
lastT = performance.now();
chip.classList.remove("is-returning", "is-respawning");
chip.classList.add("is-dragging");
chip.style.setProperty("--lift", prefersReduced() ? "1" : String(readNum(chip, "--image-drop-lift-scale", 1.05)));
}
function onPointerMove(e: PointerEvent) {
if (!dragging || e.pointerId !== pointerId) return;
dx = e.clientX - startX;
dy = e.clientY - startY;
const now = performance.now();
const dt = Math.max(now - lastT, 1);
const vx = (e.clientX - lastX) / dt; // px per ms
lastX = e.clientX;
lastT = now;
// Tilt from horizontal speed only: about 28deg per px/ms, clamped.
const max = readNum(chip, "--image-drop-tilt-max", 10);
const tilt = prefersReduced() ? 0 : Math.max(-max, Math.min(max, vx * 28));
setVars(dx, dy, tilt, null);
setOver(overSlot());
}
function release(e: PointerEvent) {
if (!dragging || e.pointerId !== pointerId) return;
dragging = false;
chip.classList.remove("is-dragging");
const dropIn = over && overSlot();
setOver(false);
if (dropIn) {
setVars(dx, dy, 0, null); // level the tilt as it fades
land();
return;
}
settling = true;
dx = 0;
dy = 0;
if (prefersReduced()) {
setVars(0, 0, 0, 1);
settling = false;
return;
}
chip.classList.add("is-returning");
setVars(0, 0, 0, 1);
timers.after(readNum(chip, "--image-drop-return-dur", 500) + 50, () => {
chip.classList.remove("is-returning");
settling = false;
});
}
// Enter or Space on the chip places it, for anyone not using a pointer.
function onClick(e: MouseEvent) {
if (e.detail !== 0 || dragging || settling) return;
// Placed from the keyboard, focus moves on to the slot's clear button,
// since the chip is now gone from view.
if (slot()?.open()) land(true);
}
chip.addEventListener("pointerdown", onPointerDown);
chip.addEventListener("pointermove", onPointerMove);
chip.addEventListener("pointerup", release);
chip.addEventListener("pointercancel", release);
chip.addEventListener("click", onClick);
return {
// The slot was cleared: the chip comes back to where it started.
respawn() {
if (!landed) return;
landed = false;
dx = 0;
dy = 0;
setVars(0, 0, 0, 1);
chip.classList.remove("is-fading");
setLanded(false);
if (prefersReduced()) {
settling = false;
return;
}
void chip.offsetWidth; // reflow, so the respawn animation restarts
chip.classList.add("is-respawning");
timers.after(readNum(chip, "--image-drop-respawn-dur", 250) + 50, () => {
chip.classList.remove("is-respawning");
settling = false;
});
},
destroy() {
timers.clear();
if (over) slot()?.setOver(false);
chip.removeEventListener("pointerdown", onPointerDown);
chip.removeEventListener("pointermove", onPointerMove);
chip.removeEventListener("pointerup", release);
chip.removeEventListener("pointercancel", release);
chip.removeEventListener("click", onClick);
},
};
}
export type ImageDropChipProps = Omit<ComponentProps<"button">, "children"> & {
src: string;
/** What the picture shows. It becomes the landed picture's alt text. */
alt?: string;
/** The button's accessible name. Default "Use this image". */
label?: string;
};
/**
* An image with weight: it lifts on grab, tilts with how fast it moves, and
* springs home when let go anywhere but the slot. Let go over the slot, it
* fades where it was dropped while the slot becomes the picture. Enter or
* Space places it too. It comes back when the slot is cleared.
*/
export function ImageDropChip({ src, alt = "", label = "Use this image", className, ...props }: ImageDropChipProps) {
const pair = useContext(PairContext);
const ref = useRef<HTMLButtonElement>(null);
const [landed, setLanded] = useState(false);
// Synced after render, never during it: render may not write a ref.
const latest = useRef({ src, alt });
useLayoutEffect(() => {
latest.current = { src, alt };
});
useEffect(() => {
const chip = ref.current;
if (!chip) return;
const ctrl = createChipDrag(chip, pair, () => ({ ...latest.current }), setLanded);
pair?.setChip({ respawn: ctrl.respawn });
return () => {
ctrl.destroy();
pair?.setChip(null);
};
}, [pair]);
return (
<button
ref={ref}
type="button"
data-slot="image-drop-chip"
aria-label={label}
// Landed, the chip is gone from view, so it leaves the tab order too.
aria-hidden={landed || undefined}
tabIndex={landed ? -1 : undefined}
className={cn("motion-image-drop-chip", className)}
{...props}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={src} alt="" draggable={false} />
</button>
);
}
export type ImageDropSlotProps = Omit<ComponentProps<"div">, "children" | "onDrop"> & {
/** `sm` 80px, `md` 104px, `lg` 160px, all square; `fill` takes the container's box, for a cover photo or a canvas slot. Default `md`. */
size?: "sm" | "md" | "lg" | "fill";
/** The line in the empty slot, and the file input's accessible name. */
label?: string;
/** What it takes, in the file input's own syntax. Default `image/*`. */
accept?: string;
/** The largest file it takes, in bytes. */
maxSize?: number;
disabled?: boolean;
/** The line of light that draws around the picture on landing, glows outside it, lingers and fades. Default on; always off under reduced motion. */
glow?: boolean;
/** Land and clear without moving: the picture simply appears. */
still?: boolean;
/** A picture already in the slot. It shows still, with no landing. */
defaultSrc?: string;
/** Alt text for a landed picture. A chip's own `alt` is used when this is absent. */
alt?: string;
/** The clear button's accessible name. Default "Remove image". */
clearLabel?: string;
/** A picture landed, from the chip or a file. A file's `src` is an object URL the slot revokes when it is cleared. */
onDrop?: (landing: ImageDropLanding) => void;
/** A dropped or picked file was turned away. */
onReject?: (rejection: ImageDropRejection) => void;
/** The slot was cleared. */
onClear?: () => void;
};
// `id` keys the picture's img, so a replaced picture keeps its own element
// while the new one fades in over it. `fromChip` stays true while the chip is
// spent into this slot, even after a file replaces its picture, so clearing
// still brings the chip back.
type Shown = ImageDropLanding & { id: number; fromChip: boolean; objectUrl: boolean; preset?: boolean };
let nextShownId = 1;
// @use-when a drop slot for one image that becomes the picture when it lands,
// with a squash, a spring and a line of light that draws around it and glows
// outward: an avatar, a cover photo, a canvas slot. Pairs with a draggable image chip; also takes a dropped or
// picked file. For a plain upload field, Dropzone.
/**
* A slot for one image. A file dropped from the desktop, a file picked with a
* click, Enter or Space, or the paired chip all land the same way: the slot
* cross-fades into the picture, squashes, springs back and, at the bottom of
* the squash, a line of light draws around the picture with a glow outside it
* in the accent and brand colours, lingers a moment and fades. The glow needs
* about 200px of room around the slot at its default reach. A new picture
* dropped on a full slot replaces the old one and lands the same way. The
* picture stays until cleared, and clearing blurs it away.
*/
export function ImageDropSlot({
size = "md",
label = "Drop an image or browse",
accept = "image/*",
maxSize,
disabled = false,
glow = true,
still = false,
defaultSrc,
alt,
clearLabel = "Remove image",
onDrop,
onReject,
onClear,
className,
...props
}: ImageDropSlotProps) {
const pair = useContext(PairContext);
const ref = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const [shown, setShown] = useState<Shown | null>(() =>
defaultSrc ? { id: 0, src: defaultSrc, alt: alt ?? "", fromChip: false, objectUrl: false, preset: true } : null,
);
// A replaced picture, held under the new one until the new one has faded in,
// so there is never a blank frame. Its file's object URL goes with it.
const [previous, setPrevious] = useState<Shown | null>(null);
const previousRef = useRef<Shown | null>(null);
const previousTimer = useRef(0);
const [phase, setPhase] = useState<"empty" | "filled" | "emptying">(defaultSrc ? "filled" : "empty");
const [over, setOver] = useState(false);
const [announce, setAnnounce] = useState("");
const depth = useRef(0);
const pendingLand = useRef(false);
const refocus = useRef(false);
const focusClear = useRef(false);
const clearRef = useRef<HTMLButtonElement>(null);
const [timers] = useState(makeTimers);
// Ends the glow that is playing, if one is.
const stopGlow = useRef<(() => void) | null>(null);
// Read when needed, so changed props are never missed by the handlers below.
// Synced after render, never during it: render may not write a ref. A
// landing also mirrors itself here at once (see `land`).
const latest = useRef({ phase, shown, disabled, glow, still, alt, onDrop, onClear });
useLayoutEffect(() => {
latest.current = { phase, shown, disabled, glow, still, alt, onDrop, onClear };
});
function dropPrevious() {
window.clearTimeout(previousTimer.current);
const was = previousRef.current;
if (was?.objectUrl) URL.revokeObjectURL(was.src);
previousRef.current = null;
setPrevious(null);
}
function land(landing: ImageDropLanding, fromChip: boolean, objectUrl = false, byKey = false) {
const l = latest.current;
// Mid-clear, a landing would race the clear, so it is refused.
if (l.phase === "emptying" || l.disabled) {
if (objectUrl) URL.revokeObjectURL(landing.src);
return;
}
const final = { ...landing, alt: l.alt ?? landing.alt };
const old = l.phase === "filled" ? l.shown : null;
const next: Shown = { ...final, id: nextShownId++, fromChip: fromChip || !!old?.fromChip, objectUrl };
if (old) {
// A picture already there: it stays under the new one for the fade in,
// then goes. One still waiting from an earlier swap goes now.
dropPrevious();
previousRef.current = old;
setPrevious(old);
const el = ref.current;
const hold = l.still || prefersReduced() || !el ? 0 : readNum(el, "--image-drop-fade-in", 400);
previousTimer.current = window.setTimeout(dropPrevious, hold + 50);
}
pendingLand.current = true;
focusClear.current = byKey;
// Mirror the state now, so a second drop in the same frame sees it.
latest.current = { ...l, phase: "filled", shown: next };
setShown(next);
setPhase("filled");
setAnnounce(old ? "Image replaced" : "Image added");
l.onDrop?.(final);
}
// The pair finds this slot through the wrapper, with the latest handlers.
useEffect(() => {
const el = ref.current;
if (!pair || !el) return;
pair.setSlot({
el,
open: () => latest.current.phase !== "emptying" && !latest.current.disabled,
setOver: (on) => el.classList.toggle("is-over", on),
land: (landing, fromChip, byKey) => land(landing, fromChip, false, byKey),
});
return () => {
pair.setSlot(null);
};
});
function endGlow() {
stopGlow.current?.();
stopGlow.current = null;
}
// A landing plays once the picture is in the DOM.
useLayoutEffect(() => {
const el = ref.current;
if (!pendingLand.current || !el) return;
pendingLand.current = false;
if (latest.current.still || prefersReduced()) return;
timers.clear();
endGlow();
el.classList.remove("is-landing");
void el.offsetWidth; // reflow, so the squash restarts
el.classList.add("is-landing");
if (!latest.current.glow) return;
// Fire at the bottom of the squash: the surface compresses and the light
// runs out around the picture's edge.
const at = readNum(el, "--image-drop-down-dur", 250) + readNum(el, "--image-drop-glow-delay", 0);
timers.after(at, () => {
stopGlow.current = playGlow(el);
});
}, [shown, timers]);
// The squash holds its end state; drop the class (and its will-change) once
// the spring has settled.
useEffect(() => {
const el = ref.current;
if (!el) return;
function onEnd(e: AnimationEvent) {
if (e.target === el && e.animationName === "motion-image-drop-up") el?.classList.remove("is-landing");
}
el.addEventListener("animationend", onEnd);
return () => el.removeEventListener("animationend", onEnd);
}, []);
// Back to empty after a clear, focus returns to the slot's own control; a
// chip placed from the keyboard (into an empty slot or over a picture)
// hands focus on to the clear button.
useEffect(() => {
if (phase === "empty" && refocus.current) {
refocus.current = false;
inputRef.current?.focus();
}
if (phase === "filled" && focusClear.current) {
focusClear.current = false;
clearRef.current?.focus();
}
}, [phase, shown]);
// Unmount: timers and the glow stop, and a file's object URL is let go.
const shownRef = useRef(shown);
useLayoutEffect(() => {
shownRef.current = shown;
});
useEffect(
() => () => {
timers.clear();
stopGlow.current?.();
window.clearTimeout(previousTimer.current);
if (shownRef.current?.objectUrl) URL.revokeObjectURL(shownRef.current.src);
if (previousRef.current?.objectUrl) URL.revokeObjectURL(previousRef.current.src);
},
[timers],
);
function clear() {
const el = ref.current;
const l = latest.current;
if (l.phase !== "filled" || !el) return;
timers.clear();
endGlow();
dropPrevious();
el.classList.remove("is-landing");
refocus.current = true;
const finish = () => {
const was = latest.current.shown;
if (was?.objectUrl) URL.revokeObjectURL(was.src);
setShown(null);
setPhase("empty");
setAnnounce("Image removed");
if (was?.fromChip) pair?.chip.current?.respawn();
latest.current.onClear?.();
};
if (l.still || prefersReduced()) {
finish();
return;
}
setPhase("emptying");
timers.after(readNum(el, "--image-drop-out-dur", 400) + 50, finish);
}
function take(list: FileList | null) {
const file = list?.[0];
if (!file || disabled || latest.current.phase === "emptying") return;
if (!accepts(file, accept)) return onReject?.({ file, reason: "type" });
if (maxSize !== undefined && file.size > maxSize) return onReject?.({ file, reason: "size" });
land({ src: URL.createObjectURL(file), alt: "", file }, false, true);
}
// Empty or full, the slot takes a drop: a new picture replaces the old.
const open = phase !== "emptying" && !disabled;
// dragenter and dragleave fire for every child crossed, so count them.
function onDragEnter(e: DragEvent<HTMLDivElement>) {
e.preventDefault();
if (!open) return;
depth.current += 1;
setOver(true);
}
function onDragOver(e: DragEvent<HTMLDivElement>) {
// Always claim the drag, so a file let go on a disabled or clearing slot
// is refused here instead of the browser opening it.
e.preventDefault();
if (!open) e.dataTransfer.dropEffect = "none";
}
function onDragLeave() {
depth.current = Math.max(0, depth.current - 1);
if (depth.current === 0) setOver(false);
}
function onDropFile(e: DragEvent<HTMLDivElement>) {
e.preventDefault();
depth.current = 0;
setOver(false);
if (open) take(e.dataTransfer.files);
}
return (
<div
ref={ref}
data-slot="image-drop-slot"
data-size={size}
data-state={phase}
data-drag-over={over && open ? "" : undefined}
data-disabled={disabled ? "" : undefined}
data-still={still || undefined}
onDragEnter={onDragEnter}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDropFile}
{...props}
className={cn("motion-image-drop-slot", className)}
>
<span className="motion-image-drop-label" aria-hidden="true">
{label}
</span>
{/* One keyed list, so a replaced picture keeps its own element (no
second fade) and sits under the new one, which paints after it. */}
{[previous, shown].map((pic) =>
pic ? (
// eslint-disable-next-line @next/next/no-img-element
<img
key={pic.id}
className="motion-image-drop-image"
src={pic.src}
alt={pic === shown ? pic.alt : ""}
aria-hidden={pic === shown ? undefined : true}
// A picture there from the start shows at once, with no fade in.
data-preset={pic.preset || undefined}
/>
) : null,
)}
{phase === "empty" ? (
<input
ref={inputRef}
type="file"
accept={accept}
disabled={disabled}
aria-label={label}
className="motion-image-drop-input"
onChange={(e) => {
take(e.target.files);
// The same file again still fires a change.
e.target.value = "";
}}
/>
) : (
<button
ref={clearRef}
type="button"
className="motion-image-drop-clear"
data-preset={shown?.preset || undefined}
aria-label={clearLabel}
disabled={phase === "emptying"}
onClick={clear}
>
<X aria-hidden="true" />
</button>
)}
{/* Polite live region: says when a picture lands or leaves. */}
<span className="motion-image-drop-sr" role="status" aria-live="polite">
{announce}
</span>
</div>
);
}type Triple = [number, number, number];
/* The landing glow for image-drop: a line of light draws around the picture
from the top centre, both ways at once, with a bright head on each front,
and a soft aurora fades in behind it, hanging outside the line. Then it
lingers: the light keeps flowing, unevenly, with swells drifting along the
frame, before the whole layer fades out.
It is drawn by one WebGL2 fragment shader on a canvas that overhangs the
slot and sits under the picture. The canvas and its GPU context exist only
while the glow plays: made when it fires, thrown away when it ends, so a
page of idle slots holds no contexts (browsers cap them). With no WebGL2,
or a lost context, there is simply no glow. */
const MAX_IDLE = 6;
// The intro, in seconds: the line draws for 1.8, the glow is revealed from
// 0.35 over 2.1, and the head has faded by 2.1.
const INTRO_TIME = 2.6;
// How fast the noise runs along the frame at flow speed 1, in px per second.
const FLOW_RATE = 34;
const VERTEX = `#version 300 es
void main() {
// One triangle that covers the canvas, built from the vertex index.
vec2 corner = vec2(float((gl_VertexID & 1) << 2), float((gl_VertexID & 2) << 1));
gl_Position = vec4(corner - 1.0, 0.0, 1.0);
}`;
/* Distances are in CSS px, measured from the centre of the canvas, which is
the centre of the picture. `d` is the signed distance to the line's path (a
rounded rectangle just outside the picture's edge): negative inside,
positive outside. Everything that spreads (the glow, the tight bloom under
the head, the grain's depth) is measured outward from the line, so the
light hangs outside the frame and the picture stays untouched. */
const FRAGMENT = `#version 300 es
precision highp float;
precision highp int;
uniform vec2 uSize;
uniform float uDpr;
uniform vec2 uHalf;
uniform float uRadius;
uniform vec4 uPath;
uniform float uLine;
uniform float uOuter;
uniform float uGlow;
uniform float uReach;
uniform float uNoise;
uniform float uCells;
uniform float uGrains;
uniform float uOctaves;
uniform vec4 uDrift;
uniform float uPhase;
uniform vec3 uLch1;
uniform vec3 uLch2;
uniform vec3 uLch3;
uniform vec3 uBack;
uniform float uInk;
uniform float uExposure;
uniform float uIntensity;
uniform float uOpacity;
uniform float uSoft;
uniform float uWisp;
uniform vec2 uWispCells;
uniform float uFilaments;
uniform float uExtent;
uniform float uGrain;
uniform float uSeed;
uniform vec4 uIntro;
uniform vec2 uIdle[${MAX_IDLE}];
out vec4 fragColor;
const float TAU = 6.28318530718;
const float QUARTER = 1.57079632679;
float lattice(ivec2 c) {
uvec2 q = uvec2(c) * uvec2(1597334673u, 3812015801u);
uint n = (q.x ^ q.y) * 1597334673u;
return float(n) * (TAU / 4294967296.0);
}
// Gradient noise that repeats every period cells along x, so it joins up all
// the way round the frame with no seam.
float loopNoise(vec2 p, int period) {
vec2 i = floor(p);
vec2 f = p - i;
vec2 w = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
ivec2 c = ivec2(i);
int x0 = (c.x + period * 64) % period;
int x1 = (x0 + 1) % period;
float a = lattice(ivec2(x0, c.y));
float b = lattice(ivec2(x1, c.y));
float e = lattice(ivec2(x0, c.y + 1));
float g = lattice(ivec2(x1, c.y + 1));
float va = dot(vec2(cos(a), sin(a)), f);
float vb = dot(vec2(cos(b), sin(b)), f - vec2(1.0, 0.0));
float ve = dot(vec2(cos(e), sin(e)), f - vec2(0.0, 1.0));
float vg = dot(vec2(cos(g), sin(g)), f - vec2(1.0, 1.0));
return mix(mix(va, vb, w.x), mix(ve, vg, w.x), w.y) * 1.414;
}
float roundBox(vec2 p, vec2 b, float r) {
vec2 q = abs(p) - b + r;
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
}
// Distance travelled along the frame, clockwise from the top-left end of the
// top edge, for the nearest point on a rounded rectangle with straight
// halves uPath.xy and corner radius uPath.z. Works on either side of the line.
float along(vec2 p) {
vec2 h = uPath.xy;
float r = uPath.z;
float arc = QUARTER * r;
vec2 q = abs(p) - h;
if (q.x > 0.0 && q.y > 0.0) {
float a = atan(q.y, q.x);
if (p.x >= 0.0 && p.y >= 0.0) return 2.0 * h.x + (QUARTER - a) * r;
if (p.x >= 0.0) return 2.0 * h.x + arc + 2.0 * h.y + a * r;
if (p.y < 0.0) return 4.0 * h.x + 2.0 * arc + 2.0 * h.y + (QUARTER - a) * r;
return 4.0 * h.x + 3.0 * arc + 4.0 * h.y + a * r;
}
if (q.y >= q.x) return p.y >= 0.0 ? p.x + h.x : 3.0 * h.x + 2.0 * arc + 2.0 * h.y - p.x;
return p.x >= 0.0 ? 2.0 * h.x + arc + h.y - p.y : 4.0 * h.x + 3.0 * arc + 3.0 * h.y + p.y;
}
// The glow's falloff: a sharp exponential near the line over a long soft
// one, eased to nothing by the reach.
float profile(float x, float reach) {
float t = max(x, 0.0);
float shape = 0.4 * exp(-t / (0.07 * reach)) + 0.6 * exp(-t / (0.28 * reach));
return shape * (1.0 - smoothstep(0.35 * reach, reach, t));
}
// Between two OKLCH colours, the hue the short way round, so a blend never
// cuts across the middle of the wheel through grey.
vec3 mixLch(vec3 a, vec3 b, float t) {
float turn = mod(b.z - a.z + 0.5 * TAU, TAU) - 0.5 * TAU;
return vec3(mix(a.xy, b.xy, t), a.z + turn * t);
}
// OKLCH (hue in radians) to linear sRGB, with the published OKLab matrices.
vec3 fromLch(vec3 lch) {
vec3 lab = vec3(lch.x, lch.y * cos(lch.z), lch.y * sin(lch.z));
vec3 lms = mat3(1.0, 1.0, 1.0, 0.3963377774, -0.1055613458, -0.0894841775, 0.2158037573, -0.0638541728, -1.291485548) * lab;
lms = lms * lms * lms;
return max(mat3(4.0767416621, -1.2684380046, -0.0041960863, -3.3077115913, 2.6097574011, -0.7034186147, 0.2309699292, -0.3413193965, 1.707614701) * lms, 0.0);
}
vec3 encode(vec3 c) {
c = clamp(c, 0.0, 1.0);
return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
}
void main() {
vec2 p = gl_FragCoord.xy / uDpr - 0.5 * uSize;
float fw = 1.0 / uDpr;
float d = roundBox(p, uHalf, uRadius);
float hw = 0.5 * uLine;
// Beyond the glow's furthest reach, or inside the picture: nothing.
if (d - hw > uExtent || -d - hw > uOuter + fw) {
fragColor = vec4(0.0);
return;
}
float perimeter = uPath.w;
float halfP = 0.5 * perimeter;
float s = along(p);
int cells = int(uCells + 0.5);
float n = loopNoise(vec2((s - uDrift.x) / perimeter * uCells, uDrift.z), cells);
float weight = 1.0;
if (uOctaves > 1.5) {
float u2 = (s - uDrift.y) / perimeter * uCells * 2.0 + 3.0;
n += 0.45 * loopNoise(vec2(u2, uDrift.z * 1.7 + 11.0), cells * 2);
weight += 0.45;
}
if (uOctaves > 2.5) {
float u3 = (s - uDrift.y) / perimeter * uCells * 4.0 + 7.0;
n += 0.2 * loopNoise(vec2(u3, uDrift.z * 2.3 + 23.0), cells * 4);
weight += 0.2;
}
n /= weight;
float v = smoothstep(-0.55, 0.55, n) * 2.0 - 1.0;
// The grain through the glow, its depth measured outward.
int grains = int(uGrains + 0.5);
float depth = max(roundBox(p, uHalf, uPath.z), 0.0);
vec2 tp = vec2(s - uDrift.w, depth * 2.4) / perimeter * uGrains + vec2(0.0, uDrift.z * 0.8);
float warp = loopNoise(tp + vec2(0.0, 17.0), grains);
float tex = loopNoise(tp + vec2(0.6 * warp, 0.35 * warp), grains);
float startDist = abs(mod(s - uIntro.x * perimeter + halfP, perimeter) - halfP);
float drawn = 1.0 - smoothstep(uIntro.y - 4.0, uIntro.y + 4.0, startDist);
float reveal = 1.0 - smoothstep(uIntro.z - uSoft, uIntro.z, startDist);
float swell = 0.0;
float idleW = 0.022 * perimeter;
for (int i = 0; i < ${MAX_IDLE}; i++) {
vec2 bump = uIdle[i];
if (bump.y <= 0.0) continue;
float dist = abs(mod(s - bump.x * perimeter + halfP, perimeter) - halfP);
swell += bump.y * exp(-dist * dist / (2.0 * idleW * idleW)) * (1.0 - smoothstep(2.0 * idleW, 3.0 * idleW, dist));
}
swell = min(swell, 1.5) * reveal;
float outer = max(d - hw, 0.0);
// Wisps: the glow's outer shape made irregular, so it never reads as a
// tidy offset of the rounded rectangle. Cell sizes come from the reach in
// pixels, not the frame's noise cells, so a small slot gets as much detail
// as a large one. First, how far it reaches varies round the frame: broad
// lobes and finer wisps, drifting slowly with the flow.
float lobe = loopNoise(vec2((s - 0.5 * uDrift.x) / perimeter * uWispCells.x, uDrift.z * 0.6 + 41.0), int(uWispCells.x + 0.5));
float strand = loopNoise(vec2((s - 0.8 * uDrift.y) / perimeter * uWispCells.y + 5.0, uDrift.z * 1.1 + 59.0), int(uWispCells.y + 0.5));
float reachMul = clamp(1.0 + uWisp * (0.4 * lobe + 0.2 * strand), 0.45, 1.4);
// Then the distance the falloff is measured on is bent by flowing noise:
// nothing at the line, growing outward. One layer is stretched outward
// (fine filaments that fan from the frame and creep out over time), one is
// plain 2D in pixels (so the filaments wander instead of radiating evenly).
float ramp = smoothstep(0.0, 0.6 * uReach, outer);
vec2 fq = vec2((s - 0.3 * uDrift.w) / perimeter * uFilaments, outer / (0.45 * uReach) - uDrift.z * 0.7);
float f1 = loopNoise(fq + vec2(0.0, 71.0), int(uFilaments + 0.5));
vec2 pq = p / (0.22 * uReach) + vec2(uDrift.z * 1.3, -uDrift.z);
float f2 = loopNoise(pq + vec2(0.0, 0.8 * f1), 4096);
float outerW = max(outer + uWisp * 0.3 * uReach * ramp * (0.6 * f1 + 0.4 * f2), 0.0);
// Last, the far part of the falloff dissolves through finer noise, so
// there is no single outer line anywhere.
float f3 = loopNoise(pq * 2.1 + vec2(13.0, 0.6 * f1), 4096);
float dissolve = clamp(0.5 + 1.2 * f3 + 0.4 * f1, 0.0, 1.0);
float lineAmp = 1.0 + uNoise * 0.4 * v;
float glowAmp = max(1.0 + uNoise * v, 0.0);
float grainy = max(1.0 + uNoise * tex * (0.45 + 0.55 * smoothstep(0.0, 0.4 * uReach, outer)), 0.0);
float reach = uReach * (1.0 + uNoise * 0.25 * v) * (1.0 + uNoise * 0.15 * tex) * (1.0 + 0.2 * min(swell, 1.0)) * reachMul;
float width = max(uLine, fw);
float line = clamp((0.5 * width - abs(d)) / fw + 0.5, 0.0, 1.0) * (uLine / width);
float off = max(abs(d) - hw, 0.0);
float spread = 1.5 + 1.2 * uLine;
float halo = exp(-off / spread) * (1.0 - smoothstep(4.0 * spread, 10.0 * spread, off)) * min(uLine, 1.0);
// The line's own bloom stops at the picture's edge (the inset is the gap).
if (d < 0.0) halo *= 1.0 - smoothstep(0.0, max(uOuter, 0.001), off);
// The glow hangs outside the line, on the bent distance. Right at the line
// the bend is zero, so it still hugs the line evenly.
float body = profile(outerW, reach);
body *= mix(1.0, dissolve, uWisp * smoothstep(0.3 * reach, reach, outerW));
float tight = profile(outer, reach * 0.32);
float outside = clamp(d / fw + 0.5, 0.0, 1.0);
float headW = 14.0 + 2.0 * uLine;
float introDelta = startDist - uIntro.y;
float pulseLine = uIntro.w * exp(-introDelta * introDelta / (headW * headW));
float pulseGlow = uIntro.w * 0.7 * exp(-introDelta * introDelta / (25.0 * headW * headW));
// Three colours round the frame, 1 to 2 to 3 and back to 1, travelling
// with the phase and nudged by the noise. Each stretch eases in and out, so
// every colour has a moment to itself and the loop has no seam.
float around = fract(s / perimeter + (0.9 * uNoise * v - uPhase) / TAU) * 3.0;
float leg = floor(around);
float k = smoothstep(0.0, 1.0, around - leg);
vec3 lch = leg < 0.5 ? mixLch(uLch1, uLch2, k) : leg < 1.5 ? mixLch(uLch2, uLch3, k) : mixLch(uLch3, uLch1, k);
float lineLight = line * ((1.25 * lineAmp + 0.9 * swell) * drawn + 2.2 * pulseLine);
float haloLight = halo * ((0.25 * lineAmp + 0.3 * swell) * drawn + 0.7 * pulseLine);
float glowLight = outside * (body * uGlow * (glowAmp + 0.8 * swell) * grainy * reveal + tight * pulseGlow);
vec3 color;
float alpha;
if (uInk > 0.5) {
// A light page: a fine inked line and a tinted glow.
vec3 ink = encode(fromLch(vec3(clamp(lch.x * 0.8, 0.36, 0.6), lch.y * 1.12 + 0.02, lch.z)));
vec3 tint = encode(fromLch(vec3(clamp(lch.x * 0.92 + 0.06, 0.55, 0.78), lch.y * 1.05 + 0.01, lch.z)));
float aLine = clamp(line * ((0.55 + 0.35 * lineAmp + 0.35 * swell) * drawn + 0.9 * pulseLine) * min(uIntensity, 1.5), 0.0, 1.0);
float soft = (glowLight + haloLight * 0.6) * uIntensity;
float aGlow = clamp(pow(soft, 1.3) * 0.6, 0.0, 0.7);
alpha = aLine + aGlow * (1.0 - aLine);
color = alpha > 0.0001 ? (ink * aLine + tint * aGlow * (1.0 - aLine)) / alpha : tint;
} else {
// A dark page: light, exposed so it rolls off instead of clipping, and
// written so that over the page colour it adds up like a screen.
vec3 tone = encode(fromLch(lch));
tone /= max(max(tone.r, max(tone.g, tone.b)), 0.45);
vec3 deep = encode(fromLch(vec3(lch.x * 0.86, lch.y * 1.3 + 0.02, lch.z)));
deep /= max(max(deep.r, max(deep.g, deep.b)), 0.45);
vec3 emission = (tone * (lineLight + haloLight) + deep * glowLight) * uIntensity;
vec3 shown = 1.0 - exp(-emission * uExposure);
alpha = max(shown.r, max(shown.g, shown.b));
color = alpha > 0.0001 ? shown * (1.0 - uBack) / alpha + uBack : uBack;
}
// Dither, so the long soft falloff shows no bands, and optional grain.
if (alpha > 0.002) {
float ign = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
color += (ign - 0.5) / 255.0;
alpha += (fract(ign + 0.618034) - 0.5) / 255.0;
if (uGrain > 0.0) {
float g = lattice(ivec2(gl_FragCoord.xy) + ivec2(int(uSeed), 17)) / TAU;
color += (g - 0.5) * uGrain * 0.12;
}
} else {
alpha = 0.0;
}
fragColor = vec4(clamp(color, 0.0, 1.0), clamp(alpha, 0.0, 1.0) * uOpacity);
}`;
const UNIFORMS = [
"uSize", "uDpr", "uHalf", "uRadius", "uPath", "uLine", "uOuter", "uGlow", "uReach", "uNoise",
"uCells", "uGrains", "uOctaves", "uDrift", "uPhase", "uLch1", "uLch2", "uLch3", "uBack", "uInk",
"uExposure", "uIntensity", "uOpacity", "uGrain", "uSeed", "uIntro", "uIdle", "uSoft", "uWisp", "uWispCells", "uFilaments", "uExtent",
] as const;
type UniformName = (typeof UNIFORMS)[number];
/** A setting, read off the element so a wrapper's own settings win. */
export function readNum(el: Element, name: string, fallback: number): number {
const raw = getComputedStyle(el).getPropertyValue(name).trim();
if (!raw) return fallback;
if (raw.endsWith("ms")) return parseFloat(raw);
if (raw.endsWith("s")) return parseFloat(raw) * 1000;
const n = parseFloat(raw);
return isNaN(n) ? fallback : n;
}
const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
const smooth = (edge0: number, edge1: number, value: number) => {
const t = clamp((value - edge0) / (edge1 - edge0), 0, 1);
return t * t * (3 - 2 * t);
};
const easeInOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
const wrap = (value: number) => ((value % 1) + 1) % 1;
/* Colours. The settings are CSS colours, so the browser resolves them first
(set on a probe element, read back as a computed colour), then they are
read as sRGB here: rgb(), oklch(), oklab() and color(srgb ...) by hand,
anything else (hex, a named colour, hsl) through a 1px 2D canvas. */
const toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4));
const toSrgb = (c: number) => {
const v = clamp(c, 0, 1);
return v <= 0.0031308 ? v * 12.92 : 1.055 * Math.pow(v, 1 / 2.4) - 0.055;
};
function fromOklab([L, A, B]: Triple): Triple {
const l = Math.pow(L + 0.3963377774 * A + 0.2158037573 * B, 3);
const m = Math.pow(L - 0.1055613458 * A - 0.0638541728 * B, 3);
const s = Math.pow(L - 0.0894841775 * A - 1.291485548 * B, 3);
return [
toSrgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
toSrgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
toSrgb(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),
];
}
function toOklab([r, g, b]: Triple): Triple {
const lr = toLinear(r);
const lg = toLinear(g);
const lb = toLinear(b);
const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb);
const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb);
const s = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb);
return [
0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
];
}
const toLch = ([l, a, b]: Triple): Triple => [l, Math.hypot(a, b), Math.atan2(b, a)];
const luminance = ([r, g, b]: Triple) => 0.2126 * r + 0.7152 * g + 0.0722 * b;
let paint: CanvasRenderingContext2D | null | undefined;
/** Any colour the browser knows, as sRGB 0 to 1, or null when (nearly) clear. */
function parseColor(value: string): Triple | null {
const text = value.trim().toLowerCase();
if (!text || text === "transparent" || text === "none") return null;
const fn = /^([a-z]+)\(([^)]*)\)$/.exec(text);
if (fn) {
const parts = fn[2].split(/[\s,/]+/).filter(Boolean);
const read = (index: number, scale: number) => {
const part = parts[index] ?? "0";
const number = Number.parseFloat(part);
if (!Number.isFinite(number)) return 0;
return part.endsWith("%") ? (number / 100) * scale : number;
};
const alphaIndex = fn[1] === "color" ? 4 : 3;
if (parts.length > alphaIndex && read(alphaIndex, 1) < 0.05) return null;
if (fn[1] === "rgb" || fn[1] === "rgba")
return [clamp(read(0, 255) / 255, 0, 1), clamp(read(1, 255) / 255, 0, 1), clamp(read(2, 255) / 255, 0, 1)];
if (fn[1] === "oklch") {
const hue = (read(2, 360) * Math.PI) / 180;
const chroma = read(1, 0.4);
return fromOklab([read(0, 1), chroma * Math.cos(hue), chroma * Math.sin(hue)]);
}
if (fn[1] === "oklab") return fromOklab([read(0, 1), read(1, 0.4), read(2, 0.4)]);
if (fn[1] === "color" && parts[0] === "srgb")
return [clamp(read(1, 1), 0, 1), clamp(read(2, 1), 0, 1), clamp(read(3, 1), 0, 1)];
}
if (paint === undefined) {
const c = document.createElement("canvas");
c.width = 1;
c.height = 1;
paint = c.getContext("2d", { willReadFrequently: true });
}
if (!paint) return null;
paint.clearRect(0, 0, 1, 1);
paint.fillStyle = "rgba(0, 0, 0, 0)";
paint.fillStyle = text;
paint.fillRect(0, 0, 1, 1);
const d = paint.getImageData(0, 0, 1, 1).data;
if (d[3] < 13) return null;
return [d[0] / 255, d[1] / 255, d[2] / 255];
}
/** A colour setting, resolved on this slot so a wrapper's or a theme's own value wins. */
function readSetting(slot: HTMLElement, name: string): Triple | null {
const probe = document.createElement("span");
probe.style.display = "none";
probe.style.color = `var(${name})`;
slot.appendChild(probe);
const value = getComputedStyle(probe).color;
probe.remove();
return parseColor(value);
}
/* The page colour behind the slot: the first painted background up the tree.
With none, the text colour tells light from dark, then the system setting. */
function readPage(slot: HTMLElement): Triple {
for (let node = slot.parentElement; node; node = node.parentElement) {
const fill = parseColor(getComputedStyle(node).backgroundColor);
if (fill) return fill;
}
const text = parseColor(getComputedStyle(slot).color);
if (text) return luminance(text) > 0.5 ? [0.04, 0.04, 0.04] : [1, 1, 1];
return window.matchMedia("(prefers-color-scheme: dark)").matches ? [0.04, 0.04, 0.04] : [1, 1, 1];
}
function compile(gl: WebGL2RenderingContext, type: number, source: string) {
const shader = gl.createShader(type);
if (!shader) return null;
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
gl.deleteShader(shader);
return null;
}
return shader;
}
type Swell = { at: number; rate: number; born: number; life: number; gain: number; fade: number };
/**
* Plays one landing glow around the slot's picture and cleans up after
* itself. Returns a stop function that ends it early (a clear, a new landing,
* an unmount), or null when there is nothing to play.
*/
export function playGlow(slot: HTMLElement): (() => void) | null {
const w = slot.offsetWidth;
const h = slot.offsetHeight;
if (w < 2 || h < 2) return null;
// Settings, read at fire time so a live retune reaches the next landing.
const line = clamp(readNum(slot, "--image-drop-glow-line", 1), 0, 12);
const inset = Math.max(0, readNum(slot, "--image-drop-glow-inset", 0));
const glowStrength = clamp(readNum(slot, "--image-drop-glow-strength", 0.5), 0, 3) * 0.6;
const glowWidth = readNum(slot, "--image-drop-glow-width", 110);
const noise = clamp(readNum(slot, "--image-drop-glow-noise", 0.8), 0, 1);
const noiseScale = clamp(readNum(slot, "--image-drop-glow-noise-scale", 3), 0.2, 12);
const flowSpeed = clamp(readNum(slot, "--image-drop-glow-flow", 1), 0, 6);
const idleCount = clamp(Math.round(readNum(slot, "--image-drop-glow-swells", 4)), 0, MAX_IDLE);
const idleSpeed = clamp(readNum(slot, "--image-drop-glow-swell-speed", 1), 0, 5);
const idleStrength = clamp(readNum(slot, "--image-drop-glow-swell-strength", 1), 0, 3);
const intensity = clamp(readNum(slot, "--image-drop-glow-intensity", 0.8), 0, 4);
const opacity = clamp(readNum(slot, "--image-drop-glow-opacity", 0.5), 0, 1);
const grain = clamp(readNum(slot, "--image-drop-glow-grain", 0), 0, 1);
const introSpeed = clamp(readNum(slot, "--image-drop-glow-intro-speed", 1), 0.1, 10);
const lag = clamp(readNum(slot, "--image-drop-glow-lag", 0), 0, 1);
const wisp = clamp(readNum(slot, "--image-drop-glow-wisp", 0.7), 0, 1);
const hold = Math.max(0, readNum(slot, "--image-drop-glow-hold", 600)) / 1000;
const fade = Math.max(0, readNum(slot, "--image-drop-glow-fade", 350)) / 1000;
// The line's path: a rounded rectangle just outside the picture, by the
// inset plus half the line, with the picture's corner grown by the same.
const rawRadius = getComputedStyle(slot).borderTopLeftRadius;
const picRadius = Math.min(
rawRadius.endsWith("%") ? (parseFloat(rawRadius) / 100) * Math.min(w, h) : parseFloat(rawRadius) || 0,
Math.min(w, h) / 2,
);
const halfX = w / 2 + inset + line / 2;
const halfY = h / 2 + inset + line / 2;
const limit = Math.min(halfX, halfY);
const radius = clamp(picRadius + inset + line / 2, 0, limit);
// The glow grows outward, so its reach is not capped by the picture's size.
const reach = Math.max(glowWidth, 4);
const bend = Math.min(Math.max(radius, reach * 1.75), limit);
const hx = Math.max(halfX - bend, 0);
const hy = Math.max(halfY - bend, 0);
const perimeter = Math.max(4 * (hx + hy) + 2 * Math.PI * bend, 1);
// The canvas overhangs the picture by the glow's furthest reach on every
// side. It sits in the slot's padding box, so the slot's border is added
// back to line its centre up with the picture's.
// The farthest any light can land past the line: the noise can stretch the
// reach to about 1.75 times, the wisps by up to 1.4 times more, and the bend
// can pull the falloff out by another 0.3 of the reach.
const extent = reach * (1.75 * (1 + 0.4 * wisp) + 0.3 * wisp) + 2;
const pad = Math.ceil(inset + line + extent + 4);
const border = slot.clientLeft;
const cssW = w + pad * 2;
const cssH = h + pad * 2;
const ratio = Math.min(window.devicePixelRatio || 1, 2);
const canvas = document.createElement("canvas");
canvas.className = "motion-image-drop-glow";
canvas.setAttribute("aria-hidden", "true");
canvas.width = Math.round(cssW * ratio);
canvas.height = Math.round(cssH * ratio);
canvas.style.left = -(pad + border) + "px";
canvas.style.top = -(pad + border) + "px";
canvas.style.width = cssW + "px";
canvas.style.height = cssH + "px";
const gl = canvas.getContext("webgl2", {
alpha: true,
premultipliedAlpha: false,
antialias: false,
depth: false,
stencil: false,
powerPreference: "high-performance",
});
if (!gl) return null;
const vs = compile(gl, gl.VERTEX_SHADER, VERTEX);
const fs = compile(gl, gl.FRAGMENT_SHADER, FRAGMENT);
const program = gl.createProgram();
const vao = gl.createVertexArray();
let linked = false;
if (vs && fs && program) {
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
linked = !!gl.getProgramParameter(program, gl.LINK_STATUS);
}
let raf = 0;
let stopped = false;
function stop() {
if (stopped) return;
stopped = true;
cancelAnimationFrame(raf);
document.removeEventListener("visibilitychange", onVisibility);
canvas.removeEventListener("webglcontextlost", stop);
if (!gl!.isContextLost()) {
gl!.deleteVertexArray(vao);
gl!.deleteProgram(program);
gl!.deleteShader(vs);
gl!.deleteShader(fs);
// Hand the context back now rather than whenever it is collected.
gl!.getExtension("WEBGL_lose_context")?.loseContext();
}
canvas.remove();
}
if (!linked || !program) {
stop();
return null;
}
const loc = {} as Record<UniformName, WebGLUniformLocation | null>;
for (const name of UNIFORMS) loc[name] = gl.getUniformLocation(program, name);
// Colours: three, in OKLCH. One that will not resolve takes its neighbour's
// place. A near-grey one borrows the next one's hue, so the blend into it
// does not swing through an unrelated colour; the shader takes each hue
// the short way round.
let colorKey = "";
function syncColors() {
const page = readPage(slot);
const read = [1, 2, 3].map((i) => readSetting(slot, `--image-drop-glow-color-${i}`));
const known = read.find((c) => c) ?? ([0.25, 0.45, 1] as Triple);
const rgb = read.map((c, i) => c ?? read[(i + 1) % 3] ?? read[(i + 2) % 3] ?? known);
const key = [page, ...rgb].join("|");
if (key === colorKey) return;
colorKey = key;
gl!.uniform3f(loc.uBack, page[0], page[1], page[2]);
gl!.uniform1f(loc.uInk, luminance(page) > 0.55 ? 1 : 0);
const lch = rgb.map((c) => toLch(toOklab(c)));
lch.forEach((c, i) => {
if (c[1] < 0.02) c[2] = lch[(i + 1) % 3][1] >= 0.02 ? lch[(i + 1) % 3][2] : lch[(i + 2) % 3][2];
});
gl!.uniform3f(loc.uLch1, lch[0][0], lch[0][1], lch[0][2]);
gl!.uniform3f(loc.uLch2, lch[1][0], lch[1][1], lch[1][2]);
gl!.uniform3f(loc.uLch3, lch[2][0], lch[2][1], lch[2][2]);
}
gl.viewport(0, 0, canvas.width, canvas.height);
gl.useProgram(program);
gl.bindVertexArray(vao);
gl.disable(gl.BLEND);
gl.clearColor(0, 0, 0, 0);
gl.uniform2f(loc.uSize, cssW, cssH);
gl.uniform1f(loc.uDpr, canvas.width / cssW);
gl.uniform2f(loc.uHalf, halfX, halfY);
gl.uniform1f(loc.uRadius, radius);
gl.uniform4f(loc.uPath, hx, hy, bend, perimeter);
gl.uniform1f(loc.uLine, line);
gl.uniform1f(loc.uOuter, inset);
gl.uniform1f(loc.uGlow, glowStrength);
gl.uniform1f(loc.uReach, reach);
gl.uniform1f(loc.uExtent, extent);
gl.uniform1f(loc.uWisp, wisp);
gl.uniform2f(
loc.uWispCells,
Math.max(3, Math.round(perimeter / (1.2 * reach))),
Math.max(7, Math.round(perimeter / (0.35 * reach))),
);
gl.uniform1f(loc.uFilaments, Math.max(8, Math.round(perimeter / (0.12 * reach))));
gl.uniform1f(loc.uNoise, noise);
gl.uniform1f(loc.uCells, Math.max(2, Math.round((perimeter * noiseScale) / 1800)));
gl.uniform1f(loc.uGrains, Math.max(3, Math.round((perimeter * noiseScale) / (3 * 1.3 * reach))));
gl.uniform1f(loc.uOctaves, 2);
gl.uniform1f(loc.uExposure, 1.5);
gl.uniform1f(loc.uIntensity, intensity);
gl.uniform1f(loc.uGrain, grain);
syncColors();
slot.appendChild(canvas);
canvas.addEventListener("webglcontextlost", stop);
// The frame loop's clocks, all in seconds.
let flowTime = 0;
let clock = 0;
let idleClock = 0;
let nextSwell = 0;
let introTime = 0;
let afterIntro = 0;
let colorsAt = 0;
let last = 0;
const swells: Swell[] = [];
const idleSlots = new Float32Array(MAX_IDLE * 2);
// A new swell goes where it is furthest from the others: of 16 evenly
// spaced tries from a random start, the one with the widest gap.
function spawnSwell() {
const offset = Math.random();
let best = offset;
let bestGap = -1;
for (let i = 0; i < 16; i++) {
const candidate = wrap(offset + i / 16);
let gap = 1;
for (const other of swells) {
const apart = Math.abs(candidate - other.at);
gap = Math.min(gap, apart, 1 - apart);
}
if (gap > bestGap) {
bestGap = gap;
best = candidate;
}
}
swells.push({
at: best,
rate: 0.7 + Math.random() * 0.6,
born: idleClock,
life: 8 + Math.random() * 4,
gain: 0.75 + Math.random() * 0.25,
fade: 1,
});
}
function frame(now: number) {
raf = 0;
if (stopped) return;
// A long gap (the tab was hidden, a slow frame) counts as one frame, so
// the glow carries on where it was instead of jumping.
const dt = last && now - last < 100 ? clamp((now - last) / 1000, 0, 0.05) : 1 / 60;
last = now;
flowTime += dt * flowSpeed;
clock += dt;
if (introTime < INTRO_TIME) introTime = Math.min(INTRO_TIME, introTime + dt * introSpeed);
else afterIntro += dt;
// Linger, then fade the whole layer and let it go.
if (afterIntro >= hold + fade) {
stop();
return;
}
const fading = fade > 0 ? easeInOut(clamp((afterIntro - hold) / fade, 0, 1)) : 0;
const drift = dt * idleSpeed * 0.012;
idleClock += dt;
for (let i = 0; i < swells.length; i++) {
const swell = swells[i];
swell.at = wrap(swell.at + drift * swell.rate);
const surplus = i < swells.length - idleCount;
swell.fade = surplus ? swell.fade * Math.exp(-dt / 0.5) : Math.min(1, swell.fade + dt * 2);
}
for (let i = swells.length - 1; i >= 0; i--)
if (idleClock - swells[i].born > swells[i].life || swells[i].fade < 0.002) swells.splice(i, 1);
if (introTime >= INTRO_TIME && swells.length < idleCount && idleClock >= nextSwell) {
spawnSwell();
nextSwell = idleClock + (10 / Math.max(idleCount, 1)) * (0.6 + Math.random() * 0.4);
}
if (now - colorsAt > 1000) {
colorsAt = now;
syncColors();
}
const travel = flowTime * FLOW_RATE;
gl!.uniform4f(loc.uDrift, travel % perimeter, (travel * 1.6) % perimeter, flowTime * 0.09, (travel * 1.3) % perimeter);
gl!.uniform1f(loc.uPhase, ((flowTime * Math.PI * 2) / 70) % (Math.PI * 2));
gl!.uniform1f(loc.uSeed, Math.floor(clock * 60) % 997);
gl!.uniform1f(loc.uOpacity, opacity * (1 - fading));
const halfP = perimeter / 2;
if (introTime < INTRO_TIME) {
const lineK = easeInOut(clamp(introTime / 1.8, 0, 1));
const glowK = easeInOut(clamp((introTime - 0.35) / 2.1, 0, 1));
// How far the glow trails the line. At 0 the glow's front rides the
// line's front and is full a short way behind it, so the two arrive
// together. At 1 the glow starts late and sweeps round after the line
// has closed. In between is a blend of the two fronts.
const lineFront = lineK * (halfP + 60);
const soft = (0.2 + 0.4 * lag) * halfP;
gl!.uniform1f(loc.uSoft, soft);
gl!.uniform4f(
loc.uIntro,
hx / perimeter,
lineFront,
lineFront + (glowK * (halfP * 1.6) - lineFront) * lag,
smooth(0, 0.12, introTime) * (1 - smooth(1.3, 2.1, introTime)) * 0.9,
);
} else {
gl!.uniform1f(loc.uSoft, 1);
gl!.uniform4f(loc.uIntro, 0, 1e6, 1e6, 0);
}
for (let i = 0; i < MAX_IDLE; i++) {
const swell = swells[i];
if (!swell) {
idleSlots[i * 2] = 0;
idleSlots[i * 2 + 1] = 0;
continue;
}
const envelope = Math.pow(Math.sin(Math.PI * clamp((idleClock - swell.born) / swell.life, 0, 1)), 2);
idleSlots[i * 2] = swell.at;
idleSlots[i * 2 + 1] = envelope * swell.gain * swell.fade * idleStrength;
}
gl!.uniform2fv(loc.uIdle, idleSlots);
gl!.clear(gl!.COLOR_BUFFER_BIT);
gl!.drawArrays(gl!.TRIANGLES, 0, 3);
if (!document.hidden) raf = requestAnimationFrame(frame);
else last = 0;
}
// A hidden tab holds the glow where it is; it carries on when the tab is back.
function onVisibility() {
if (stopped || document.hidden || raf) return;
last = 0;
raf = requestAnimationFrame(frame);
}
document.addEventListener("visibilitychange", onVisibility);
raf = requestAnimationFrame(frame);
return stop;
}/* Image drop: an expressive motion recipe from UI.MD. Settings first, then rules.
The settings sit on :where(:root), which has no weight, so any :root block of
yours overrides them whatever order the stylesheets load in. */
:where(:root) {
/* Look: kit tokens, so it follows a retheme and both modes. The empty slot
wears Dropzone's edge (dashed, no wash, accent on hover and drag-over); a
filled slot is a card. */
--image-drop-size-sm: 5rem; /* 80px */
--image-drop-size-md: 6.5rem; /* 104px, the default */
--image-drop-size-lg: 10rem; /* 160px */
--image-drop-chip-size: 4.5rem; /* 72px */
--image-drop-radius: var(--radius-lg);
--image-drop-border: 1px; /* Dropzone's dashed edge */
--image-drop-edge: var(--border);
--image-drop-accent: var(--color-accent-500); /* edge and label on hover, focus and drag-over */
--image-drop-fill: transparent;
--image-drop-label: var(--muted-foreground);
--image-drop-shadow: var(--shadow-ring-md); /* the card tier: the ring is the edge */
/* The chip: lifts on grab, tilts with speed, springs home on a miss. */
--image-drop-lift-scale: 1.05;
--image-drop-lift-dur: 200ms;
--image-drop-lift-ease: var(--ease-expressive);
--image-drop-tilt-max: 10; /* degrees */
--image-drop-tilt-dur: 150ms;
--image-drop-tilt-ease: ease-out;
--image-drop-return-dur: 500ms;
--image-drop-return-ease: var(--ease-expressive-spring);
--image-drop-dur: 450ms; /* the chip fading out where it was let go */
--image-drop-ease: cubic-bezier(0.34, 1.35, 0.64, 1);
--image-drop-chip-blur: var(--blur-2xs, 2px);
--image-drop-respawn-dur: 250ms; /* the chip coming back once the slot is cleared */
--image-drop-respawn-ease: var(--ease-expressive);
/* The landing: the slot cross-fades into the picture, squashes, then springs. */
--image-drop-squash: 0.97;
--image-drop-down-dur: 250ms;
--image-drop-down-ease: var(--ease-expressive);
--image-drop-up-dur: 450ms;
--image-drop-up-ease: var(--ease-expressive);
--image-drop-fade-in: 400ms; /* slot to picture, and the shadow arriving */
--image-drop-fade-ease: ease-in-out;
/* Clearing: the picture blurs away and the dashed edge comes back. */
--image-drop-out-dur: 400ms;
--image-drop-out-ease: var(--ease-expressive);
--image-drop-out-blur: 4px;
/* The glow: at the bottom of the squash a line of light draws around the
picture from the top centre, both ways at once, with a bright head on
each front, and a soft aurora fades in behind it, hanging outside the
line; nothing is drawn over the picture. Then it lingers, the light
flowing unevenly with swells drifting along the frame, and fades out.
The intro takes 2.6s at intro speed 1; the hold starts when it ends. */
--image-drop-glow-delay: 0ms; /* after the bottom of the squash */
--image-drop-glow-intro-speed: 1; /* 2 plays the draw-in twice as fast */
--image-drop-glow-lag: 0; /* 0: the glow arrives with the line. 1: it sweeps round after the line has closed */
--image-drop-glow-hold: 600ms;
--image-drop-glow-fade: 350ms;
--image-drop-glow-line: 1px; /* the line's width */
--image-drop-glow-inset: 0px; /* a gap between the picture and the line */
--image-drop-glow-width: 110px; /* how far the glow reaches past the line */
--image-drop-glow-wisp: 0.7; /* 0: a clean offset of the frame. 1: an irregular, wispy edge that breathes */
--image-drop-glow-strength: 0.5; /* the glow against the line, 0 to 3 */
--image-drop-glow-intensity: 0.8; /* everything at once, 0 to 4 */
--image-drop-glow-opacity: 0.5;
--image-drop-glow-noise: 0.8; /* how uneven the light is, 0 to 1 */
--image-drop-glow-noise-scale: 3; /* higher, smaller patches */
--image-drop-glow-flow: 1; /* how fast the light and its colours run along the frame */
--image-drop-glow-swells: 4; /* brighter patches drifting along the frame while it lingers, 0 to 6 */
--image-drop-glow-swell-speed: 1;
--image-drop-glow-swell-strength: 1;
--image-drop-glow-grain: 0; /* film grain, 0 to 1 */
/* Three colours, blended in OKLCH round the frame (1 to 2 to 3 and back
to 1), the blend travelling slowly round: accent, brand and brand 2,
read when the glow fires, so it follows a retheme. Any CSS colour works.
On a light page the line is inked in a deeper shade and the glow is a
tint; on a dark page both are light. */
--image-drop-glow-color-1: var(--color-accent-500);
--image-drop-glow-color-2: var(--color-brand-500);
--image-drop-glow-color-3: var(--color-brand-2-500);
}
/* Dark: the accent climbs a step to stay bright on a dark page, as Dropzone's
does, and the glow's colours climb with it, so they read as light rather
than a deep tint. */
:where(.dark) {
--image-drop-accent: var(--color-accent-400);
--image-drop-glow-color-1: var(--color-accent-400);
--image-drop-glow-color-2: var(--color-brand-400);
--image-drop-glow-color-3: var(--color-brand-2-400);
}
/* The chip */
/* ============================================================ */
/* Follows the pointer 1:1: no transition on translate. The controller writes
--dx, --dy, --tilt and --lift straight to its style. */
.motion-image-drop-chip {
appearance: none;
border: 0;
padding: 0;
position: relative;
z-index: 10;
display: block;
flex-shrink: 0;
width: var(--image-drop-chip-size);
height: var(--image-drop-chip-size);
border-radius: var(--image-drop-radius);
overflow: hidden;
background: var(--muted);
box-shadow: var(--image-drop-shadow);
cursor: grab;
touch-action: none; /* required for a touch drag */
user-select: none;
-webkit-user-select: none;
-webkit-tap-highlight-color: transparent;
translate: var(--dx, 0px) var(--dy, 0px);
rotate: var(--tilt, 0deg);
scale: var(--lift, 1);
transition:
scale var(--image-drop-lift-dur) var(--image-drop-lift-ease),
rotate var(--image-drop-tilt-dur) var(--image-drop-tilt-ease);
}
.motion-image-drop-chip img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
pointer-events: none;
}
/* will-change only while something moves, so a resting chip is not held on
its own layer. */
.motion-image-drop-chip.is-dragging {
cursor: grabbing;
z-index: 20;
will-change: translate, rotate, scale;
}
.motion-image-drop-chip.is-returning {
transition:
translate var(--image-drop-return-dur) var(--image-drop-return-ease),
rotate var(--image-drop-return-dur) var(--image-drop-return-ease),
scale var(--image-drop-return-dur) var(--image-drop-return-ease);
will-change: translate, rotate, scale;
}
/* A good drop: the chip does not fly or resize. It fades and blurs away where
it was let go, levelling its tilt, while the slot becomes the picture. */
.motion-image-drop-chip.is-fading {
opacity: 0;
filter: blur(var(--image-drop-chip-blur));
pointer-events: none;
transition:
opacity var(--image-drop-dur) var(--image-drop-ease),
filter var(--image-drop-dur) var(--image-drop-ease),
rotate var(--image-drop-tilt-dur) var(--image-drop-tilt-ease);
will-change: opacity, filter;
}
@keyframes motion-image-drop-respawn {
from { opacity: 0; transform: scale(0.9); }
to { opacity: 1; transform: scale(1); }
}
.motion-image-drop-chip.is-respawning {
animation-name: motion-image-drop-respawn;
animation-duration: var(--image-drop-respawn-dur);
animation-timing-function: var(--image-drop-respawn-ease);
}
/* Keyboard focus is the kit's 3px ring, listed first so it paints over the
chip's own ring. */
.motion-image-drop-chip:focus-visible {
outline: none;
box-shadow: 0 0 0 3px var(--ring-focus), var(--image-drop-shadow);
}
/* The slot */
/* ============================================================ */
.motion-image-drop-slot {
position: relative;
isolation: isolate; /* keeps the glow's negative z-index inside the slot */
box-sizing: border-box;
flex-shrink: 0;
display: grid;
place-items: center;
width: var(--image-drop-size-md);
height: var(--image-drop-size-md);
border-radius: var(--image-drop-radius);
border: var(--image-drop-border) dashed var(--image-drop-edge);
background: var(--image-drop-fill);
transition:
border-color var(--transition-duration-small) var(--ease-small),
background-color var(--transition-duration-small) var(--ease-small);
}
.motion-image-drop-slot[data-size="sm"] {
width: var(--image-drop-size-sm);
height: var(--image-drop-size-sm);
}
.motion-image-drop-slot[data-size="lg"] {
width: var(--image-drop-size-lg);
height: var(--image-drop-size-lg);
}
/* fill: the container decides, for a cover photo or a canvas slot. */
.motion-image-drop-slot[data-size="fill"] {
width: 100%;
height: 100%;
}
.motion-image-drop-label {
max-width: 100%;
padding: 0.5rem;
font-size: var(--text-1xs);
line-height: var(--text-1xs--line-height);
text-align: center;
text-wrap: balance;
color: var(--image-drop-label);
pointer-events: none;
transition:
color var(--transition-duration-small) var(--ease-small),
opacity var(--transition-duration-small) var(--ease-small);
}
/* Hover (on a device that hovers), keyboard focus, a held file or the chip
over it: the edge and the label turn accent, as on Dropzone. */
@media (hover: hover) {
.motion-image-drop-slot[data-state="empty"]:hover {
border-color: var(--image-drop-accent);
}
.motion-image-drop-slot[data-state="empty"]:hover .motion-image-drop-label {
color: var(--image-drop-accent);
}
}
.motion-image-drop-slot[data-state="empty"][data-drag-over],
.motion-image-drop-slot[data-state="empty"].is-over,
.motion-image-drop-slot:has(.motion-image-drop-input:focus-visible) {
border-color: var(--image-drop-accent);
}
.motion-image-drop-slot[data-state="empty"][data-drag-over] .motion-image-drop-label,
.motion-image-drop-slot[data-state="empty"].is-over .motion-image-drop-label,
.motion-image-drop-slot:has(.motion-image-drop-input:focus-visible) .motion-image-drop-label {
color: var(--image-drop-accent);
}
.motion-image-drop-slot:has(.motion-image-drop-input:focus-visible) {
box-shadow: 0 0 0 3px var(--ring-focus);
}
.motion-image-drop-slot[data-disabled] {
opacity: 0.5;
}
/* The real control: a native file input stretched over the slot and drawn
invisible, so a click, Enter or Space opens the picker with the browser's
own focus, name and disabled handling. */
.motion-image-drop-input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
.motion-image-drop-input:disabled {
cursor: not-allowed;
}
/* Filled: a card. The edge gives way to the card shadow as the picture fades in. */
.motion-image-drop-slot[data-state="filled"] {
border-color: transparent;
box-shadow: var(--image-drop-shadow);
transition:
border-color var(--image-drop-fade-in) var(--image-drop-fade-ease),
box-shadow var(--image-drop-fade-in) var(--image-drop-fade-ease);
}
/* Full, with a file held over it or the chip over it: an accent ring says
a drop here replaces the picture. */
.motion-image-drop-slot[data-state="filled"][data-drag-over],
.motion-image-drop-slot[data-state="filled"].is-over {
box-shadow: 0 0 0 2px var(--image-drop-accent), var(--image-drop-shadow);
}
.motion-image-drop-slot[data-state="filled"] .motion-image-drop-label,
.motion-image-drop-slot[data-state="emptying"] .motion-image-drop-label {
opacity: 0;
}
/* Clearing: the shadow fades out with the picture and the dashed edge returns. */
.motion-image-drop-slot[data-state="emptying"] {
border-color: var(--image-drop-edge);
box-shadow: none;
transition:
border-color var(--image-drop-out-dur) var(--image-drop-out-ease),
box-shadow var(--image-drop-out-dur) var(--image-drop-out-ease);
}
/* The landed picture covers the whole border box (a negative inset by the
border width), otherwise the dashed edge's track shows as a hairline around
it. Same box as the slot, so the same radius. */
.motion-image-drop-image {
position: absolute;
inset: calc(var(--image-drop-border) * -1);
width: calc(100% + var(--image-drop-border) * 2);
height: calc(100% + var(--image-drop-border) * 2);
/* Tailwind's base caps every img at max-width 100%, which is the slot's
inner box: the picture came up two border widths short on its end edge. */
max-width: none;
display: block;
object-fit: cover;
border-radius: var(--image-drop-radius);
pointer-events: none;
opacity: 1;
transition: opacity var(--image-drop-fade-in) var(--image-drop-fade-ease);
@starting-style {
opacity: 0;
}
}
.motion-image-drop-slot[data-state="emptying"] .motion-image-drop-image {
opacity: 0;
filter: blur(var(--image-drop-out-blur));
transition:
opacity var(--image-drop-out-dur) var(--image-drop-out-ease),
filter var(--image-drop-out-dur) var(--image-drop-out-ease);
}
/* Two separate keyframe phases, so the squash and the spring each get their
own clock and curve. The second waits out the first; both hold their end.
Longhands, not the shorthand: WebKit mis-parses var() inside the animation
shorthand. */
@keyframes motion-image-drop-down {
from { transform: scale(1); }
to { transform: scale(var(--image-drop-squash, 0.97)); }
}
@keyframes motion-image-drop-up {
from { transform: scale(var(--image-drop-squash, 0.97)); }
to { transform: scale(1); }
}
.motion-image-drop-slot.is-landing {
animation-name: motion-image-drop-down, motion-image-drop-up;
animation-duration: var(--image-drop-down-dur), var(--image-drop-up-dur);
animation-timing-function: var(--image-drop-down-ease), var(--image-drop-up-ease);
animation-delay: 0ms, var(--image-drop-down-dur);
animation-fill-mode: forwards, forwards;
will-change: transform;
}
/* Clear button, pinned to the picture's top corner. */
.motion-image-drop-clear {
position: absolute;
top: 0.375rem;
inset-inline-end: 0.375rem;
z-index: 2;
width: 1.5rem;
height: 1.5rem;
padding: 0;
border: 0;
border-radius: 50%;
display: grid;
place-items: center;
background: var(--card);
color: var(--card-foreground);
box-shadow: var(--shadow-ring-md);
cursor: pointer;
-webkit-tap-highlight-color: transparent;
opacity: 1;
transition: opacity var(--image-drop-fade-in) var(--image-drop-fade-ease);
@starting-style {
opacity: 0;
}
}
.motion-image-drop-clear svg {
display: block;
width: 0.875rem;
height: 0.875rem;
stroke-width: var(--stroke-icon);
}
.motion-image-drop-slot[data-state="emptying"] .motion-image-drop-clear {
opacity: 0;
pointer-events: none;
transition: opacity var(--image-drop-out-dur) var(--image-drop-out-ease);
}
.motion-image-drop-clear:focus-visible {
outline: none;
box-shadow: 0 0 0 3px var(--ring-focus), var(--shadow-ring-md);
}
/* A 24px button grows its hit area to 44px under a finger. */
@media (pointer: coarse) {
.motion-image-drop-clear::before {
content: "";
position: absolute;
inset: -0.625rem;
}
}
/* box-shadow vanishes in forced-colors (high contrast) mode, so focus falls
back to a system-colour outline. */
@media (forced-colors: active) {
.motion-image-drop-chip:focus-visible,
.motion-image-drop-clear:focus-visible,
.motion-image-drop-slot:has(.motion-image-drop-input:focus-visible) {
outline: 2px solid CanvasText;
outline-offset: 2px;
}
}
/* The glow */
/* ============================================================ */
/* A canvas the controller adds when the glow fires and removes when it ends.
It overhangs the slot by the farthest wisp on every side (about 270px at the
default width, so give the slot room); the controller sets its size and
offset. Under the picture: the light comes out from
beneath it, and the picture stays untouched. */
.motion-image-drop-glow {
position: absolute;
z-index: -1;
display: block;
pointer-events: none;
}
/* Visually hidden, still read by screen readers (the live region). */
.motion-image-drop-sr {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
border: 0;
overflow: hidden;
clip: rect(0, 0, 0, 0);
clip-path: inset(50%);
white-space: nowrap;
}
/* Still: the image simply appears, and clearing simply empties. For a slot
that fills often, or one whose image was already there. */
.motion-image-drop-slot[data-still],
.motion-image-drop-slot[data-still] .motion-image-drop-image,
.motion-image-drop-slot[data-still] .motion-image-drop-clear {
transition: none;
}
/* A picture there from the start (defaultSrc) shows at once. Clearing it
still blurs it away: the emptying rules above are more specific. */
.motion-image-drop-image[data-preset],
.motion-image-drop-clear[data-preset] {
transition: none;
}
/* Reduced motion keeps drag and drop working: the chip still follows the
pointer, but nothing lifts, tilts, springs, squashes or glows. The picture
simply appears. Each selector repeats the specificity of the rule it undoes,
so the later position wins without !important. */
@media (prefers-reduced-motion: reduce) {
.motion-image-drop-chip,
.motion-image-drop-chip.is-returning,
.motion-image-drop-chip.is-fading {
transition: none;
will-change: auto;
}
.motion-image-drop-chip.is-respawning,
.motion-image-drop-slot.is-landing {
animation: none;
}
/* The controller never fires the glow here; this holds even if a page
turns reduced motion on while one is playing. */
.motion-image-drop-glow {
display: none;
}
.motion-image-drop-slot[data-state="filled"],
.motion-image-drop-slot[data-state="emptying"],
.motion-image-drop-image,
.motion-image-drop-slot[data-state="emptying"] .motion-image-drop-image,
.motion-image-drop-clear,
.motion-image-drop-slot[data-state="emptying"] .motion-image-drop-clear {
transition: none;
}
}