fix: prevent asset conflicts between React and Grid.js versions

Add coexistence checks to all enqueue methods to prevent loading
both React and Grid.js assets simultaneously.

Changes:
- ReactAdmin.php: Only enqueue React assets when ?react=1
- Init.php: Skip Grid.js when React active on admin pages
- Form.php, Coupon.php, Access.php: Restore classic assets when ?react=0
- Customer.php, Product.php, License.php: Add coexistence checks

Now the toggle between Classic and React versions works correctly.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
dwindown
2026-04-18 17:02:14 +07:00
parent bd9cdac02e
commit e8fbfb14c1
74973 changed files with 6658406 additions and 71 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,62 @@
import { EventStore } from "./EventStore.js";
import { TimeoutStore } from "./TimeoutStore.js";
import { GestureKey, InternalConfig, InternalHandlers, NativeHandlers, State, UserGestureConfig } from "./types.js";
export declare class Controller {
/**
* The list of gestures handled by the Controller.
*/
gestures: Set<GestureKey>;
/**
* The event store that keeps track of the config.target listeners.
*/
private _targetEventStore;
/**
* Object that keeps track of all gesture event listeners.
*/
gestureEventStores: {
[key in GestureKey]?: EventStore;
};
gestureTimeoutStores: {
[key in GestureKey]?: TimeoutStore;
};
handlers: InternalHandlers;
private nativeHandlers?;
config: InternalConfig;
pointerIds: Set<number>;
touchIds: Set<number>;
state: State;
constructor(handlers: InternalHandlers);
/**
* Sets pointer or touch ids based on the event.
* @param event
*/
setEventIds(event: TouchEvent | PointerEvent): Set<number> | undefined;
/**
* Attaches handlers to the controller.
* @param handlers
* @param nativeHandlers
*/
applyHandlers(handlers: InternalHandlers, nativeHandlers?: NativeHandlers): void;
/**
* Compute and attaches a config to the controller.
* @param config
* @param gestureKey
*/
applyConfig(config: UserGestureConfig, gestureKey?: GestureKey): void;
/**
* Cleans all side effects (listeners, timeouts). When the gesture is
* destroyed (in React, when the component is unmounted.)
*/
clean(): void;
/**
* Executes side effects (attaching listeners to a `config.target`). Ran on
* each render.
*/
effect(): () => void;
/**
* The bind function that can be returned by the gesture handler (a hook in
* React for example.)
* @param args
*/
bind(...args: any[]): any;
}

View File

@@ -0,0 +1,10 @@
import type { Controller } from "./Controller.js";
import { GestureKey } from "./types.js";
export declare class EventStore {
private _listeners;
private _ctrl;
private _gestureKey?;
constructor(ctrl: Controller, gestureKey?: GestureKey);
add(element: EventTarget, device: string, action: string, handler: (event: any) => void, options?: AddEventListenerOptions): () => void;
clean(): void;
}

View File

@@ -0,0 +1,6 @@
export declare class TimeoutStore {
private _timeouts;
add<FunctionType extends (...args: any[]) => any>(key: string, callback: FunctionType, ms?: number, ...args: Parameters<FunctionType>): void;
remove(key: string): void;
clean(): void;
}

View File

@@ -0,0 +1,11 @@
import { GestureKey, EngineClass, Action } from "./types.js";
import { ResolverMap } from "./config/resolver.js";
export declare const EngineMap: Map<GestureKey, EngineClass<any>>;
export declare const ConfigResolverMap: Map<GestureKey, ResolverMap>;
export declare function registerAction(action: Action): void;
export declare const dragAction: Action;
export declare const hoverAction: Action;
export declare const moveAction: Action;
export declare const pinchAction: Action;
export declare const scrollAction: Action;
export declare const wheelAction: Action;

View File

@@ -0,0 +1,11 @@
import { GestureKey, InternalConfig, UserGestureConfig } from "../types.js";
export type Resolver = (x: any, key: string, obj: any) => any;
export type ResolverMap = {
[k: string]: Resolver | ResolverMap | boolean;
};
export declare function resolveWith<T extends {
[k: string]: any;
}, V extends {
[k: string]: any;
}>(config: Partial<T> | undefined, resolvers: ResolverMap): V;
export declare function parse(newConfig: UserGestureConfig, gestureKey?: GestureKey, _config?: any): InternalConfig;

View File

@@ -0,0 +1,137 @@
import { Controller } from "../Controller.js";
import { GestureKey, IngKey, State, Vector2 } from "../types.js";
import { NonUndefined } from "../types.js";
export interface Engine<Key extends GestureKey> {
/**
* Function that some gestures can use to add initilization
* properties to the state when it is created.
*/
init?(): void;
/**
* Setup function that some gestures can use to set additional properties of
* the state when the gesture starts.
*/
setup?(): void;
/**
* Function used by some gestures to determine the intentionality of a
* a movement depending on thresholds. The intent function can change the
* `state._active` or `state._blocked` flags if the gesture isn't intentional.
* @param event
*/
axisIntent?(event?: UIEvent): void;
restrictToAxis?(movement: Vector2): void;
}
export declare abstract class Engine<Key extends GestureKey> {
/**
* The Controller handling state.
*/
ctrl: Controller;
/**
* The gesture key ('drag' | 'pinch' | 'wheel' | 'scroll' | 'move' | 'hover')
*/
readonly key: Key;
/**
* The key representing the active state of the gesture in the shared state.
* ('dragging' | 'pinching' | 'wheeling' | 'scrolling' | 'moving' | 'hovering')
*/
abstract readonly ingKey: IngKey;
/**
* The arguments passed to the `bind` function.
*/
/**
* State prop that aliases state values (`xy` or `da`).
*/
abstract readonly aliasKey: string;
args: any[];
constructor(ctrl: Controller, args: any[], key: Key);
/**
* Function implemented by gestures that compute the offset from the state
* movement.
*/
abstract computeOffset(): void;
/**
* Function implemented by the gestures that compute the movement from the
* corrected offset (after bounds and potential rubberbanding).
*/
abstract computeMovement(): void;
/**
* Executes the bind function so that listeners are properly set by the
* Controller.
* @param bindFunction
*/
abstract bind(bindFunction: (device: string, action: string, handler: (event: any) => void, options?: AddEventListenerOptions) => void): void;
/**
* Shortcut to the gesture state read from the Controller.
*/
get state(): NonNullable<State[Key]>;
set state(state: NonNullable<State[Key]>);
/**
* Shortcut to the shared state read from the Controller
*/
get shared(): import("../types.js").SharedGestureState;
/**
* Shortcut to the gesture event store read from the Controller.
*/
get eventStore(): NonNullable<{
drag?: import("../EventStore.js").EventStore | undefined;
wheel?: import("../EventStore.js").EventStore | undefined;
scroll?: import("../EventStore.js").EventStore | undefined;
move?: import("../EventStore.js").EventStore | undefined;
hover?: import("../EventStore.js").EventStore | undefined;
pinch?: import("../EventStore.js").EventStore | undefined;
}[Key]>;
/**
* Shortcut to the gesture timeout store read from the Controller.
*/
get timeoutStore(): NonNullable<{
drag?: import("../TimeoutStore.js").TimeoutStore | undefined;
wheel?: import("../TimeoutStore.js").TimeoutStore | undefined;
scroll?: import("../TimeoutStore.js").TimeoutStore | undefined;
move?: import("../TimeoutStore.js").TimeoutStore | undefined;
hover?: import("../TimeoutStore.js").TimeoutStore | undefined;
pinch?: import("../TimeoutStore.js").TimeoutStore | undefined;
}[Key]>;
/**
* Shortcut to the gesture config read from the Controller.
*/
get config(): NonNullable<import("../types.js").InternalConfig[Key]>;
/**
* Shortcut to the shared config read from the Controller.
*/
get sharedConfig(): import("../types.js").InternalGenericOptions;
/**
* Shortcut to the gesture handler read from the Controller.
*/
get handler(): NonNullable<import("../types.js").InternalHandlers[Key]>;
reset(): void;
/**
* Function ran at the start of the gesture.
* @param event
*/
start(event: NonUndefined<State[Key]>['event']): void;
/**
* Assign raw values to `state._values` and transformed values to
* `state.values`.
* @param values
*/
computeValues(values: Vector2): void;
/**
* Assign `state._values` to `state._initial` and transformed `state.values` to
* `state.initial`.
* @param values
*/
computeInitial(): void;
/**
* Computes all sorts of state attributes, including kinematics.
* @param event
*/
compute(event?: NonUndefined<State[Key]>['event']): void;
/**
* Fires the gesture handler.
*/
emit(): void;
/**
* Cleans the gesture timeouts and event listeners.
*/
clean(): void;
}

View File

@@ -0,0 +1,2 @@
export { Controller } from "./Controller.js";
export { parseMergedHandlers } from "./parser.js";

View File

@@ -0,0 +1,6 @@
import { GestureHandlers, UserGestureConfig } from "./types.js";
export declare function parseMergedHandlers(mergedHandlers: GestureHandlers, mergedConfig: UserGestureConfig): {
handlers: {};
config: UserGestureConfig;
nativeHandlers: any;
};

View File

@@ -0,0 +1 @@
export * from "./types/index.js";

View File

@@ -0,0 +1,12 @@
import type { ResolverMap } from "../config/resolver.js";
import type { Controller } from "../Controller.js";
import type { Engine } from "../engines/Engine.js";
import { GestureKey } from "./config.js";
export type EngineClass<Key extends GestureKey> = {
new (controller: Controller, args: any[], key: Key): Engine<Key>;
};
export type Action = {
key: GestureKey;
engine: EngineClass<GestureKey>;
resolver: ResolverMap;
};

View File

@@ -0,0 +1,244 @@
import { State } from "./state.js";
import { Vector2, Target, PointerType, NonUndefined } from "./utils.js";
export type GestureKey = Exclude<keyof State, 'shared'>;
export type CoordinatesKey = Exclude<GestureKey, 'pinch'>;
export type GenericOptions = {
/**
* Lets you specify a dom node or ref you want to attach the gesture to.
*/
target?: Target;
/**
* Lets you specify which window element the gesture should bind events to
* (only relevant for the drag gesture).
*/
window?: EventTarget;
/**
* Lets you customize if you want events to be passive or captured.
*/
eventOptions?: AddEventListenerOptions;
/**
* When set to false none of the handlers will be fired.
*/
enabled?: boolean;
/**
* A function that you can use to transform movement and offset values. Useful
* to map your screen coordinates to custom space coordinates such as a
* canvas.
*/
transform?: (v: Vector2) => Vector2;
};
export type GestureOptions<T extends GestureKey> = GenericOptions & {
/**
* Whether the gesture is enabled.
*/
enabled?: boolean;
/**
* Lets you customize if you want events to be passive or captured.
*/
eventOptions?: AddEventListenerOptions;
/**
* The position `offset` will start from.
*/
from?: Vector2 | ((state: NonUndefined<State[T]>) => Vector2);
/**
* The handler will fire only when the gesture displacement is greater than
* the threshold.
*/
threshold?: number | Vector2;
/**
* The handler will preventDefault all events when `true`.
*/
preventDefault?: boolean;
/**
* Forces the handler to fire even for non intentional displacement (ignores
* the threshold). In that case, the intentional attribute from state will
* remain false until the threshold is reached.
*/
triggerAllEvents?: boolean;
/**
* The elasticity coefficient of the gesture when going out of bounds. When
* set to true, the elasticiy coefficient will be defaulted to 0.15
*/
rubberband?: boolean | number | Vector2;
/**
* A function that you can use to transform movement and offset values. Useful
* to map your screen coordinates to custom space coordinates such as a
* canvas.
*/
transform?: (v: Vector2) => Vector2;
};
export type Bounds = {
top?: number;
bottom?: number;
left?: number;
right?: number;
};
export type CoordinatesConfig<Key extends CoordinatesKey = CoordinatesKey> = GestureOptions<Key> & {
/**
* The handler will only trigger if a movement is detected on the specified
* axis.
*/
axis?: 'x' | 'y' | 'lock';
/**
* Limits the gesture `offset` to the specified bounds.
*/
bounds?: Bounds | ((state: State[Key]) => Bounds);
/**
* Determines the number of pixels in one direction needed for axises to be
* calculated.
*/
axisThreshold?: number;
};
export type PinchBounds = {
min?: number;
max?: number;
};
export type ModifierKey = 'ctrlKey' | 'altKey' | 'metaKey' | null;
export type PinchConfig = GestureOptions<'pinch'> & {
pointer?: {
/**
* If true, pinch will use touch events on touch-enabled devices.
*/
touch?: boolean;
};
/**
* Limits the scale `offset` to the specified bounds.
*/
scaleBounds?: PinchBounds | ((state: State['pinch']) => PinchBounds);
/**
* Limits the angle `offset` to the specified bounds.
*/
angleBounds?: PinchBounds | ((state: State['pinch']) => PinchBounds);
/**
* Scales OR rotates when set to 'lock'.
*/
axis?: 'lock' | undefined;
/**
* Key that triggers scale when using the wheel. Defaults to `'ctrlKey'`.
*/
modifierKey?: ModifierKey | NonNullable<ModifierKey>[];
/**
* Whether wheel should trigger a pinch at all.
*/
pinchOnWheel?: boolean;
};
export type DragBounds = Bounds | HTMLElement | {
current: HTMLElement | null;
};
type MoveAndHoverMouseOnly = {
/**
* If false, onMove or onHover handlers will also fire on touch devices.
*/
mouseOnly?: boolean;
};
export type MoveConfig = CoordinatesConfig<'move'> & MoveAndHoverMouseOnly;
export type HoverConfig = MoveAndHoverMouseOnly;
export type DragConfig = Omit<CoordinatesConfig<'drag'>, 'axisThreshold' | 'bounds'> & {
/**
* If true, the component won't trigger your drag logic if the user just clicked on the component.
*/
filterTaps?: boolean;
/**
* The maximum total displacement a tap can have
*/
tapsThreshold?: number;
/**
* Set this option to true when using with @react-three/fiber objects.
*/
/**
* Limits the gesture `offset` to the specified bounds. Can be a ref or a dom
* node.
*/
bounds?: DragBounds | ((state: State['drag']) => DragBounds);
pointer?: {
/**
* The buttons combination that would trigger the drag. Use `-1` to allow
* for any button combination to start the drag.
*/
buttons?: number | number[];
/**
* If true, drag will use touch events on touch-enabled devices.
*/
touch?: boolean;
/**
* If true, drag will use touch events on touch-enabled devices, and use
* mouse events on non touch devices.
*/
mouse?: boolean;
/**
* If false, will disable KeyboardEvents that would otherwise trigger the
* drag gesture when the element is focused. Defaults to true.
*/
keys?: boolean;
/**
* Doesn't use setPointerCapture when false and delegate drag handling to
* window
*/
capture?: boolean;
/**
* Will perform a pointer lock when drag starts, and exit pointer lock when
* drag ends,
*/
lock?: boolean;
};
swipe?: {
/**
* The minimum velocity per axis (in pixels / ms) the drag gesture needs to
* reach before the pointer is released.
*/
velocity?: number | Vector2;
/**
* The minimum distance per axis (in pixels) the drag gesture needs to
* travel to trigger a swipe. Defaults to 50.
*/
distance?: number | Vector2;
/**
* The maximum duration in milliseconds that a swipe is detected. Defaults
* to 250.
*/
duration?: number;
};
/**
* If set, the drag will be triggered after the duration of the delay (in ms).
* When set to true, delay is defaulted to 250ms.
*/
preventScroll?: boolean | number;
/**
* If set, the drag will allow scrolling in the direction of this axis until
* the preventScroll duration has elapsed. Defaults to only 'y'.
*/
preventScrollAxis?: 'x' | 'y' | 'xy';
/**
* If set, the handler will be delayed for the duration of the delay (in ms)
* — or if the user starts moving. When set to true, delay is defaulted
* to 180ms.
*/
delay?: boolean | number;
/**
* Key-number record that determines for each device (`'mouse'`, `'touch'`,
* `'pen'`) the number of pixels of drag in one direction needed for axises to
* be calculated.
*/
axisThreshold?: Partial<Record<PointerType, number>>;
/**
* The distance (in pixels) emulated by arrow keys.
*/
keyboardDisplacement?: number;
};
export type UserDragConfig = GenericOptions & DragConfig;
export type UserPinchConfig = GenericOptions & PinchConfig;
export type UserWheelConfig = GenericOptions & CoordinatesConfig<'wheel'>;
export type UserScrollConfig = GenericOptions & CoordinatesConfig<'scroll'>;
export type UserMoveConfig = GenericOptions & MoveConfig;
export type UserHoverConfig = GenericOptions & HoverConfig;
export type UserGestureConfig = GenericOptions & {
drag?: DragConfig;
wheel?: CoordinatesConfig<'wheel'>;
scroll?: CoordinatesConfig<'scroll'>;
move?: MoveConfig;
pinch?: PinchConfig;
hover?: {
enabled?: boolean;
} & HoverConfig;
};
export {};

View File

@@ -0,0 +1,48 @@
import { FullGestureState, State, EventTypes } from "./state.js";
import { GestureKey } from "./config.js";
import { DOMHandlers, EventHandler } from "./utils.js";
export type Handler<Key extends GestureKey, EventType = EventTypes[Key]> = (state: Omit<FullGestureState<Key>, 'event'> & {
event: EventType;
}) => any | void;
type check<T extends AnyHandlerEventTypes, Key extends GestureKey> = undefined extends T[Key] ? EventTypes[Key] : T[Key];
export type UserHandlers<T extends AnyHandlerEventTypes = EventTypes> = {
onDrag: Handler<'drag', check<T, 'drag'>>;
onDragStart: Handler<'drag', check<T, 'drag'>>;
onDragEnd: Handler<'drag', check<T, 'drag'>>;
onPinch: Handler<'pinch', check<T, 'pinch'>>;
onPinchStart: Handler<'pinch', check<T, 'pinch'>>;
onPinchEnd: Handler<'pinch', check<T, 'pinch'>>;
onWheel: Handler<'wheel', check<T, 'wheel'>>;
onWheelStart: Handler<'wheel', check<T, 'wheel'>>;
onWheelEnd: Handler<'wheel', check<T, 'wheel'>>;
onMove: Handler<'move', check<T, 'move'>>;
onMoveStart: Handler<'move', check<T, 'move'>>;
onMoveEnd: Handler<'move', check<T, 'move'>>;
onScroll: Handler<'scroll', check<T, 'scroll'>>;
onScrollStart: Handler<'scroll', check<T, 'scroll'>>;
onScrollEnd: Handler<'scroll', check<T, 'scroll'>>;
onHover: Handler<'hover', check<T, 'hover'>>;
};
type NativeHandlersKeys = keyof Omit<DOMHandlers, keyof UserHandlers>;
type GetEventType<Key extends NativeHandlersKeys> = DOMHandlers[Key] extends EventHandler<infer EventType> | undefined ? EventType : UIEvent;
export type NativeHandlers<T extends AnyHandlerEventTypes = {}> = {
[key in NativeHandlersKeys]?: (state: State['shared'] & {
event: undefined extends T[key] ? GetEventType<key> : T[key];
args: any;
}, ...args: any) => void;
};
export type AnyHandlerEventTypes = Partial<{
drag: any;
wheel: any;
scroll: any;
move: any;
pinch: any;
hover: any;
} & {
[key in NativeHandlersKeys]: any;
}>;
export type GestureHandlers<HandlerType extends AnyHandlerEventTypes = EventTypes> = Partial<NativeHandlers<HandlerType> & UserHandlers<HandlerType>>;
export type InternalHandlers = {
[Key in GestureKey]?: Handler<Key, any>;
};
export {};

View File

@@ -0,0 +1,6 @@
export * from "./config.js";
export * from "./internalConfig.js";
export * from "./state.js";
export * from "./utils.js";
export * from "./handlers.js";
export * from "./action.js";

View File

@@ -0,0 +1,68 @@
import { GestureKey, CoordinatesKey, ModifierKey } from "./config.js";
import { State } from "./state.js";
import { PointerType, Vector2 } from "./utils.js";
export type InternalGenericOptions = {
target?: () => EventTarget;
eventOptions: AddEventListenerOptions;
window: EventTarget;
enabled: boolean;
transform?: (v: Vector2) => Vector2;
};
export type InternalGestureOptions<Key extends GestureKey = GestureKey> = {
enabled: boolean;
eventOptions: AddEventListenerOptions;
from: Vector2 | ((state: State[Key]) => Vector2);
threshold: Vector2;
preventDefault: boolean;
triggerAllEvents: boolean;
rubberband: Vector2;
bounds: [Vector2, Vector2] | ((state: State[Key]) => [Vector2, Vector2]);
hasCustomTransform: boolean;
transform: (v: Vector2) => Vector2;
};
export type InternalCoordinatesOptions<Key extends CoordinatesKey = CoordinatesKey> = InternalGestureOptions<Key> & {
axis?: 'x' | 'y';
lockDirection: boolean;
axisThreshold: number;
};
export type InternalDragOptions = Omit<InternalCoordinatesOptions<'drag'>, 'axisThreshold'> & {
filterTaps: boolean;
tapsThreshold: number;
pointerButtons: number | number[];
pointerCapture: boolean;
preventScrollDelay?: number;
preventScrollAxis?: 'x' | 'y' | 'xy';
pointerLock: boolean;
keys: boolean;
device: 'pointer' | 'touch' | 'mouse';
swipe: {
velocity: Vector2;
distance: Vector2;
duration: number;
};
delay: number;
axisThreshold: Record<PointerType, number>;
keyboardDisplacement: number;
};
export type InternalPinchOptions = InternalGestureOptions<'pinch'> & {
/**
* When device is undefined, we'll be using wheel to zoom.
*/
device: 'gesture' | 'pointer' | 'touch' | undefined;
lockDirection: boolean;
modifierKey: ModifierKey | NonNullable<ModifierKey>[];
pinchOnWheel: boolean;
};
type MoveAndHoverMouseOnly = {
mouseOnly: boolean;
};
export type InternalConfig = {
shared: InternalGenericOptions;
drag?: InternalDragOptions;
wheel?: InternalCoordinatesOptions<'wheel'>;
scroll?: InternalCoordinatesOptions<'scroll'>;
move?: InternalCoordinatesOptions<'move'> & MoveAndHoverMouseOnly;
hover?: InternalCoordinatesOptions<'hover'> & MoveAndHoverMouseOnly;
pinch?: InternalPinchOptions;
};
export {};

View File

@@ -0,0 +1,272 @@
import { GestureKey } from "./config.js";
import { NonUndefined, Vector2, WebKitGestureEvent } from "./utils.js";
export type IngKey = 'dragging' | 'wheeling' | 'moving' | 'hovering' | 'scrolling' | 'pinching';
export type SharedGestureState = {
/**
* True if the element is being dragged.
*/
dragging?: boolean;
/**
* True if the element is being wheeled.
*/
wheeling?: boolean;
/**
* True if the element is being moved.
*/
moving?: boolean;
/**
* True if the element is being hovered.
*/
hovering?: boolean;
/**
* True if the element is being scrolled.
*/
scrolling?: boolean;
/**
* True if the element is being pinched.
*/
pinching?: boolean;
/**
* Number of fingers touching the screen.
*/
touches: number;
/**
* True when the main mouse button or touch is pressed.
*/
pressed: boolean;
/**
* Alias for pressed.
*/
down: boolean;
/**
* True if the document is in lock mode.
*/
locked: boolean;
/**
* Indicates which buttons are pressed (https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons).
*/
buttons: number;
/**
* True when the Shift key is pressed.
*/
shiftKey: boolean;
/**
* True when the Alt key is pressed.
*/
altKey: boolean;
/**
* True when the Meta key is pressed.
*/
metaKey: boolean;
/**
* True when the Control key is pressed.
*/
ctrlKey: boolean;
};
export type CommonGestureState = {
_active: boolean;
_blocked: boolean;
_force: boolean;
_step: [false | number, false | number];
_movementBound: [false | number, false | number];
_values: Vector2;
_initial: Vector2;
_movement: Vector2;
_distance: Vector2;
_direction: Vector2;
_delta: Vector2;
_bounds: [Vector2, Vector2];
/**
* The event triggering the gesture.
*/
event: UIEvent;
/**
* The event target.
*/
target: EventTarget;
/**
* The event current target.
*/
currentTarget: EventTarget;
/**
* True when the gesture is intentional (passed the threshold).
*/
intentional: boolean;
/**
* Cumulative distance of the gesture. Deltas are summed with their absolute
* values.
*/
distance: Vector2;
/**
* Displacement of the current gesture.
*/
movement: Vector2;
/**
* Difference between the current movement and the previous movement.
*/
delta: Vector2;
/**
* Cumulative displacements of all gestures (sum of all movements triggered
* by the handler)
*/
offset: Vector2;
/**
* Offset when the gesture started.
*/
lastOffset: Vector2;
/**
* Velocity vector.
*/
velocity: Vector2;
/**
* Current raw values of the gesture. Can be coordinates or distance / angle
* depending on the gesture.
*/
values: Vector2;
/**
* Raw values when the gesture started.
*/
initial: Vector2;
/**
* Direction per axis. `-1` when going down, `1` when going up, `0` when still.
*/
direction: Vector2;
/**
* Bound overflow per axis. `-1` when overflowing bounds to the left/top, `1` when overflowing bounds to the right/bottom.
*/
overflow: Vector2;
/**
* True when it's the first event of the active gesture.
*/
first: boolean;
/**
* True when it's the last event of the active gesture.
*/
last: boolean;
/**
* True when the gesture is active.
*/
active: boolean;
/**
* The timestamp (ms) of when the gesture started.
*/
startTime: number;
/**
* The timestamp (ms) of the current event.
*/
timeStamp: number;
/**
* Elapsed time (ms) of the current gesture.
*/
elapsedTime: number;
/**
* Time delta (ms) with the previous event.
*/
timeDelta: number;
/**
* Event type.
*/
type: string;
/**
* Value returned by your handler on its previous run.
*/
memo?: any;
/**
* The arguments passed to the bind function (only relevant in React when
* using `<div {...bind(someArgument)} />`)
*/
args?: any;
};
export type CoordinatesState = CommonGestureState & {
/**
* The initial axis (x or y) of the gesture.
*/
axis: 'x' | 'y' | undefined;
/**
* Pointer coordinates (alias to values)
*/
xy: Vector2;
};
export type DragState = CoordinatesState & {
_pointerId?: number;
_pointerActive: boolean;
_keyboardActive: boolean;
_preventScroll: boolean;
_delayed: boolean;
/**
* True when the drag gesture has been canceled by the `cancel` function.
*/
canceled: boolean;
/**
* Function that can be called to cancel the drag.
*/
cancel(): void;
/**
* True if the drag gesture is recognized as a tap (ie when the displacement
* is lower than 3px per axis).
*/
tap: boolean;
/**
* [swipeX, swipeY] is [0, 0] if no swipe detected, -1 or 1 otherwise.
*/
swipe: Vector2;
};
export interface PinchState extends CommonGestureState {
_pointerEvents: Map<number, PointerEvent>;
_touchIds: [] | [number, number];
/**
* Distance and angle raw values (alias to values).
*/
da: Vector2;
/**
* The initial axis (scale or angle) of the gesture.
*/
axis: 'scale' | 'angle' | undefined;
/**
* Coordinates of the center of touch events, or the cursor when using wheel
* to pinch.
*/
origin: Vector2;
/**
* The number of full rotation the current gesture has performed.
*/
turns: number;
/**
* True when the pinch gesture has been canceled by the `cancel` function.
*/
canceled: boolean;
/**
* Function that can be called to cancel the pinch.
*/
cancel(): void;
}
export type EventTypes = {
drag: PointerEvent | TouchEvent | MouseEvent | KeyboardEvent;
wheel: WheelEvent;
scroll: UIEvent;
move: PointerEvent;
hover: PointerEvent;
pinch: PointerEvent | TouchEvent | WheelEvent | WebKitGestureEvent;
};
export interface State {
shared: SharedGestureState;
drag?: DragState & {
event: EventTypes['drag'];
};
wheel?: CoordinatesState & {
event: EventTypes['wheel'];
};
scroll?: CoordinatesState & {
event: EventTypes['scroll'];
};
move?: CoordinatesState & {
event: EventTypes['move'];
};
hover?: CoordinatesState & {
event: EventTypes['hover'];
};
pinch?: PinchState & {
event: EventTypes['pinch'];
};
}
export type FullGestureState<Key extends GestureKey> = SharedGestureState & NonUndefined<State[Key]>;

View File

@@ -0,0 +1,169 @@
export type Vector2 = [number, number];
export type WebKitGestureEvent = PointerEvent & {
scale: number;
rotation: number;
};
export type Target = EventTarget | {
current: EventTarget | null;
};
export type PointerType = 'mouse' | 'touch' | 'pen';
export type NonUndefined<T> = T extends undefined ? never : T;
export type EventHandler<E extends Event = Event> = (event: E) => void;
export interface DOMHandlers {
onCopy?: EventHandler<ClipboardEvent>;
onCopyCapture?: EventHandler<ClipboardEvent>;
onCut?: EventHandler<ClipboardEvent>;
onCutCapture?: EventHandler<ClipboardEvent>;
onPaste?: EventHandler<ClipboardEvent>;
onPasteCapture?: EventHandler<ClipboardEvent>;
onCompositionEnd?: EventHandler<CompositionEvent>;
onCompositionEndCapture?: EventHandler<CompositionEvent>;
onCompositionStart?: EventHandler<CompositionEvent>;
onCompositionStartCapture?: EventHandler<CompositionEvent>;
onCompositionUpdate?: EventHandler<CompositionEvent>;
onCompositionUpdateCapture?: EventHandler<CompositionEvent>;
onFocus?: EventHandler<FocusEvent>;
onFocusCapture?: EventHandler<FocusEvent>;
onBlur?: EventHandler<FocusEvent>;
onBlurCapture?: EventHandler<FocusEvent>;
onChange?: EventHandler<FormDataEvent>;
onChangeCapture?: EventHandler<FormDataEvent>;
onBeforeInput?: EventHandler<FormDataEvent>;
onBeforeInputCapture?: EventHandler<FormDataEvent>;
onInput?: EventHandler<FormDataEvent>;
onInputCapture?: EventHandler<FormDataEvent>;
onReset?: EventHandler<FormDataEvent>;
onResetCapture?: EventHandler<FormDataEvent>;
onSubmit?: EventHandler<FormDataEvent>;
onSubmitCapture?: EventHandler<FormDataEvent>;
onInvalid?: EventHandler<FormDataEvent>;
onInvalidCapture?: EventHandler<FormDataEvent>;
onLoad?: EventHandler;
onLoadCapture?: EventHandler;
onError?: EventHandler;
onErrorCapture?: EventHandler;
onKeyDown?: EventHandler<KeyboardEvent>;
onKeyDownCapture?: EventHandler<KeyboardEvent>;
onKeyUp?: EventHandler<KeyboardEvent>;
onKeyUpCapture?: EventHandler<KeyboardEvent>;
onAbort?: EventHandler;
onAbortCapture?: EventHandler;
onCanPlay?: EventHandler;
onCanPlayCapture?: EventHandler;
onCanPlayThrough?: EventHandler;
onCanPlayThroughCapture?: EventHandler;
onDurationChange?: EventHandler;
onDurationChangeCapture?: EventHandler;
onEmptied?: EventHandler;
onEmptiedCapture?: EventHandler;
onEncrypted?: EventHandler;
onEncryptedCapture?: EventHandler;
onEnded?: EventHandler;
onEndedCapture?: EventHandler;
onLoadedData?: EventHandler;
onLoadedDataCapture?: EventHandler;
onLoadedMetadata?: EventHandler;
onLoadedMetadataCapture?: EventHandler;
onLoadStart?: EventHandler;
onLoadStartCapture?: EventHandler;
onPause?: EventHandler;
onPauseCapture?: EventHandler;
onPlay?: EventHandler;
onPlayCapture?: EventHandler;
onPlaying?: EventHandler;
onPlayingCapture?: EventHandler;
onProgress?: EventHandler;
onProgressCapture?: EventHandler;
onRateChange?: EventHandler;
onRateChangeCapture?: EventHandler;
onSeeked?: EventHandler;
onSeekedCapture?: EventHandler;
onSeeking?: EventHandler;
onSeekingCapture?: EventHandler;
onStalled?: EventHandler;
onStalledCapture?: EventHandler;
onSuspend?: EventHandler;
onSuspendCapture?: EventHandler;
onTimeUpdate?: EventHandler;
onTimeUpdateCapture?: EventHandler;
onVolumeChange?: EventHandler;
onVolumeChangeCapture?: EventHandler;
onWaiting?: EventHandler;
onWaitingCapture?: EventHandler;
onAuxClick?: EventHandler<MouseEvent>;
onAuxClickCapture?: EventHandler<MouseEvent>;
onClick?: EventHandler<MouseEvent>;
onClickCapture?: EventHandler<MouseEvent>;
onContextMenu?: EventHandler<MouseEvent>;
onContextMenuCapture?: EventHandler<MouseEvent>;
onDoubleClick?: EventHandler<MouseEvent>;
onDoubleClickCapture?: EventHandler<MouseEvent>;
onDrag?: EventHandler<DragEvent>;
onDragCapture?: EventHandler<DragEvent>;
onDragEnd?: EventHandler<DragEvent>;
onDragEndCapture?: EventHandler<DragEvent>;
onDragEnter?: EventHandler<DragEvent>;
onDragEnterCapture?: EventHandler<DragEvent>;
onDragExit?: EventHandler<DragEvent>;
onDragExitCapture?: EventHandler<DragEvent>;
onDragLeave?: EventHandler<DragEvent>;
onDragLeaveCapture?: EventHandler<DragEvent>;
onDragOver?: EventHandler<DragEvent>;
onDragOverCapture?: EventHandler<DragEvent>;
onDragStart?: EventHandler<DragEvent>;
onDragStartCapture?: EventHandler<DragEvent>;
onDrop?: EventHandler<DragEvent>;
onDropCapture?: EventHandler<DragEvent>;
onMouseDown?: EventHandler<MouseEvent>;
onMouseDownCapture?: EventHandler<MouseEvent>;
onMouseEnter?: EventHandler<MouseEvent>;
onMouseLeave?: EventHandler<MouseEvent>;
onMouseMove?: EventHandler<MouseEvent>;
onMouseMoveCapture?: EventHandler<MouseEvent>;
onMouseOut?: EventHandler<MouseEvent>;
onMouseOutCapture?: EventHandler<MouseEvent>;
onMouseOver?: EventHandler<MouseEvent>;
onMouseOverCapture?: EventHandler<MouseEvent>;
onMouseUp?: EventHandler<MouseEvent>;
onMouseUpCapture?: EventHandler<MouseEvent>;
onSelect?: EventHandler;
onSelectCapture?: EventHandler;
onTouchCancel?: EventHandler<TouchEvent>;
onTouchCancelCapture?: EventHandler<TouchEvent>;
onTouchEnd?: EventHandler<TouchEvent>;
onTouchEndCapture?: EventHandler<TouchEvent>;
onTouchMove?: EventHandler<TouchEvent>;
onTouchMoveCapture?: EventHandler<TouchEvent>;
onTouchStart?: EventHandler<TouchEvent>;
onTouchStartCapture?: EventHandler<TouchEvent>;
onPointerDown?: EventHandler<PointerEvent>;
onPointerDownCapture?: EventHandler<PointerEvent>;
onPointerMove?: EventHandler<PointerEvent>;
onPointerMoveCapture?: EventHandler<PointerEvent>;
onPointerUp?: EventHandler<PointerEvent>;
onPointerUpCapture?: EventHandler<PointerEvent>;
onPointerCancel?: EventHandler<PointerEvent>;
onPointerCancelCapture?: EventHandler<PointerEvent>;
onPointerEnter?: EventHandler<PointerEvent>;
onPointerLeave?: EventHandler<PointerEvent>;
onPointerOver?: EventHandler<PointerEvent>;
onPointerOverCapture?: EventHandler<PointerEvent>;
onPointerOut?: EventHandler<PointerEvent>;
onPointerOutCapture?: EventHandler<PointerEvent>;
onGotPointerCapture?: EventHandler<PointerEvent>;
onGotPointerCaptureCapture?: EventHandler<PointerEvent>;
onLostPointerCapture?: EventHandler<PointerEvent>;
onLostPointerCaptureCapture?: EventHandler<PointerEvent>;
onScroll?: EventHandler<UIEvent>;
onScrollCapture?: EventHandler<UIEvent>;
onWheel?: EventHandler<WheelEvent>;
onWheelCapture?: EventHandler<WheelEvent>;
onAnimationStart?: EventHandler<AnimationEvent>;
onAnimationStartCapture?: EventHandler<AnimationEvent>;
onAnimationEnd?: EventHandler<AnimationEvent>;
onAnimationEndCapture?: EventHandler<AnimationEvent>;
onAnimationIteration?: EventHandler<AnimationEvent>;
onAnimationIterationCapture?: EventHandler<AnimationEvent>;
onTransitionEnd?: EventHandler<TransitionEvent>;
onTransitionEndCapture?: EventHandler<TransitionEvent>;
}

View File

@@ -0,0 +1 @@
export { rubberbandIfOutOfBounds } from "./utils/maths.js";

View File

@@ -0,0 +1,11 @@
import { Vector2 } from "../types.js";
export declare function clamp(v: number, min: number, max: number): number;
export declare const V: {
toVector<T>(v: T | [T, T] | undefined, fallback?: T | [T, T] | undefined): [T, T];
add(v1: Vector2, v2: Vector2): Vector2;
sub(v1: Vector2, v2: Vector2): Vector2;
addTo(v1: Vector2, v2: Vector2): void;
subTo(v1: Vector2, v2: Vector2): void;
};
export declare function rubberbandIfOutOfBounds(position: number, min: number, max: number, constant?: number): number;
export declare function computeRubberband(bounds: [Vector2, Vector2], [Vx, Vy]: Vector2, [Rx, Ry]: Vector2): Vector2;

View File

@@ -0,0 +1,39 @@
function clamp(v, min, max) {
return Math.max(min, Math.min(v, max));
}
const V = {
toVector(v, fallback) {
if (v === undefined) v = fallback;
return Array.isArray(v) ? v : [v, v];
},
add(v1, v2) {
return [v1[0] + v2[0], v1[1] + v2[1]];
},
sub(v1, v2) {
return [v1[0] - v2[0], v1[1] - v2[1]];
},
addTo(v1, v2) {
v1[0] += v2[0];
v1[1] += v2[1];
},
subTo(v1, v2) {
v1[0] -= v2[0];
v1[1] -= v2[1];
}
};
function rubberband(distance, dimension, constant) {
if (dimension === 0 || Math.abs(dimension) === Infinity) return Math.pow(distance, constant * 5);
return distance * dimension * constant / (dimension + constant * distance);
}
function rubberbandIfOutOfBounds(position, min, max, constant = 0.15) {
if (constant === 0) return clamp(position, min, max);
if (position < min) return -rubberband(min - position, max - min, constant) + min;
if (position > max) return +rubberband(position - max, max - min, constant) + max;
return position;
}
function computeRubberband(bounds, [Vx, Vy], [Rx, Ry]) {
const [[X0, X1], [Y0, Y1]] = bounds;
return [rubberbandIfOutOfBounds(Vx, X0, X1, Rx), rubberbandIfOutOfBounds(Vy, Y0, Y1, Ry)];
}
export { V, computeRubberband as c, rubberbandIfOutOfBounds as r };

View File

@@ -0,0 +1,43 @@
'use strict';
function clamp(v, min, max) {
return Math.max(min, Math.min(v, max));
}
const V = {
toVector(v, fallback) {
if (v === undefined) v = fallback;
return Array.isArray(v) ? v : [v, v];
},
add(v1, v2) {
return [v1[0] + v2[0], v1[1] + v2[1]];
},
sub(v1, v2) {
return [v1[0] - v2[0], v1[1] - v2[1]];
},
addTo(v1, v2) {
v1[0] += v2[0];
v1[1] += v2[1];
},
subTo(v1, v2) {
v1[0] -= v2[0];
v1[1] -= v2[1];
}
};
function rubberband(distance, dimension, constant) {
if (dimension === 0 || Math.abs(dimension) === Infinity) return Math.pow(distance, constant * 5);
return distance * dimension * constant / (dimension + constant * distance);
}
function rubberbandIfOutOfBounds(position, min, max, constant = 0.15) {
if (constant === 0) return clamp(position, min, max);
if (position < min) return -rubberband(min - position, max - min, constant) + min;
if (position > max) return +rubberband(position - max, max - min, constant) + max;
return position;
}
function computeRubberband(bounds, [Vx, Vy], [Rx, Ry]) {
const [[X0, X1], [Y0, Y1]] = bounds;
return [rubberbandIfOutOfBounds(Vx, X0, X1, Rx), rubberbandIfOutOfBounds(Vy, Y0, Y1, Ry)];
}
exports.V = V;
exports.computeRubberband = computeRubberband;
exports.rubberbandIfOutOfBounds = rubberbandIfOutOfBounds;

View File

@@ -0,0 +1,43 @@
'use strict';
function clamp(v, min, max) {
return Math.max(min, Math.min(v, max));
}
const V = {
toVector(v, fallback) {
if (v === undefined) v = fallback;
return Array.isArray(v) ? v : [v, v];
},
add(v1, v2) {
return [v1[0] + v2[0], v1[1] + v2[1]];
},
sub(v1, v2) {
return [v1[0] - v2[0], v1[1] - v2[1]];
},
addTo(v1, v2) {
v1[0] += v2[0];
v1[1] += v2[1];
},
subTo(v1, v2) {
v1[0] -= v2[0];
v1[1] -= v2[1];
}
};
function rubberband(distance, dimension, constant) {
if (dimension === 0 || Math.abs(dimension) === Infinity) return Math.pow(distance, constant * 5);
return distance * dimension * constant / (dimension + constant * distance);
}
function rubberbandIfOutOfBounds(position, min, max, constant = 0.15) {
if (constant === 0) return clamp(position, min, max);
if (position < min) return -rubberband(min - position, max - min, constant) + min;
if (position > max) return +rubberband(position - max, max - min, constant) + max;
return position;
}
function computeRubberband(bounds, [Vx, Vy], [Rx, Ry]) {
const [[X0, X1], [Y0, Y1]] = bounds;
return [rubberbandIfOutOfBounds(Vx, X0, X1, Rx), rubberbandIfOutOfBounds(Vy, Y0, Y1, Ry)];
}
exports.V = V;
exports.computeRubberband = computeRubberband;
exports.rubberbandIfOutOfBounds = rubberbandIfOutOfBounds;

View File

@@ -0,0 +1,2 @@
export * from "./declarations/src/index";
//# sourceMappingURL=use-gesture-core.cjs.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"use-gesture-core.cjs.d.ts","sourceRoot":"","sources":["./declarations/src/index.d.ts"],"names":[],"mappings":"AAAA"}

View File

@@ -0,0 +1,336 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var actions_dist_useGestureCoreActions = require('./actions-6579bdef.cjs.dev.js');
require('./maths-267f0992.cjs.dev.js');
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
const sharedConfigResolver = {
target(value) {
if (value) {
return () => 'current' in value ? value.current : value;
}
return undefined;
},
enabled(value = true) {
return value;
},
window(value = actions_dist_useGestureCoreActions.SUPPORT.isBrowser ? window : undefined) {
return value;
},
eventOptions({
passive = true,
capture = false
} = {}) {
return {
passive,
capture
};
},
transform(value) {
return value;
}
};
const _excluded = ["target", "eventOptions", "window", "enabled", "transform"];
function resolveWith(config = {}, resolvers) {
const result = {};
for (const [key, resolver] of Object.entries(resolvers)) {
switch (typeof resolver) {
case 'function':
if (process.env.NODE_ENV === 'development') {
const r = resolver.call(result, config[key], key, config);
if (!Number.isNaN(r)) result[key] = r;
} else {
result[key] = resolver.call(result, config[key], key, config);
}
break;
case 'object':
result[key] = resolveWith(config[key], resolver);
break;
case 'boolean':
if (resolver) result[key] = config[key];
break;
}
}
return result;
}
function parse(newConfig, gestureKey, _config = {}) {
const _ref = newConfig,
{
target,
eventOptions,
window,
enabled,
transform
} = _ref,
rest = _objectWithoutProperties(_ref, _excluded);
_config.shared = resolveWith({
target,
eventOptions,
window,
enabled,
transform
}, sharedConfigResolver);
if (gestureKey) {
const resolver = actions_dist_useGestureCoreActions.ConfigResolverMap.get(gestureKey);
_config[gestureKey] = resolveWith(actions_dist_useGestureCoreActions._objectSpread2({
shared: _config.shared
}, rest), resolver);
} else {
for (const key in rest) {
const resolver = actions_dist_useGestureCoreActions.ConfigResolverMap.get(key);
if (resolver) {
_config[key] = resolveWith(actions_dist_useGestureCoreActions._objectSpread2({
shared: _config.shared
}, rest[key]), resolver);
} else if (process.env.NODE_ENV === 'development') {
if (!['drag', 'pinch', 'scroll', 'wheel', 'move', 'hover'].includes(key)) {
if (key === 'domTarget') {
throw Error(`[@use-gesture]: \`domTarget\` option has been renamed to \`target\`.`);
}
console.warn(`[@use-gesture]: Unknown config key \`${key}\` was used. Please read the documentation for further information.`);
}
}
}
}
return _config;
}
class EventStore {
constructor(ctrl, gestureKey) {
actions_dist_useGestureCoreActions._defineProperty(this, "_listeners", new Set());
this._ctrl = ctrl;
this._gestureKey = gestureKey;
}
add(element, device, action, handler, options) {
const listeners = this._listeners;
const type = actions_dist_useGestureCoreActions.toDomEventType(device, action);
const _options = this._gestureKey ? this._ctrl.config[this._gestureKey].eventOptions : {};
const eventOptions = actions_dist_useGestureCoreActions._objectSpread2(actions_dist_useGestureCoreActions._objectSpread2({}, _options), options);
element.addEventListener(type, handler, eventOptions);
const remove = () => {
element.removeEventListener(type, handler, eventOptions);
listeners.delete(remove);
};
listeners.add(remove);
return remove;
}
clean() {
this._listeners.forEach(remove => remove());
this._listeners.clear();
}
}
class TimeoutStore {
constructor() {
actions_dist_useGestureCoreActions._defineProperty(this, "_timeouts", new Map());
}
add(key, callback, ms = 140, ...args) {
this.remove(key);
this._timeouts.set(key, window.setTimeout(callback, ms, ...args));
}
remove(key) {
const timeout = this._timeouts.get(key);
if (timeout) window.clearTimeout(timeout);
}
clean() {
this._timeouts.forEach(timeout => void window.clearTimeout(timeout));
this._timeouts.clear();
}
}
class Controller {
constructor(handlers) {
actions_dist_useGestureCoreActions._defineProperty(this, "gestures", new Set());
actions_dist_useGestureCoreActions._defineProperty(this, "_targetEventStore", new EventStore(this));
actions_dist_useGestureCoreActions._defineProperty(this, "gestureEventStores", {});
actions_dist_useGestureCoreActions._defineProperty(this, "gestureTimeoutStores", {});
actions_dist_useGestureCoreActions._defineProperty(this, "handlers", {});
actions_dist_useGestureCoreActions._defineProperty(this, "config", {});
actions_dist_useGestureCoreActions._defineProperty(this, "pointerIds", new Set());
actions_dist_useGestureCoreActions._defineProperty(this, "touchIds", new Set());
actions_dist_useGestureCoreActions._defineProperty(this, "state", {
shared: {
shiftKey: false,
metaKey: false,
ctrlKey: false,
altKey: false
}
});
resolveGestures(this, handlers);
}
setEventIds(event) {
if (actions_dist_useGestureCoreActions.isTouch(event)) {
this.touchIds = new Set(actions_dist_useGestureCoreActions.touchIds(event));
return this.touchIds;
} else if ('pointerId' in event) {
if (event.type === 'pointerup' || event.type === 'pointercancel') this.pointerIds.delete(event.pointerId);else if (event.type === 'pointerdown') this.pointerIds.add(event.pointerId);
return this.pointerIds;
}
}
applyHandlers(handlers, nativeHandlers) {
this.handlers = handlers;
this.nativeHandlers = nativeHandlers;
}
applyConfig(config, gestureKey) {
this.config = parse(config, gestureKey, this.config);
}
clean() {
this._targetEventStore.clean();
for (const key of this.gestures) {
this.gestureEventStores[key].clean();
this.gestureTimeoutStores[key].clean();
}
}
effect() {
if (this.config.shared.target) this.bind();
return () => this._targetEventStore.clean();
}
bind(...args) {
const sharedConfig = this.config.shared;
const props = {};
let target;
if (sharedConfig.target) {
target = sharedConfig.target();
if (!target) return;
}
if (sharedConfig.enabled) {
for (const gestureKey of this.gestures) {
const gestureConfig = this.config[gestureKey];
const bindFunction = bindToProps(props, gestureConfig.eventOptions, !!target);
if (gestureConfig.enabled) {
const Engine = actions_dist_useGestureCoreActions.EngineMap.get(gestureKey);
new Engine(this, args, gestureKey).bind(bindFunction);
}
}
const nativeBindFunction = bindToProps(props, sharedConfig.eventOptions, !!target);
for (const eventKey in this.nativeHandlers) {
nativeBindFunction(eventKey, '', event => this.nativeHandlers[eventKey](actions_dist_useGestureCoreActions._objectSpread2(actions_dist_useGestureCoreActions._objectSpread2({}, this.state.shared), {}, {
event,
args
})), undefined, true);
}
}
for (const handlerProp in props) {
props[handlerProp] = actions_dist_useGestureCoreActions.chain(...props[handlerProp]);
}
if (!target) return props;
for (const handlerProp in props) {
const {
device,
capture,
passive
} = actions_dist_useGestureCoreActions.parseProp(handlerProp);
this._targetEventStore.add(target, device, '', props[handlerProp], {
capture,
passive
});
}
}
}
function setupGesture(ctrl, gestureKey) {
ctrl.gestures.add(gestureKey);
ctrl.gestureEventStores[gestureKey] = new EventStore(ctrl, gestureKey);
ctrl.gestureTimeoutStores[gestureKey] = new TimeoutStore();
}
function resolveGestures(ctrl, internalHandlers) {
if (internalHandlers.drag) setupGesture(ctrl, 'drag');
if (internalHandlers.wheel) setupGesture(ctrl, 'wheel');
if (internalHandlers.scroll) setupGesture(ctrl, 'scroll');
if (internalHandlers.move) setupGesture(ctrl, 'move');
if (internalHandlers.pinch) setupGesture(ctrl, 'pinch');
if (internalHandlers.hover) setupGesture(ctrl, 'hover');
}
const bindToProps = (props, eventOptions, withPassiveOption) => (device, action, handler, options = {}, isNative = false) => {
var _options$capture, _options$passive;
const capture = (_options$capture = options.capture) !== null && _options$capture !== void 0 ? _options$capture : eventOptions.capture;
const passive = (_options$passive = options.passive) !== null && _options$passive !== void 0 ? _options$passive : eventOptions.passive;
let handlerProp = isNative ? device : actions_dist_useGestureCoreActions.toHandlerProp(device, action, capture);
if (withPassiveOption && passive) handlerProp += 'Passive';
props[handlerProp] = props[handlerProp] || [];
props[handlerProp].push(handler);
};
const RE_NOT_NATIVE = /^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;
function sortHandlers(_handlers) {
const native = {};
const handlers = {};
const actions = new Set();
for (let key in _handlers) {
if (RE_NOT_NATIVE.test(key)) {
actions.add(RegExp.lastMatch);
handlers[key] = _handlers[key];
} else {
native[key] = _handlers[key];
}
}
return [handlers, native, actions];
}
function registerGesture(actions, handlers, handlerKey, key, internalHandlers, config) {
if (!actions.has(handlerKey)) return;
if (!actions_dist_useGestureCoreActions.EngineMap.has(key)) {
if (process.env.NODE_ENV === 'development') {
console.warn(`[@use-gesture]: You've created a custom handler that that uses the \`${key}\` gesture but isn't properly configured.\n\nPlease add \`${key}Action\` when creating your handler.`);
}
return;
}
const startKey = handlerKey + 'Start';
const endKey = handlerKey + 'End';
const fn = state => {
let memo = undefined;
if (state.first && startKey in handlers) handlers[startKey](state);
if (handlerKey in handlers) memo = handlers[handlerKey](state);
if (state.last && endKey in handlers) handlers[endKey](state);
return memo;
};
internalHandlers[key] = fn;
config[key] = config[key] || {};
}
function parseMergedHandlers(mergedHandlers, mergedConfig) {
const [handlers, nativeHandlers, actions] = sortHandlers(mergedHandlers);
const internalHandlers = {};
registerGesture(actions, handlers, 'onDrag', 'drag', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onWheel', 'wheel', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onScroll', 'scroll', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onPinch', 'pinch', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onMove', 'move', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onHover', 'hover', internalHandlers, mergedConfig);
return {
handlers: internalHandlers,
config: mergedConfig,
nativeHandlers
};
}
exports.Controller = Controller;
exports.parseMergedHandlers = parseMergedHandlers;

View File

@@ -0,0 +1,7 @@
'use strict';
if (process.env.NODE_ENV === "production") {
module.exports = require("./use-gesture-core.cjs.prod.js");
} else {
module.exports = require("./use-gesture-core.cjs.dev.js");
}

View File

@@ -0,0 +1,323 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var actions_dist_useGestureCoreActions = require('./actions-89e642c9.cjs.prod.js');
require('./maths-83bc6f64.cjs.prod.js');
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
const sharedConfigResolver = {
target(value) {
if (value) {
return () => 'current' in value ? value.current : value;
}
return undefined;
},
enabled(value = true) {
return value;
},
window(value = actions_dist_useGestureCoreActions.SUPPORT.isBrowser ? window : undefined) {
return value;
},
eventOptions({
passive = true,
capture = false
} = {}) {
return {
passive,
capture
};
},
transform(value) {
return value;
}
};
const _excluded = ["target", "eventOptions", "window", "enabled", "transform"];
function resolveWith(config = {}, resolvers) {
const result = {};
for (const [key, resolver] of Object.entries(resolvers)) {
switch (typeof resolver) {
case 'function':
{
result[key] = resolver.call(result, config[key], key, config);
}
break;
case 'object':
result[key] = resolveWith(config[key], resolver);
break;
case 'boolean':
if (resolver) result[key] = config[key];
break;
}
}
return result;
}
function parse(newConfig, gestureKey, _config = {}) {
const _ref = newConfig,
{
target,
eventOptions,
window,
enabled,
transform
} = _ref,
rest = _objectWithoutProperties(_ref, _excluded);
_config.shared = resolveWith({
target,
eventOptions,
window,
enabled,
transform
}, sharedConfigResolver);
if (gestureKey) {
const resolver = actions_dist_useGestureCoreActions.ConfigResolverMap.get(gestureKey);
_config[gestureKey] = resolveWith(actions_dist_useGestureCoreActions._objectSpread2({
shared: _config.shared
}, rest), resolver);
} else {
for (const key in rest) {
const resolver = actions_dist_useGestureCoreActions.ConfigResolverMap.get(key);
if (resolver) {
_config[key] = resolveWith(actions_dist_useGestureCoreActions._objectSpread2({
shared: _config.shared
}, rest[key]), resolver);
}
}
}
return _config;
}
class EventStore {
constructor(ctrl, gestureKey) {
actions_dist_useGestureCoreActions._defineProperty(this, "_listeners", new Set());
this._ctrl = ctrl;
this._gestureKey = gestureKey;
}
add(element, device, action, handler, options) {
const listeners = this._listeners;
const type = actions_dist_useGestureCoreActions.toDomEventType(device, action);
const _options = this._gestureKey ? this._ctrl.config[this._gestureKey].eventOptions : {};
const eventOptions = actions_dist_useGestureCoreActions._objectSpread2(actions_dist_useGestureCoreActions._objectSpread2({}, _options), options);
element.addEventListener(type, handler, eventOptions);
const remove = () => {
element.removeEventListener(type, handler, eventOptions);
listeners.delete(remove);
};
listeners.add(remove);
return remove;
}
clean() {
this._listeners.forEach(remove => remove());
this._listeners.clear();
}
}
class TimeoutStore {
constructor() {
actions_dist_useGestureCoreActions._defineProperty(this, "_timeouts", new Map());
}
add(key, callback, ms = 140, ...args) {
this.remove(key);
this._timeouts.set(key, window.setTimeout(callback, ms, ...args));
}
remove(key) {
const timeout = this._timeouts.get(key);
if (timeout) window.clearTimeout(timeout);
}
clean() {
this._timeouts.forEach(timeout => void window.clearTimeout(timeout));
this._timeouts.clear();
}
}
class Controller {
constructor(handlers) {
actions_dist_useGestureCoreActions._defineProperty(this, "gestures", new Set());
actions_dist_useGestureCoreActions._defineProperty(this, "_targetEventStore", new EventStore(this));
actions_dist_useGestureCoreActions._defineProperty(this, "gestureEventStores", {});
actions_dist_useGestureCoreActions._defineProperty(this, "gestureTimeoutStores", {});
actions_dist_useGestureCoreActions._defineProperty(this, "handlers", {});
actions_dist_useGestureCoreActions._defineProperty(this, "config", {});
actions_dist_useGestureCoreActions._defineProperty(this, "pointerIds", new Set());
actions_dist_useGestureCoreActions._defineProperty(this, "touchIds", new Set());
actions_dist_useGestureCoreActions._defineProperty(this, "state", {
shared: {
shiftKey: false,
metaKey: false,
ctrlKey: false,
altKey: false
}
});
resolveGestures(this, handlers);
}
setEventIds(event) {
if (actions_dist_useGestureCoreActions.isTouch(event)) {
this.touchIds = new Set(actions_dist_useGestureCoreActions.touchIds(event));
return this.touchIds;
} else if ('pointerId' in event) {
if (event.type === 'pointerup' || event.type === 'pointercancel') this.pointerIds.delete(event.pointerId);else if (event.type === 'pointerdown') this.pointerIds.add(event.pointerId);
return this.pointerIds;
}
}
applyHandlers(handlers, nativeHandlers) {
this.handlers = handlers;
this.nativeHandlers = nativeHandlers;
}
applyConfig(config, gestureKey) {
this.config = parse(config, gestureKey, this.config);
}
clean() {
this._targetEventStore.clean();
for (const key of this.gestures) {
this.gestureEventStores[key].clean();
this.gestureTimeoutStores[key].clean();
}
}
effect() {
if (this.config.shared.target) this.bind();
return () => this._targetEventStore.clean();
}
bind(...args) {
const sharedConfig = this.config.shared;
const props = {};
let target;
if (sharedConfig.target) {
target = sharedConfig.target();
if (!target) return;
}
if (sharedConfig.enabled) {
for (const gestureKey of this.gestures) {
const gestureConfig = this.config[gestureKey];
const bindFunction = bindToProps(props, gestureConfig.eventOptions, !!target);
if (gestureConfig.enabled) {
const Engine = actions_dist_useGestureCoreActions.EngineMap.get(gestureKey);
new Engine(this, args, gestureKey).bind(bindFunction);
}
}
const nativeBindFunction = bindToProps(props, sharedConfig.eventOptions, !!target);
for (const eventKey in this.nativeHandlers) {
nativeBindFunction(eventKey, '', event => this.nativeHandlers[eventKey](actions_dist_useGestureCoreActions._objectSpread2(actions_dist_useGestureCoreActions._objectSpread2({}, this.state.shared), {}, {
event,
args
})), undefined, true);
}
}
for (const handlerProp in props) {
props[handlerProp] = actions_dist_useGestureCoreActions.chain(...props[handlerProp]);
}
if (!target) return props;
for (const handlerProp in props) {
const {
device,
capture,
passive
} = actions_dist_useGestureCoreActions.parseProp(handlerProp);
this._targetEventStore.add(target, device, '', props[handlerProp], {
capture,
passive
});
}
}
}
function setupGesture(ctrl, gestureKey) {
ctrl.gestures.add(gestureKey);
ctrl.gestureEventStores[gestureKey] = new EventStore(ctrl, gestureKey);
ctrl.gestureTimeoutStores[gestureKey] = new TimeoutStore();
}
function resolveGestures(ctrl, internalHandlers) {
if (internalHandlers.drag) setupGesture(ctrl, 'drag');
if (internalHandlers.wheel) setupGesture(ctrl, 'wheel');
if (internalHandlers.scroll) setupGesture(ctrl, 'scroll');
if (internalHandlers.move) setupGesture(ctrl, 'move');
if (internalHandlers.pinch) setupGesture(ctrl, 'pinch');
if (internalHandlers.hover) setupGesture(ctrl, 'hover');
}
const bindToProps = (props, eventOptions, withPassiveOption) => (device, action, handler, options = {}, isNative = false) => {
var _options$capture, _options$passive;
const capture = (_options$capture = options.capture) !== null && _options$capture !== void 0 ? _options$capture : eventOptions.capture;
const passive = (_options$passive = options.passive) !== null && _options$passive !== void 0 ? _options$passive : eventOptions.passive;
let handlerProp = isNative ? device : actions_dist_useGestureCoreActions.toHandlerProp(device, action, capture);
if (withPassiveOption && passive) handlerProp += 'Passive';
props[handlerProp] = props[handlerProp] || [];
props[handlerProp].push(handler);
};
const RE_NOT_NATIVE = /^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;
function sortHandlers(_handlers) {
const native = {};
const handlers = {};
const actions = new Set();
for (let key in _handlers) {
if (RE_NOT_NATIVE.test(key)) {
actions.add(RegExp.lastMatch);
handlers[key] = _handlers[key];
} else {
native[key] = _handlers[key];
}
}
return [handlers, native, actions];
}
function registerGesture(actions, handlers, handlerKey, key, internalHandlers, config) {
if (!actions.has(handlerKey)) return;
if (!actions_dist_useGestureCoreActions.EngineMap.has(key)) {
return;
}
const startKey = handlerKey + 'Start';
const endKey = handlerKey + 'End';
const fn = state => {
let memo = undefined;
if (state.first && startKey in handlers) handlers[startKey](state);
if (handlerKey in handlers) memo = handlers[handlerKey](state);
if (state.last && endKey in handlers) handlers[endKey](state);
return memo;
};
internalHandlers[key] = fn;
config[key] = config[key] || {};
}
function parseMergedHandlers(mergedHandlers, mergedConfig) {
const [handlers, nativeHandlers, actions] = sortHandlers(mergedHandlers);
const internalHandlers = {};
registerGesture(actions, handlers, 'onDrag', 'drag', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onWheel', 'wheel', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onScroll', 'scroll', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onPinch', 'pinch', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onMove', 'move', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onHover', 'hover', internalHandlers, mergedConfig);
return {
handlers: internalHandlers,
config: mergedConfig,
nativeHandlers
};
}
exports.Controller = Controller;
exports.parseMergedHandlers = parseMergedHandlers;

View File

@@ -0,0 +1,331 @@
import { S as SUPPORT, C as ConfigResolverMap, _ as _objectSpread2, a as _defineProperty, t as toDomEventType, i as isTouch, b as touchIds, E as EngineMap, c as chain, p as parseProp, d as toHandlerProp } from './actions-fe213e88.esm.js';
import './maths-0ab39ae9.esm.js';
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
const sharedConfigResolver = {
target(value) {
if (value) {
return () => 'current' in value ? value.current : value;
}
return undefined;
},
enabled(value = true) {
return value;
},
window(value = SUPPORT.isBrowser ? window : undefined) {
return value;
},
eventOptions({
passive = true,
capture = false
} = {}) {
return {
passive,
capture
};
},
transform(value) {
return value;
}
};
const _excluded = ["target", "eventOptions", "window", "enabled", "transform"];
function resolveWith(config = {}, resolvers) {
const result = {};
for (const [key, resolver] of Object.entries(resolvers)) {
switch (typeof resolver) {
case 'function':
if (process.env.NODE_ENV === 'development') {
const r = resolver.call(result, config[key], key, config);
if (!Number.isNaN(r)) result[key] = r;
} else {
result[key] = resolver.call(result, config[key], key, config);
}
break;
case 'object':
result[key] = resolveWith(config[key], resolver);
break;
case 'boolean':
if (resolver) result[key] = config[key];
break;
}
}
return result;
}
function parse(newConfig, gestureKey, _config = {}) {
const _ref = newConfig,
{
target,
eventOptions,
window,
enabled,
transform
} = _ref,
rest = _objectWithoutProperties(_ref, _excluded);
_config.shared = resolveWith({
target,
eventOptions,
window,
enabled,
transform
}, sharedConfigResolver);
if (gestureKey) {
const resolver = ConfigResolverMap.get(gestureKey);
_config[gestureKey] = resolveWith(_objectSpread2({
shared: _config.shared
}, rest), resolver);
} else {
for (const key in rest) {
const resolver = ConfigResolverMap.get(key);
if (resolver) {
_config[key] = resolveWith(_objectSpread2({
shared: _config.shared
}, rest[key]), resolver);
} else if (process.env.NODE_ENV === 'development') {
if (!['drag', 'pinch', 'scroll', 'wheel', 'move', 'hover'].includes(key)) {
if (key === 'domTarget') {
throw Error(`[@use-gesture]: \`domTarget\` option has been renamed to \`target\`.`);
}
console.warn(`[@use-gesture]: Unknown config key \`${key}\` was used. Please read the documentation for further information.`);
}
}
}
}
return _config;
}
class EventStore {
constructor(ctrl, gestureKey) {
_defineProperty(this, "_listeners", new Set());
this._ctrl = ctrl;
this._gestureKey = gestureKey;
}
add(element, device, action, handler, options) {
const listeners = this._listeners;
const type = toDomEventType(device, action);
const _options = this._gestureKey ? this._ctrl.config[this._gestureKey].eventOptions : {};
const eventOptions = _objectSpread2(_objectSpread2({}, _options), options);
element.addEventListener(type, handler, eventOptions);
const remove = () => {
element.removeEventListener(type, handler, eventOptions);
listeners.delete(remove);
};
listeners.add(remove);
return remove;
}
clean() {
this._listeners.forEach(remove => remove());
this._listeners.clear();
}
}
class TimeoutStore {
constructor() {
_defineProperty(this, "_timeouts", new Map());
}
add(key, callback, ms = 140, ...args) {
this.remove(key);
this._timeouts.set(key, window.setTimeout(callback, ms, ...args));
}
remove(key) {
const timeout = this._timeouts.get(key);
if (timeout) window.clearTimeout(timeout);
}
clean() {
this._timeouts.forEach(timeout => void window.clearTimeout(timeout));
this._timeouts.clear();
}
}
class Controller {
constructor(handlers) {
_defineProperty(this, "gestures", new Set());
_defineProperty(this, "_targetEventStore", new EventStore(this));
_defineProperty(this, "gestureEventStores", {});
_defineProperty(this, "gestureTimeoutStores", {});
_defineProperty(this, "handlers", {});
_defineProperty(this, "config", {});
_defineProperty(this, "pointerIds", new Set());
_defineProperty(this, "touchIds", new Set());
_defineProperty(this, "state", {
shared: {
shiftKey: false,
metaKey: false,
ctrlKey: false,
altKey: false
}
});
resolveGestures(this, handlers);
}
setEventIds(event) {
if (isTouch(event)) {
this.touchIds = new Set(touchIds(event));
return this.touchIds;
} else if ('pointerId' in event) {
if (event.type === 'pointerup' || event.type === 'pointercancel') this.pointerIds.delete(event.pointerId);else if (event.type === 'pointerdown') this.pointerIds.add(event.pointerId);
return this.pointerIds;
}
}
applyHandlers(handlers, nativeHandlers) {
this.handlers = handlers;
this.nativeHandlers = nativeHandlers;
}
applyConfig(config, gestureKey) {
this.config = parse(config, gestureKey, this.config);
}
clean() {
this._targetEventStore.clean();
for (const key of this.gestures) {
this.gestureEventStores[key].clean();
this.gestureTimeoutStores[key].clean();
}
}
effect() {
if (this.config.shared.target) this.bind();
return () => this._targetEventStore.clean();
}
bind(...args) {
const sharedConfig = this.config.shared;
const props = {};
let target;
if (sharedConfig.target) {
target = sharedConfig.target();
if (!target) return;
}
if (sharedConfig.enabled) {
for (const gestureKey of this.gestures) {
const gestureConfig = this.config[gestureKey];
const bindFunction = bindToProps(props, gestureConfig.eventOptions, !!target);
if (gestureConfig.enabled) {
const Engine = EngineMap.get(gestureKey);
new Engine(this, args, gestureKey).bind(bindFunction);
}
}
const nativeBindFunction = bindToProps(props, sharedConfig.eventOptions, !!target);
for (const eventKey in this.nativeHandlers) {
nativeBindFunction(eventKey, '', event => this.nativeHandlers[eventKey](_objectSpread2(_objectSpread2({}, this.state.shared), {}, {
event,
args
})), undefined, true);
}
}
for (const handlerProp in props) {
props[handlerProp] = chain(...props[handlerProp]);
}
if (!target) return props;
for (const handlerProp in props) {
const {
device,
capture,
passive
} = parseProp(handlerProp);
this._targetEventStore.add(target, device, '', props[handlerProp], {
capture,
passive
});
}
}
}
function setupGesture(ctrl, gestureKey) {
ctrl.gestures.add(gestureKey);
ctrl.gestureEventStores[gestureKey] = new EventStore(ctrl, gestureKey);
ctrl.gestureTimeoutStores[gestureKey] = new TimeoutStore();
}
function resolveGestures(ctrl, internalHandlers) {
if (internalHandlers.drag) setupGesture(ctrl, 'drag');
if (internalHandlers.wheel) setupGesture(ctrl, 'wheel');
if (internalHandlers.scroll) setupGesture(ctrl, 'scroll');
if (internalHandlers.move) setupGesture(ctrl, 'move');
if (internalHandlers.pinch) setupGesture(ctrl, 'pinch');
if (internalHandlers.hover) setupGesture(ctrl, 'hover');
}
const bindToProps = (props, eventOptions, withPassiveOption) => (device, action, handler, options = {}, isNative = false) => {
var _options$capture, _options$passive;
const capture = (_options$capture = options.capture) !== null && _options$capture !== void 0 ? _options$capture : eventOptions.capture;
const passive = (_options$passive = options.passive) !== null && _options$passive !== void 0 ? _options$passive : eventOptions.passive;
let handlerProp = isNative ? device : toHandlerProp(device, action, capture);
if (withPassiveOption && passive) handlerProp += 'Passive';
props[handlerProp] = props[handlerProp] || [];
props[handlerProp].push(handler);
};
const RE_NOT_NATIVE = /^on(Drag|Wheel|Scroll|Move|Pinch|Hover)/;
function sortHandlers(_handlers) {
const native = {};
const handlers = {};
const actions = new Set();
for (let key in _handlers) {
if (RE_NOT_NATIVE.test(key)) {
actions.add(RegExp.lastMatch);
handlers[key] = _handlers[key];
} else {
native[key] = _handlers[key];
}
}
return [handlers, native, actions];
}
function registerGesture(actions, handlers, handlerKey, key, internalHandlers, config) {
if (!actions.has(handlerKey)) return;
if (!EngineMap.has(key)) {
if (process.env.NODE_ENV === 'development') {
console.warn(`[@use-gesture]: You've created a custom handler that that uses the \`${key}\` gesture but isn't properly configured.\n\nPlease add \`${key}Action\` when creating your handler.`);
}
return;
}
const startKey = handlerKey + 'Start';
const endKey = handlerKey + 'End';
const fn = state => {
let memo = undefined;
if (state.first && startKey in handlers) handlers[startKey](state);
if (handlerKey in handlers) memo = handlers[handlerKey](state);
if (state.last && endKey in handlers) handlers[endKey](state);
return memo;
};
internalHandlers[key] = fn;
config[key] = config[key] || {};
}
function parseMergedHandlers(mergedHandlers, mergedConfig) {
const [handlers, nativeHandlers, actions] = sortHandlers(mergedHandlers);
const internalHandlers = {};
registerGesture(actions, handlers, 'onDrag', 'drag', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onWheel', 'wheel', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onScroll', 'scroll', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onPinch', 'pinch', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onMove', 'move', internalHandlers, mergedConfig);
registerGesture(actions, handlers, 'onHover', 'hover', internalHandlers, mergedConfig);
return {
handlers: internalHandlers,
config: mergedConfig,
nativeHandlers
};
}
export { Controller, parseMergedHandlers };