): 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
```