UNPKG

@humanspeak/svelte-motion

Version:

Framer Motion for Svelte 5. Declarative motion.<tag> components with AnimatePresence exit animations, gestures (hover, tap, drag, focus, in-view), variants, FLIP layout animations, shared-layout transitions, spring physics, and scroll-linked motion values

58 lines (57 loc) 1.67 kB
/** * Creates imperative drag controls for programmatically starting and stopping drags. * * Use this factory to create a controls object that can trigger a drag from external * events (e.g., a button press or keyboard shortcut). Pass the controls to a motion * element via the `dragControls` prop, then call `controls.start(event)` to initiate * the drag as if the user had pressed down on the element. * * @returns {DragControls} An object with `start`, `cancel`, `stop`, and `subscribe` methods. * @see https://motion.dev/docs/react-motion-component#dragging * * @example * ```svelte * <script> * import { motion, createDragControls } from '@humanspeak/svelte-motion' * * const controls = createDragControls() * * function startDrag(event) { * controls.start(event, { snapToCursor: true }) * } * </script> * * <button onpointerdown={startDrag}>Drag handle</button> * <motion.div drag="x" dragControls={controls}> * Draggable content * </motion.div> * ``` */ export const createDragControls = () => { let target = null; let starter = null; let cancelInertia = null; const controls = { start(event, options) { if (!target || !starter) return; const snap = options?.snapToCursor ?? false; starter(event, snap); }, cancel() { cancelInertia?.(); }, stop() { cancelInertia?.(); }, subscribe(el) { target = el; } }; controls._bind = (el, s, c) => { target = el; starter = s; cancelInertia = c ?? null; }; return controls; };