### Example: Panning with Composed Gesture Source: https://github.com/rezi/svelte-gestures/blob/main/README.md Demonstrates composing 'pan' and 'scroll' gestures. A short press initiates scrolling, while a longer press enables panning. This example shows how to manage gesture execution based on timing and movement. ```javascript // Conceptual example of composed gesture logic // Actual implementation would involve registering pan, press, and scroll gestures useComposedGesture(({ register }) => { const panGesture = register(pan); const pressGesture = register(press, { onUp: () => { // If press is short, allow scroll return false; // Indicate scroll should take over } }); const scrollGesture = register(scroll); return (activeEvents, event) => { if (pressGesture.isPressed()) { // If press is held, handle panning return panGesture.onMove(activeEvents, event); } else { // Otherwise, handle scrolling return scrollGesture.onMove(activeEvents, event); } }; }); ``` -------------------------------- ### Install svelte-gestures via npm Source: https://github.com/rezi/svelte-gestures/blob/main/README_5.0.7.md Installs the svelte-gestures package using npm. This is the standard method for adding the library to your Svelte project. ```bash npm install svelte-gestures ``` -------------------------------- ### Install svelte-gestures via Deno Source: https://github.com/rezi/svelte-gestures/blob/main/README_5.0.7.md Installs the svelte-gestures package for Deno projects. This command adds the library as a dependency within your Deno environment. ```bash deno add @rezi/svelte-gestures ``` -------------------------------- ### Svelte Gesture Event Handling Example Source: https://github.com/rezi/svelte-gestures/blob/main/README_5.1.4.md Demonstrates how to use the 'pan' gesture recognizer in Svelte. It shows how to import the gesture, define event handlers for different gesture events (like 'pan', 'pandown', 'panmove'), and access detailed event information including coordinates and pointer count. ```html
``` -------------------------------- ### ComposedGesture Example: Combining Pan and Scroll in Svelte Source: https://github.com/rezi/svelte-gestures/blob/main/README_5.0.7.md This example demonstrates how to use `composedGesture` to combine the `press`, `pan`, and `scroll` gestures. It registers `press` with specific options, `scroll`, and `pan`. The returned callback function determines whether to trigger `pan` after a successful `press` or `scroll` otherwise. This allows for distinct behaviors based on user interaction timing and type. ```html
press: {x} {y}
``` -------------------------------- ### Swipe Gesture Recognition in Svelte Source: https://github.com/rezi/svelte-gestures/blob/main/README.md This example demonstrates how to use the `useSwipe` attachment from `svelte-gestures` to detect swipe gestures. It captures the swipe direction, pointer type, and the target element. Configuration options like `timeframe` and `minSwipeDistance` can be passed to customize the gesture recognition. This functionality relies on the `svelte-gestures` library. ```html
({ timeframe: 300, minSwipeDistance: 50, touchAction: 'none' }))}>
swipe direction: {direction}
pointerType {pointerType}
target: {target?.tagName}
``` -------------------------------- ### Install svelte-gestures via JSR Source: https://github.com/rezi/svelte-gestures/blob/main/README_5.0.7.md Installs the svelte-gestures package using JSR (JavaScript Registry). This is an alternative package manager for JavaScript and TypeScript. ```bash npx jsr add @rezi/svelte-gestures ``` -------------------------------- ### Implement Press Gesture in Svelte Source: https://github.com/rezi/svelte-gestures/blob/main/README_5.0.7.md This example shows how to integrate a press gesture using the `press` action from 'svelte-gestures'. It records the press coordinates, target element, and pointer type. Options include `timeframe`, `spread` to define movement tolerance, and `triggerBeforeFinished` to fire the event even if the press is ongoing. `touchAction` is also configurable. ```html
press: {x} {y}
``` -------------------------------- ### Tap Gesture - Detect Quick Tap/Click Actions in Svelte Source: https://context7.com/rezi/svelte-gestures/llms.txt The tap gesture identifies quick pointer down-up actions within a timeframe and a minimal movement threshold. This example logs the tap position and pointer type. It is useful for distinguishing taps from drags. ```typescript import { useTap, type TapCustomEvent } from 'svelte-gestures'; let tapPosition = $state({ x: 0, y: 0 }); let lastTapTime = $state(0); function handleTap(event: TapCustomEvent) { tapPosition = { x: event.detail.x, y: event.detail.y }; lastTapTime = Date.now(); console.log('Tapped with', event.detail.pointerType); } ``` -------------------------------- ### Tap Gesture Logic (TypeScript) Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/gestures/tap/tap.svelte.ts.html Implements the tap gesture detection. It records the starting position and time on pointer down and checks for a short duration and minimal movement on pointer up to trigger a custom tap event. Dependencies include the HTMLElement node and optional TapParameters. ```typescript function tapBase( node: HTMLElement, inputParameters?: Partial ): { onDown: (activeEvents: PointerEvent[], event: PointerEvent) => void; onUp: (activeEvents: PointerEvent[], event: PointerEvent) => void; parameters: TapParameters; } { const parameters: TapParameters = { timeframe: DEFAULT_DELAY, composed: false, touchAction: 'auto', ...inputParameters, }; let startTime: number; let clientX: number; let clientY: number; function onUp(activeEvents: PointerEvent[], event: PointerEvent): void { if ( Math.abs(event.clientX - clientX) < 4 && Math.abs(event.clientY - clientY) < 4 && Date.now() - startTime < parameters.timeframe ) { const rect = node.getBoundingClientRect(); const x = Math.round(event.clientX - rect.left); const y = Math.round(event.clientY - rect.top); node.dispatchEvent( new CustomEvent(gestureName, { detail: { x, y, target: event.target, pointerType: event.pointerType, }, }) ); } } function onDown(activeEvents: PointerEvent[], event: PointerEvent): void { clientX = event.clientX; clientY = event.clientY; startTime = Date.now(); } return { onDown, onUp, parameters }; } ``` -------------------------------- ### Setup and Destroy Gesture Event Handlers - TypeScript Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/shared.ts.html This code sets up the initial 'pointerdown' event listener and provides a `destroy` function. The `destroy` function removes the 'pointerdown' listener and calls the `onDestroy` callback for all plugins if no active events are present, ensuring proper cleanup of gesture resources. ```typescript // this is needed to prevent multiple event handlers being added when gesture is recreated if (!activeEvents.length) { // ... handlePointerdown function definition ... removePointerdownHandler = addEventListener( node, 'pointerdown', handlePointerdown ); } return { destroy: (): void => { if (!activeEvents.length) { removePointerdownHandler(); plugins.forEach((plugin) => { plugin.onDestroy?.(); }); } }, }; }, }; } ``` -------------------------------- ### Swipe Gesture - Detect Directional Swipes in Svelte Source: https://context7.com/rezi/svelte-gestures/llms.txt The swipe gesture recognizes fast directional movements within a specific timeframe and minimum distance. This example demonstrates detecting swipe direction and logging the starting target. It supports configurable touch actions for scroll and swipe detection. ```typescript import { useSwipe, type SwipeCustomEvent } from 'svelte-gestures'; let direction = $state(null); let swipeCount = $state(0); function handleSwipe(event: SwipeCustomEvent) { direction = event.detail.direction; // 'top' | 'right' | 'bottom' | 'left' swipeCount++; } function handleSwipeDown(event: GestureCustomEvent) { console.log('Swipe started at', event.detail.target); }
({ timeframe: 300, minSwipeDistance: 50, touchAction: 'pan-y' // Allow vertical scroll, detect horizontal swipes }), { onswipedown: handleSwipeDown } )}> Swipe direction: {direction || 'none'} (count: {swipeCount})
``` -------------------------------- ### Initialize Canvas for Svelte Gestures Plugin (JavaScript) Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/plugins/plugin-highlight.ts.html The onInit function sets up the necessary canvas elements for the Svelte Gestures highlight plugin. It creates a visible canvas for drawing highlights and an off-screen canvas for smoother animations. It also attaches event listeners for window resize and sets the initial position if a dispatch event is provided. ```javascript function onInit(dispatchEvent?: DispatchEvent): void { // Reset if already running (could caused by some unexpected browser behavior) onDestroy();   canvas = window.document.createElement('canvas'); canvas.id = 'svelte-gestures-highlight-plugin'; ctx = canvas.getContext('2d');   canvas.style.cssText = ` display: block; width: 100dvw; height: 100dvh; top: 0; left: 0; position: fixed; pointer-events: none; z-index: ${options.zIndex ?? fallbacks.zIndex}; `; window.document.body.appendChild(canvas); window.addEventListener('resize', resize);   if (dispatchEvent) { setPosition(dispatchEvent.event); }   // Create an off-screen canvas offScreenCanvas = document.createElement('canvas');   resize(); offScreenCtx = offScreenCanvas.getContext('2d'); fadingRunning = true; animate(); } ``` -------------------------------- ### Get Event Position Relative to Node Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/shared.ts.html The `getEventPostionInNode` function calculates the coordinates of a `PointerEvent` relative to the top-left corner of a given HTML element. This normalizes event positions. ```typescript export function getEventPostionInNode( node: HTMLElement, event: PointerEvent ): { x: number; y: number } { const rect = node.getBoundingClientRect(); return { x: Math.round(event.clientX - rect.left), y: Math.round(event.clientY - rect.top), }; } ``` -------------------------------- ### Get Center of Two Points Calculation Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/shared.ts.html The `getCenterOfTwoPoints` function calculates the midpoint between two active pointer events relative to a target HTML element. It's crucial for pinch-to-zoom gestures. ```typescript export function getCenterOfTwoPoints( node: HTMLElement, activeEvents: PointerEvent[] ): Coord { const rect = node.getBoundingClientRect(); const xDistance = Math.abs(activeEvents[0].clientX - activeEvents[1].clientX); const yDistance = Math.abs(activeEvents[0].clientY - activeEvents[1].clientY); const minX = Math.min(activeEvents[0].clientX, activeEvents[1].clientX); const minY = Math.min(activeEvents[0].clientY, activeEvents[1].clientY); const centerX = minX + xDistance / 2; const centerY = minY + yDistance / 2; const x = Math.round(centerX - rect.left); const y = Math.round(centerY - rect.top); return { x, y }; } ``` -------------------------------- ### Basic Pan Gesture Handling in Svelte Source: https://github.com/rezi/svelte-gestures/blob/main/README_5.0.7.md Demonstrates how to use the `pan` gesture recognizer in a Svelte component. It captures pan events, updates coordinates (`x`, `y`), and logs details of pan down and move events. It requires importing the `pan` action and relevant types. ```html
``` -------------------------------- ### Highlight Plugin Options in TypeScript Source: https://github.com/rezi/svelte-gestures/blob/main/README.md Specifies the configurable options for the highlight plugin, including color, fade time, z-index, and line width. These options allow customization of the visual trace left by pointers. ```typescript { color?: string; fadeTime?: number; zIndex?: number; lineWidth?: number; } ``` -------------------------------- ### TypeScript: Scroll Composition Function Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/gestures/scroll/scroll.svelte.ts.html Provides a composable function for scroll gesture event handlers. It encapsulates the core logic for scroll event detection (onMove, onDown, onUp) and returns them along with any configured plugins. Useful for integrating scroll behavior into custom gesture setups. ```typescript export const scrollComposition = ( node: HTMLElement, inputParameters?: Partial ): SubGestureFunctions => { const { onMove, onDown, onUp, parameters } = scrollBase( node, inputParameters ); return { onMove, onUp, onDown, plugins: parameters.plugins, }; }; ``` -------------------------------- ### usePinch Gesture Attachment Source: https://github.com/rezi/svelte-gestures/blob/main/README.md The usePinch attachment detects pinch gestures, commonly used for zooming. It emits a 'pinch' event containing details like the pinch center coordinates, the current scale factor, and the pointer type. Customizable options include touchAction, composed, and plugins. ```javascript import { usePinch } from 'svelte-gestures'; // Basic usage: const { pinch, onpinch } = usePinch(myHandler, () => ({ touchAction: 'pinch-zoom' })); // With event handlers for start and end: const { pinch: pinchWithHandlers, onpinch: onpinchWithHandlers } = usePinch( myHandler, () => ({ plugins: [myPinchPlugin] }), { onpinchstart: handlePinchStart, onpinchend: handlePinchEnd } ); ``` -------------------------------- ### Touch Points Plugin Options in TypeScript Source: https://github.com/rezi/svelte-gestures/blob/main/README.md Details the options for the touch points plugin, which visualizes touch points with colored circles. Options include color, z-index, and size for customizing the appearance of touch indicators. ```typescript { color?: string; zIndex?: number; size?: number; } ``` -------------------------------- ### Highlight Plugin - Visual Gesture Traces with Svelte Source: https://context7.com/rezi/svelte-gestures/llms.txt Provides visual feedback by drawing fading traces that follow pointer movements, connecting multiple touch points. This plugin is particularly useful for debugging and visualizing gesture interactions. It requires the `usePan` gesture and can be configured with color, fade time, z-index, and line width. ```typescript import { usePan, highlightPlugin } from 'svelte-gestures'; let highlightColor = $state('#00ff00'); function handlePan(event) { console.log('Panning at', event.detail.x, event.detail.y); } function handlePanUp() { // Change color for next gesture highlightColor = '#' + Math.floor(Math.random()*16777215).toString(16); }
({ delay: 0, touchAction: 'none', plugins: [ highlightPlugin({ color: highlightColor, fadeTime: 1500, zIndex: 1000000, lineWidth: 4 }) ] }), { onpanup: handlePanUp } )}> Drag to see highlighted trails (color: {highlightColor})
``` -------------------------------- ### Dynamically Change Highlight Plugin Options for Pan Gesture Source: https://github.com/rezi/svelte-gestures/blob/main/README_5.1.4.md Shows how to use the `highlightPlugin` with `pan` gesture and dynamically update its options, such as color, fade time, and line width, on a `panup` event. This allows for visual feedback that changes during interaction. Requires `pan`, `highlightPlugin`, and relevant event types from `svelte-gestures`. ```typescript import { pan, type PanCustomEvent, type GestureCustomEvent, highlightPlugin } from 'svelte-gestures'; let lineWidth = 8; let x = $state(0); let y = $state(0); let target: EventTarget | null = $state(null); function handler(event: PanCustomEvent) { x = event.detail.x; y = event.detail.y; target = event.detail.target; } function panUp(gestureEvent: GestureCustomEvent) { gesturePluginOptions = { color: getColor(), fadeTime: 500, lineWidth }; } let gesturePluginOptions = $state({ color: '#00ff00', fadeTime: 500, lineWidth }); const getColor = (): string => { let n = (Math.random() * 0xfffff * 1000000).toString(16); return '#' + n.slice(0, 6); }; ``` ```html
({ plugins: [highlightPlugin(gesturePluginOptions)] })} onpan={handler} onpanup={panUp} style="width:500px;height:500px;border:1px solid black;max-width:100%;" > pan: {x} {y}
target: {target}
``` -------------------------------- ### Pan Gesture - Detect Dragging Movements in Svelte Source: https://context7.com/rezi/svelte-gestures/llms.txt The pan gesture detects pointer movement after a delay, providing continuous drag tracking. It utilizes pointer events for cross-platform compatibility. This example shows how to capture position and pointer type during a pan event. ```typescript import { useSwipe, usePan, type PanCustomEvent } from 'svelte-gestures'; let position = $state({ x: 0, y: 0 }); let pointerType = $state(''); function handlePan(event: PanCustomEvent) { position = { x: event.detail.x, y: event.detail.y }; pointerType = event.detail.pointerType; } function handlePanMove(event: GestureCustomEvent) { console.log('Moving at', event.detail.x, event.detail.y); }
({ delay: 300, touchAction: 'none' }), { onpanmove: handlePanMove } )}> Drag me! Position: {position.x}, {position.y}
``` -------------------------------- ### Press Gesture - Detect Long Press Actions in Svelte Source: https://context7.com/rezi/svelte-gestures/llms.txt The press gesture triggers after a pointer is held down for a specified duration, with tolerance for slight movement. This example shows how to detect a long press, its location, and the number of pointers involved. It supports triggering before or after pointer release. ```typescript import { usePress, type PressCustomEvent } from 'svelte-gestures'; let pressed = $state(false); let pressLocation = $state({ x: 0, y: 0 }); function handlePress(event: PressCustomEvent) { pressed = true; pressLocation = { x: event.detail.x, y: event.detail.y }; setTimeout(() => pressed = false, 1000); } function handlePressMove(event: GestureCustomEvent) { console.log('Pressing with', event.detail.pointersCount, 'pointers'); }
({ timeframe: 400, spread: 4, // Max movement in pixels triggerBeforeFinished: false, touchAction: 'none' }), { onpressmove: handlePressMove } )}> {pressed ? 'Pressed!' : 'Long press me'} at ({pressLocation.x}, {pressLocation.y})
``` -------------------------------- ### Touch Points Plugin - Visualize Active Pointers with Svelte Source: https://context7.com/rezi/svelte-gestures/llms.txt Visualizes active touch points by displaying colored circles around them, aiding in the debugging of multi-touch interactions and for demonstrations. It integrates with gestures like `usePinch` and allows customization of color, z-index, and circle size. ```typescript import { usePinch, touchPointPlugin } from 'svelte-gestures'; let scale = $state(1); function handlePinch(event) { scale = event.detail.scale; }
({ touchAction: 'none', plugins: [ touchPointPlugin({ color: '#ff00ff', zIndex: 999999, size: 30 }) ] }) )} style="transform: scale({scale})"> Pinch with touch visualization (scale: {scale.toFixed(2)})
``` -------------------------------- ### Svelte Gestures Plugin Event Handlers (JavaScript) Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/plugins/plugin-highlight.ts.html This object exports the event handler functions for the Svelte Gestures plugin: onMove for drawing highlights during pointer movement, onDown for initializing the plugin, onUp for cleanup when gestures end, and onDestroy for explicit destruction. It also includes an onInit handler that resets positions and initializes the plugin if active pointers exist. ```javascript return { onMove: (dispatchEvent: DispatchEvent): void => { draw(dispatchEvent.event); }, onDown: (dispatchEvent: DispatchEvent): void => { onInit(dispatchEvent); }, onUp: ( dispatchEvent: DispatchEvent, activeEvents: PointerEvent[] ): void => { if (activeEvents.length === 0) { onDestroy(); } }, onDestroy: onDestroy, onInit: (activeEvents: PointerEvent[]): void => { if (activeEvents.length) { pos.x = undefined; pos.y = undefined; onInit(); } }, }; ``` -------------------------------- ### Vibrate Plugin Options in TypeScript Source: https://github.com/rezi/svelte-gestures/blob/main/README.md Defines the options for the experimental vibrate plugin, which provides haptic feedback. It accepts a vibration sequence array, similar to the navigator.vibrate API. ```typescript { vibrationSequence: number[]; } ``` -------------------------------- ### JavaScript Rotate Gesture Composition API Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/gestures/rotate/rotate.svelte.ts.html The `rotateComposition` function provides a way to extract the core logic of the rotate gesture, making it usable outside of the `useRotate` hook. It returns the necessary event handler functions (`onMove`, `onDown`, `onUp`) and configuration parameters, allowing for more flexible integration into custom gesture setups. ```javascript export const rotateComposition = ( node: HTMLElement, inputParameters?: Partial ): SubGestureFunctions => { const { onMove, onDown, onUp, parameters } = rotateBase( node, inputParameters ); return { onMove, onDown, onUp, plugins: parameters.plugins, }; }; ``` -------------------------------- ### TypeScript Highlight Plugin Implementation Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/plugins/plugin-highlight.ts.html The highlight plugin for svelte-gestures allows for drawing visual highlights on the screen, typically used for touch or mouse interactions. It supports customizable colors, fade times, z-index, and line width. The plugin manages canvas drawing, fading animations, and resizing to fit the window. Dependencies include the shared 'GesturePlugin' and 'DispatchEvent' types. ```typescript import type { DispatchEvent, GesturePlugin } from '../shared'; export type HighlightPluginFn = (options: { color?: string; fadeTime?: number; zIndex?: number; lineWidth?: number; }) => GesturePlugin; export const highlightPlugin: HighlightPluginFn = (options) => { const fallbacks = { color: '#00ff00', fadeTime: 1000, zIndex: 1000000, lineWidth: 4, }; let canvas: HTMLCanvasElement | undefined = undefined; let ctx: CanvasRenderingContext2D | null = null; let offScreenCanvas: HTMLCanvasElement | undefined = undefined; let offScreenCtx: CanvasRenderingContext2D | null; let fadingRunning = false; let animationStepTime = Date.now(); const pos: { x?: number; y?: number; } = { x: undefined, y: undefined }; function animate(): void { const fadeTime = options.fadeTime ?? fallbacks.fadeTime; const now = Date.now(); const deltaTime = now - animationStepTime; if (deltaTime > fadeTime / 20) { if (ctx && offScreenCanvas && offScreenCtx && canvas) { offScreenCtx.drawImage(canvas, 0, 0); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.globalAlpha = 1 - (deltaTime * 3) / fadeTime; ctx.drawImage(offScreenCanvas, 0, 0); ctx.globalAlpha = 1; offScreenCtx.clearRect(0, 0, canvas.width, canvas.height); } animationStepTime = now; } if (fadingRunning) { requestAnimationFrame(animate); } } function setPosition(e: { x: number; y: number }): void { pos.x = e.x; pos.y = e.y; } function resize(): void { if (ctx && offScreenCanvas && canvas) { ctx.canvas.width = window.innerWidth; ctx.canvas.height = window.innerHeight; offScreenCanvas.width = canvas.width; offScreenCanvas.height = canvas.height; } } function draw(e: { x: number; y: number }): void { if (ctx) { ctx.beginPath(); ctx.lineWidth = options.lineWidth ?? fallbacks.lineWidth; ctx.lineCap = 'round'; ctx.strokeStyle = options.color ?? fallbacks.color; if (pos.x !== undefined && pos.y !== undefined) { ctx.moveTo(pos.x, pos.y); setPosition(e); ctx.lineTo(pos.x, pos.y); } else { setPosition(e); } ctx.stroke(); } } return { setup: (canvasElement, pointerDown, pointerMove, pointerUp) => { canvas = canvasElement as HTMLCanvasElement; ctx = canvas.getContext('2d'); offScreenCanvas = document.createElement('canvas'); offScreenCtx = offScreenCanvas.getContext('2d'); fadingRunning = true; animationStepTime = Date.now(); resize(); requestAnimationFrame(animate); canvas.addEventListener('pointerdown', pointerDown); canvas.addEventListener('pointermove', pointerMove); canvas.addEventListener('pointerup', pointerUp); window.addEventListener('resize', resize); }, pointerDown: (e) => { if (e.event.buttons === 1) { draw(e); } }, pointerMove: (e) => { if (e.event.buttons === 1) { draw(e); } }, pointerUp: () => { if (ctx && canvas) { ctx.globalAlpha = 1; fadingRunning = true; animationStepTime = Date.now(); requestAnimationFrame(animate); } }, destroy: () => { fadingRunning = false; if (canvas) { canvas.removeEventListener('pointerdown', () => {}); canvas.removeEventListener('pointermove', () => {}); canvas.removeEventListener('pointerup', () => {}); } window.removeEventListener('resize', resize); }, }; }; ``` -------------------------------- ### TypeScript Function Signature for setPointerControls Source: https://github.com/rezi/svelte-gestures/blob/main/README_5.0.7.md This TypeScript function signature defines the parameters required for setting up pointer controls for custom gestures. It includes the gesture name, the target HTML node, and callback functions for move, down, and up events. Callbacks can be set to null if not needed. ```typescript function setPointerControls( gestureName: string, node: HTMLElement, onMoveCallback: (activeEvents: PointerEvent[], event: PointerEvent) => void, onDownCallback: (activeEvents: PointerEvent[], event: PointerEvent) => void, onUpCallback: (activeEvents: PointerEvent[], event: PointerEvent) => void ); ``` -------------------------------- ### Shape Gesture Configuration Options Source: https://github.com/rezi/svelte-gestures/blob/main/README.md Configure the shapeGesture recognizer with various options. Define shapes with points and rotation/direction settings, set timeframes, thresholds for accuracy, sample point counts, touch actions, and composition options. Plugins can also be added. ```javascript { shapes: { name: string; points: { x: number; y: number }[]; allowRotation?: boolean; // default: false bothDirections?: boolean; // default: true }[]; timeframe?: number; // default: 1000ms threshold?: number; // default: 0.9 (0 to 1) nbOfSamplePoints?: number; // default: 64 touchAction?: string; // default: 'auto' composed?: boolean; // applicable with composedGesture plugins?: any[]; } ``` -------------------------------- ### Istanbul Code Coverage Report Generation Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/gestures/tap/index.html This snippet shows a common JavaScript pattern for executing code coverage reports using Istanbul. It typically runs as part of a build or test process and outputs an HTML report. ```html

Code coverage generated by [istanbul](https://istanbul.js.org/) at 2025-09-21T08:29:33.855Z

``` -------------------------------- ### Implement Tap Gesture in Svelte Source: https://github.com/rezi/svelte-gestures/blob/main/README_5.0.7.md This code illustrates the implementation of a tap gesture using the `tap` action from 'svelte-gestures'. It captures the tap's X and Y coordinates, target element, and pointer type. The gesture's `timeframe` and `touchAction` CSS property are configurable, with the tap event firing only upon completion within the specified timeframe. ```html
tap: {x} {y}
``` -------------------------------- ### JavaScript Code Coverage Initialization Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/gestures/composed-gesture/index.html JavaScript code to initialize pretty printing for code coverage reports. This function is typically called when the window loads. ```javascript window.onload = function () { prettyPrint(); }; ``` -------------------------------- ### usePan Gesture Attachment Source: https://github.com/rezi/svelte-gestures/blob/main/README.md The usePan attachment facilitates drag-like gestures. It fires a PanCustomEvent with details about the pointer's position (x, y) relative to the element, the event target, and the pointer type. Options like delay, touchAction, composed, and plugins can customize its behavior. ```javascript import { usePan } from 'svelte-gestures'; // Basic usage: const { pan, onpan } = usePan(myHandler, () => ({ delay: 100 })); // With advanced options: const { pan: panWithOpts, onpan: onpanWithOpts } = usePan( myHandler, () => ({ delay: 50, touchAction: ['pan-y'], plugins: [myPlugin] }), { onpanstart: handlePanStart, onpanend: handlePanEnd } ); ``` -------------------------------- ### Swipe Gesture Source: https://github.com/rezi/svelte-gestures/blob/main/README.md The useSwipe action detects swipe gestures. It fires a 'swipe' event with details about the direction, target, and pointer type. Configuration options include timeframe, minimum swipe distance, and touch action. ```APIDOC ## Swipe Gesture ### Description Detects swipe gestures and fires a `swipe` event. ### Method Use `useSwipe` action. ### Event `swipe` ### Event Detail - **direction** ('top' | 'right' | 'bottom' | 'left') - The direction of the swipe. - **target** (HTMLElement) - The element where the swipe started. - **pointerType** ('touch' | 'mouse' | 'pen') - The type of pointer used. ### Options - **timeframe** (number) - Maximum time in ms for a swipe (default: 300ms). - **minSwipeDistance** (number) - Minimum distance in px for a swipe (default: 60px). - **touchAction** (string) - CSS `touch-action` style (default: 'none'). - **composed** (boolean) - Applicable when used inside `composedGesture`. - **plugins** (Array) - An array of plugins to apply. ### Example Usage ```javascript import { useSwipe } from 'svelte-gestures';
Swipe me!
``` ``` -------------------------------- ### Svelte Hook for Press Gesture Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/gestures/press/press.svelte.ts.html The `usePress` hook allows components to easily integrate the press gesture. It takes event handlers and optional parameters, returning props to be spread onto an element. It manages pointer controls and cleans up event listeners. ```typescript export function usePress( handler: (e: PressCustomEvent) => void, inputParameters?: () => Partial, baseHandlers?: Partial< Record void> >, isRaw = false as T ): ReturnPress { const { setPointerControls } = createPointerControls(); const gesturePropName = isRaw ? gestureName : createAttachmentKey();   return { ...baseHandlers, [`on${gestureName}` as OnEventType]: handler, [gesturePropName]: (node: HTMLElement) => { const { onMove, onDown, onUp, parameters, clearTimeoutWrap } = pressBase( node, inputParameters?.() );   const onSharedDestroy = setPointerControls( gestureName, node, onMove, onDown, onUp, parameters.touchAction, parameters.plugins );   return (): void => { onSharedDestroy.destroy(); clearTimeoutWrap(); }; }, } as ReturnPress; } ``` -------------------------------- ### Tap Gesture Source: https://github.com/rezi/svelte-gestures/blob/main/README.md The useTap action detects tap gestures. It fires a 'tap' event when a pointer is released within a specified timeframe. The event detail includes coordinates, target, and pointer type. ```APIDOC ## Tap Gesture ### Description Detects tap gestures and fires a `tap` event upon pointer release within a timeframe. ### Method Use `useTap` action. ### Event `tap` ### Event Detail - **x** (number) - The x-coordinate of the tap. - **y** (number) - The y-coordinate of the tap. - **target** (HTMLElement) - The element that was tapped. - **pointerType** ('touch' | 'mouse' | 'pen') - The type of pointer used. ### Options - **timeframe** (number) - Maximum time in ms for a tap (default: 300ms). - **touchAction** (string) - CSS `touch-action` style (default: 'auto'). - **composed** (boolean) - Applicable when used inside `composedGesture`. - **plugins** (Array) - An array of plugins to apply. ### Example Usage ```javascript import { useTap } from 'svelte-gestures';
Tap me!
``` ``` -------------------------------- ### Base Swipe Logic Implementation in TypeScript Source: https://github.com/rezi/svelte-gestures/blob/main/coverage/src/gestures/swipe/swipe.svelte.ts.html Implements the core logic for detecting swipe gestures. It tracks pointer movements, calculates swipe distance and direction, and dispatches a custom event when a swipe is recognized. It handles horizontal and vertical swipes based on distance thresholds and orientation, and includes parameters for timeframe and minimum swipe distance. Dependencies include custom types like `SwipeParameters`, `Direction`, and `SwipePointerEventDetail`. ```typescript function swipeBase( node: HTMLElement, inputParameters?: Partial ): { onDown: (activeEvents: PointerEvent[], event: PointerEvent) => void; onUp: (activeEvents: PointerEvent[], event: PointerEvent) => void; parameters: SwipeParameters; } { const parameters: SwipeParameters = { timeframe: DEFAULT_DELAY, minSwipeDistance: DEFAULT_MIN_SWIPE_DISTANCE, touchAction: DEFAULT_TOUCH_ACTION, composed: false, ...inputParameters, }; let startTime: number; let clientX: number; let clientY: number; let target: EventTarget | null; function onDown(activeEvents: PointerEvent[], event: PointerEvent): void { clientX = event.clientX; clientY = event.clientY; startTime = Date.now(); if (activeEvents.length === 1) { target = event.target; } } function onUp(activeEvents: PointerEvent[], event: PointerEvent): void { if ( event.type === 'pointerup' && activeEvents.length === 0 && Date.now() - startTime < parameters.timeframe ) { const x = event.clientX - clientX; const y = event.clientY - clientY; const absX = Math.abs(x); const absY = Math.abs(y); let direction: Direction = null; if (absX >= 2 * absY && absX > parameters.minSwipeDistance) { // horizontal (by *2 we eliminate diagonal movements) direction = x > 0 ? 'right' : 'left'; } else if (absY >= 2 * absX && absY > parameters.minSwipeDistance) { // vertical (by *2 we eliminate diagonal movements) direction = y > 0 ? 'bottom' : 'top'; } if (direction) { node.dispatchEvent( new CustomEvent(gestureName, { detail: { direction, target, pointerType: event.pointerType }, }) ); } } } return { onDown, onUp, parameters }; } ``` -------------------------------- ### useSwipe Gesture Attachment with isRaw option Source: https://github.com/rezi/svelte-gestures/blob/main/README.md Demonstrates the useSwipe gesture attachment with the 'isRaw' option enabled. This allows for programmatic attachment of event handlers using `@attach` syntax or `addEventListener`, which is useful for elements like svelte:body where spread properties are not permitted. The 'isRaw' option changes the return format of the gesture function. ```typescript ```