This commit is contained in:
Yamozha
2021-04-02 02:24:13 +03:00
parent c23950b545
commit 7256d79e2c
31493 changed files with 3036630 additions and 0 deletions

View File

@ -0,0 +1,92 @@
/**
* Copyright (c) Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import useLayoutEffect from './useLayoutEffect';
import UIManager from '../exports/UIManager';
var DOM_LAYOUT_HANDLER_NAME = '__reactLayoutHandler';
var didWarn = !canUseDOM;
var resizeObserver = null;
function getResizeObserver() {
if (canUseDOM && typeof window.ResizeObserver !== 'undefined') {
if (resizeObserver == null) {
resizeObserver = new window.ResizeObserver(function (entries) {
entries.forEach(function (entry) {
var node = entry.target;
var onLayout = node[DOM_LAYOUT_HANDLER_NAME];
if (typeof onLayout === 'function') {
// We still need to measure the view because browsers don't yet provide
// border-box dimensions in the entry
UIManager.measure(node, function (x, y, width, height, left, top) {
var event = {
// $FlowFixMe
nativeEvent: {
layout: {
x: x,
y: y,
width: width,
height: height,
left: left,
top: top
}
},
timeStamp: Date.now()
};
Object.defineProperty(event.nativeEvent, 'target', {
enumerable: true,
get: function get() {
return entry.target;
}
});
onLayout(event);
});
}
});
});
}
} else if (!didWarn) {
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
console.warn('onLayout relies on ResizeObserver which is not supported by your browser. ' + 'Please include a polyfill, e.g., https://github.com/que-etc/resize-observer-polyfill.');
didWarn = true;
}
}
return resizeObserver;
}
export default function useElementLayout(ref, onLayout) {
var observer = getResizeObserver();
useLayoutEffect(function () {
var node = ref.current;
if (node != null) {
node[DOM_LAYOUT_HANDLER_NAME] = onLayout;
}
}, [ref, onLayout]); // Observing is done in a separate effect to avoid this effect running
// when 'onLayout' changes.
useLayoutEffect(function () {
var node = ref.current;
if (node != null && observer != null) {
if (typeof node[DOM_LAYOUT_HANDLER_NAME] === 'function') {
observer.observe(node);
} else {
observer.unobserve(node);
}
}
return function () {
if (node != null && observer != null) {
observer.unobserve(node);
}
};
}, [ref, observer]);
}

View File

@ -0,0 +1,15 @@
/**
* Copyright (c) Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* useLayoutEffect throws an error on the server. On the few occasions where is
* problematic, use this hook.
*
*
*/
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import { useEffect, useLayoutEffect } from 'react';
var useLayoutEffectImpl = canUseDOM ? useLayoutEffect : useEffect;
export default useLayoutEffectImpl;

View File

@ -0,0 +1,79 @@
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* Copyright (c) Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import UIManager from '../exports/UIManager';
import createDOMProps from '../modules/createDOMProps';
import { useMemo, useRef } from 'react';
function setNativeProps(node, nativeProps, classList, pointerEvents, style, previousStyleRef) {
if (node != null && nativeProps) {
var domProps = createDOMProps(null, _objectSpread({
pointerEvents: pointerEvents
}, nativeProps, {
classList: [classList, nativeProps.className],
style: [style, nativeProps.style]
}));
var nextDomStyle = domProps.style;
if (previousStyleRef.current != null) {
if (domProps.style == null) {
domProps.style = {};
}
for (var styleName in previousStyleRef.current) {
if (domProps.style[styleName] == null) {
domProps.style[styleName] = '';
}
}
}
previousStyleRef.current = nextDomStyle;
UIManager.updateView(node, domProps);
}
}
/**
* Adds non-standard methods to the hode element. This is temporarily until an
* API like `ReactNative.measure(hostRef, callback)` is added to React Native.
*/
export default function usePlatformMethods(props) {
var previousStyleRef = useRef(null);
var classList = props.classList,
style = props.style,
pointerEvents = props.pointerEvents;
return useMemo(function () {
return function (hostNode) {
if (hostNode != null) {
hostNode.measure = function (callback) {
return UIManager.measure(hostNode, callback);
};
hostNode.measureLayout = function (relativeToNode, success, failure) {
return UIManager.measureLayout(hostNode, relativeToNode, failure, success);
};
hostNode.measureInWindow = function (callback) {
return UIManager.measureInWindow(hostNode, callback);
};
hostNode.setNativeProps = function (nativeProps) {
return setNativeProps(hostNode, nativeProps, classList, pointerEvents, style, previousStyleRef);
};
}
return hostNode;
};
}, [classList, pointerEvents, style]);
}

View File

@ -0,0 +1,538 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
var DELAY = 'DELAY';
var ERROR = 'ERROR';
var LONG_PRESS_DETECTED = 'LONG_PRESS_DETECTED';
var NOT_RESPONDER = 'NOT_RESPONDER';
var RESPONDER_ACTIVE_LONG_PRESS_START = 'RESPONDER_ACTIVE_LONG_PRESS_START';
var RESPONDER_ACTIVE_PRESS_START = 'RESPONDER_ACTIVE_PRESS_START';
var RESPONDER_INACTIVE_PRESS_START = 'RESPONDER_INACTIVE_PRESS_START';
var RESPONDER_GRANT = 'RESPONDER_GRANT';
var RESPONDER_RELEASE = 'RESPONDER_RELEASE';
var RESPONDER_TERMINATED = 'RESPONDER_TERMINATED';
var Transitions = Object.freeze({
NOT_RESPONDER: {
DELAY: ERROR,
RESPONDER_GRANT: RESPONDER_INACTIVE_PRESS_START,
RESPONDER_RELEASE: ERROR,
RESPONDER_TERMINATED: ERROR,
LONG_PRESS_DETECTED: ERROR
},
RESPONDER_INACTIVE_PRESS_START: {
DELAY: RESPONDER_ACTIVE_PRESS_START,
RESPONDER_GRANT: ERROR,
RESPONDER_RELEASE: NOT_RESPONDER,
RESPONDER_TERMINATED: NOT_RESPONDER,
LONG_PRESS_DETECTED: ERROR
},
RESPONDER_ACTIVE_PRESS_START: {
DELAY: ERROR,
RESPONDER_GRANT: ERROR,
RESPONDER_RELEASE: NOT_RESPONDER,
RESPONDER_TERMINATED: NOT_RESPONDER,
LONG_PRESS_DETECTED: RESPONDER_ACTIVE_LONG_PRESS_START
},
RESPONDER_ACTIVE_LONG_PRESS_START: {
DELAY: ERROR,
RESPONDER_GRANT: ERROR,
RESPONDER_RELEASE: NOT_RESPONDER,
RESPONDER_TERMINATED: NOT_RESPONDER,
LONG_PRESS_DETECTED: RESPONDER_ACTIVE_LONG_PRESS_START
},
ERROR: {
DELAY: NOT_RESPONDER,
RESPONDER_GRANT: RESPONDER_INACTIVE_PRESS_START,
RESPONDER_RELEASE: NOT_RESPONDER,
RESPONDER_TERMINATED: NOT_RESPONDER,
LONG_PRESS_DETECTED: NOT_RESPONDER
}
});
var isActiveSignal = function isActiveSignal(signal) {
return signal === RESPONDER_ACTIVE_PRESS_START || signal === RESPONDER_ACTIVE_LONG_PRESS_START;
};
var isPressStartSignal = function isPressStartSignal(signal) {
return signal === RESPONDER_INACTIVE_PRESS_START || signal === RESPONDER_ACTIVE_PRESS_START || signal === RESPONDER_ACTIVE_LONG_PRESS_START;
};
var isTerminalSignal = function isTerminalSignal(signal) {
return signal === RESPONDER_TERMINATED || signal === RESPONDER_RELEASE;
};
var isValidKeyPress = function isValidKeyPress(event) {
var key = event.key;
var target = event.currentTarget;
var role = target.getAttribute('role');
var isSpacebar = key === ' ' || key === 'Spacebar';
return !event.repeat && (key === 'Enter' || isSpacebar && (role === 'button' || role === 'menuitem'));
};
var DEFAULT_LONG_PRESS_DELAY_MS = 450; // 500 - 50
var DEFAULT_PRESS_DELAY_MS = 50;
/**
* =========================== PressResponder Tutorial ===========================
*
* The `PressResponder` class helps you create press interactions by analyzing the
* geometry of elements and observing when another responder (e.g. ScrollView)
* has stolen the touch lock. It offers hooks for your component to provide
* interaction feedback to the user:
*
* - When a press has activated (e.g. highlight an element)
* - When a press has deactivated (e.g. un-highlight an element)
* - When a press sould trigger an action, meaning it activated and deactivated
* while within the geometry of the element without the lock being stolen.
*
* A high quality interaction isn't as simple as you might think. There should
* be a slight delay before activation. Moving your finger beyond an element's
* bounds should trigger deactivation, but moving the same finger back within an
* element's bounds should trigger reactivation.
*
* In order to use `PressResponder`, do the following:
*
* const pressResponder = new PressResponder(config);
*
* 2. Choose the rendered component who should collect the press events. On that
* element, spread `pressability.getEventHandlers()` into its props.
*
* return (
* <View {...this.state.pressResponder.getEventHandlers()} />
* );
*
* 3. Reset `PressResponder` when your component unmounts.
*
* componentWillUnmount() {
* this.state.pressResponder.reset();
* }
*
* ==================== Implementation Details ====================
*
* `PressResponder` only assumes that there exists a `HitRect` node. The `PressRect`
* is an abstract box that is extended beyond the `HitRect`.
*
* # Geometry
*
* ┌────────────────────────┐
* │ ┌──────────────────┐ │ - Presses start anywhere within `HitRect`.
* │ │ ┌────────────┐ │ │
* │ │ │ VisualRect │ │ │
* │ │ └────────────┘ │ │ - When pressed down for sufficient amount of time
* │ │ HitRect │ │ before letting up, `VisualRect` activates.
* │ └──────────────────┘ │
* │ Out Region o │
* └────────────────────│───┘
* └────── When the press is released outside the `HitRect`,
* the responder is NOT eligible for a "press".
*
* # State Machine
*
* ┌───────────────┐ ◀──── RESPONDER_RELEASE
* │ NOT_RESPONDER │
* └───┬───────────┘ ◀──── RESPONDER_TERMINATED
* │
* │ RESPONDER_GRANT (HitRect)
* │
* ▼
* ┌─────────────────────┐ ┌───────────────────┐ ┌───────────────────┐
* │ RESPONDER_INACTIVE_ │ DELAY │ RESPONDER_ACTIVE_ │ T + DELAY │ RESPONDER_ACTIVE_ │
* │ PRESS_START ├────────▶ │ PRESS_START ├────────────▶ │ LONG_PRESS_START │
* └─────────────────────┘ └───────────────────┘ └───────────────────┘
*
* T + DELAY => LONG_PRESS_DELAY + DELAY
*
* Not drawn are the side effects of each transition. The most important side
* effect is the invocation of `onLongPress`. Only when the browser produces a
* `click` event is `onPress` invoked.
*/
var PressResponder =
/*#__PURE__*/
function () {
function PressResponder(config) {
this._eventHandlers = null;
this._isPointerTouch = false;
this._longPressDelayTimeout = null;
this._longPressDispatched = false;
this._pressDelayTimeout = null;
this._pressOutDelayTimeout = null;
this._touchState = NOT_RESPONDER;
this.configure(config);
}
var _proto = PressResponder.prototype;
_proto.configure = function configure(config) {
this._config = config;
}
/**
* Resets any pending timers. This should be called on unmount.
*/
;
_proto.reset = function reset() {
this._cancelLongPressDelayTimeout();
this._cancelPressDelayTimeout();
this._cancelPressOutDelayTimeout();
}
/**
* Returns a set of props to spread into the interactive element.
*/
;
_proto.getEventHandlers = function getEventHandlers() {
if (this._eventHandlers == null) {
this._eventHandlers = this._createEventHandlers();
}
return this._eventHandlers;
};
_proto._createEventHandlers = function _createEventHandlers() {
var _this = this;
var start = function start(event, shouldDelay) {
event.persist();
_this._cancelPressOutDelayTimeout();
_this._longPressDispatched = false;
_this._responder = event.currentTarget;
_this._selectionTerminated = false;
_this._touchState = NOT_RESPONDER;
_this._isPointerTouch = event.nativeEvent.type === 'touchstart';
_this._receiveSignal(RESPONDER_GRANT, event);
var delayPressStart = normalizeDelay(_this._config.delayPressStart, 0, DEFAULT_PRESS_DELAY_MS);
if (shouldDelay !== false && delayPressStart > 0) {
_this._pressDelayTimeout = setTimeout(function () {
_this._receiveSignal(DELAY, event);
}, delayPressStart);
} else {
_this._receiveSignal(DELAY, event);
}
var delayLongPress = normalizeDelay(_this._config.delayLongPress, 10, DEFAULT_LONG_PRESS_DELAY_MS);
_this._longPressDelayTimeout = setTimeout(function () {
_this._handleLongPress(event);
}, delayLongPress + delayPressStart);
};
var end = function end(event) {
_this._receiveSignal(RESPONDER_RELEASE, event);
};
var keyupHandler = function keyupHandler(event) {
if (_this._touchState !== NOT_RESPONDER) {
end(event);
document.removeEventListener('keyup', keyupHandler);
}
};
return {
onStartShouldSetResponder: function onStartShouldSetResponder() {
var disabled = _this._config.disabled;
if (disabled == null) {
return true;
}
return !disabled;
},
onKeyDown: function onKeyDown(event) {
if (isValidKeyPress(event)) {
if (_this._touchState === NOT_RESPONDER) {
start(event, false); // Listen to 'keyup' on document to account for situations where
// focus is moved to another element during 'keydown'.
document.addEventListener('keyup', keyupHandler);
}
event.stopPropagation();
}
},
onResponderGrant: function onResponderGrant(event) {
return start(event);
},
onResponderMove: function onResponderMove(event) {
if (_this._config.onPressMove != null) {
_this._config.onPressMove(event);
}
var touch = getTouchFromResponderEvent(event);
if (_this._touchActivatePosition != null) {
var deltaX = _this._touchActivatePosition.pageX - touch.pageX;
var deltaY = _this._touchActivatePosition.pageY - touch.pageY;
if (Math.hypot(deltaX, deltaY) > 10) {
_this._cancelLongPressDelayTimeout();
}
}
},
onResponderRelease: function onResponderRelease(event) {
return end(event);
},
onResponderTerminate: function onResponderTerminate(event) {
if (event.nativeEvent.type === 'selectionchange') {
_this._selectionTerminated = true;
}
_this._receiveSignal(RESPONDER_TERMINATED, event);
},
onResponderTerminationRequest: function onResponderTerminationRequest(event) {
var _this$_config = _this._config,
cancelable = _this$_config.cancelable,
disabled = _this$_config.disabled,
onLongPress = _this$_config.onLongPress; // If `onLongPress` is provided, don't terminate on `contextmenu` as default
// behavior will be prevented for non-mouse pointers.
if (!disabled && onLongPress != null && _this._isPointerTouch && event.nativeEvent.type === 'contextmenu') {
return false;
}
if (cancelable == null) {
return true;
}
return cancelable;
},
// NOTE: this diverges from react-native in 3 significant ways:
// * The `onPress` callback is not connected to the responder system (the native
// `click` event must be used but is dispatched in many scenarios where no pointers
// are on the screen.) Therefore, it's possible for `onPress` to be called without
// `onPress{Start,End}` being called first.
// * The `onPress` callback is only be called on the first ancestor of the native
// `click` target that is using the PressResponder.
// * The event's `nativeEvent` is a `MouseEvent` not a `TouchEvent`.
onClick: function onClick(event) {
var _this$_config2 = _this._config,
disabled = _this$_config2.disabled,
onPress = _this$_config2.onPress;
if (!disabled) {
// If long press dispatched, cancel default click behavior.
// If the responder terminated because text was selected during the gesture,
// cancel the default click behavior.
if (_this._longPressDispatched || _this._selectionTerminated) {
event.preventDefault();
} else if (onPress != null && event.ctrlKey === false && event.altKey === false) {
onPress(event);
}
}
event.stopPropagation();
},
// If `onLongPress` is provided and a touch pointer is being used, prevent the
// default context menu from opening.
onContextMenu: function onContextMenu(event) {
var _this$_config3 = _this._config,
disabled = _this$_config3.disabled,
onLongPress = _this$_config3.onLongPress;
if (!disabled && onLongPress != null && _this._isPointerTouch && !event.defaultPrevented) {
event.preventDefault();
}
event.stopPropagation();
}
};
}
/**
* Receives a state machine signal, performs side effects of the transition
* and stores the new state. Validates the transition as well.
*/
;
_proto._receiveSignal = function _receiveSignal(signal, event) {
var prevState = this._touchState;
var nextState = null;
if (Transitions[prevState] != null) {
nextState = Transitions[prevState][signal];
}
if (this._responder == null && signal === RESPONDER_RELEASE) {
return;
}
if (nextState == null || nextState === ERROR) {
console.error("PressResponder: Invalid signal " + signal + " for state " + prevState + " on responder");
} else if (prevState !== nextState) {
this._performTransitionSideEffects(prevState, nextState, signal, event);
this._touchState = nextState;
}
}
/**
* Performs a transition between touchable states and identify any activations
* or deactivations (and callback invocations).
*/
;
_proto._performTransitionSideEffects = function _performTransitionSideEffects(prevState, nextState, signal, event) {
if (isTerminalSignal(signal)) {
this._isPointerTouch = false;
this._touchActivatePosition = null;
this._cancelLongPressDelayTimeout();
}
if (isPressStartSignal(prevState) && signal === LONG_PRESS_DETECTED) {
var onLongPress = this._config.onLongPress; // Long press is not supported for keyboards because 'click' can be dispatched
// immediately (and multiple times) after 'keydown'.
if (onLongPress != null && event.nativeEvent.key == null) {
onLongPress(event);
this._longPressDispatched = true;
}
}
var isPrevActive = isActiveSignal(prevState);
var isNextActive = isActiveSignal(nextState);
if (!isPrevActive && isNextActive) {
this._activate(event);
} else if (isPrevActive && !isNextActive) {
this._deactivate(event);
}
if (isPressStartSignal(prevState) && signal === RESPONDER_RELEASE) {
var _this$_config4 = this._config,
_onLongPress = _this$_config4.onLongPress,
onPress = _this$_config4.onPress;
if (onPress != null) {
var isPressCanceledByLongPress = _onLongPress != null && prevState === RESPONDER_ACTIVE_LONG_PRESS_START;
if (!isPressCanceledByLongPress) {
// If we never activated (due to delays), activate and deactivate now.
if (!isNextActive && !isPrevActive) {
this._activate(event);
this._deactivate(event);
}
}
}
}
this._cancelPressDelayTimeout();
};
_proto._activate = function _activate(event) {
var _this$_config5 = this._config,
onPressChange = _this$_config5.onPressChange,
onPressStart = _this$_config5.onPressStart;
var touch = getTouchFromResponderEvent(event);
this._touchActivatePosition = {
pageX: touch.pageX,
pageY: touch.pageY
};
if (onPressStart != null) {
onPressStart(event);
}
if (onPressChange != null) {
onPressChange(true);
}
};
_proto._deactivate = function _deactivate(event) {
var _this$_config6 = this._config,
onPressChange = _this$_config6.onPressChange,
onPressEnd = _this$_config6.onPressEnd;
function end() {
if (onPressEnd != null) {
onPressEnd(event);
}
if (onPressChange != null) {
onPressChange(false);
}
}
var delayPressEnd = normalizeDelay(this._config.delayPressEnd);
if (delayPressEnd > 0) {
this._pressOutDelayTimeout = setTimeout(function () {
end();
}, delayPressEnd);
} else {
end();
}
};
_proto._handleLongPress = function _handleLongPress(event) {
if (this._touchState === RESPONDER_ACTIVE_PRESS_START || this._touchState === RESPONDER_ACTIVE_LONG_PRESS_START) {
this._receiveSignal(LONG_PRESS_DETECTED, event);
}
};
_proto._cancelLongPressDelayTimeout = function _cancelLongPressDelayTimeout() {
if (this._longPressDelayTimeout != null) {
clearTimeout(this._longPressDelayTimeout);
this._longPressDelayTimeout = null;
}
};
_proto._cancelPressDelayTimeout = function _cancelPressDelayTimeout() {
if (this._pressDelayTimeout != null) {
clearTimeout(this._pressDelayTimeout);
this._pressDelayTimeout = null;
}
};
_proto._cancelPressOutDelayTimeout = function _cancelPressOutDelayTimeout() {
if (this._pressOutDelayTimeout != null) {
clearTimeout(this._pressOutDelayTimeout);
this._pressOutDelayTimeout = null;
}
};
return PressResponder;
}();
export { PressResponder as default };
function normalizeDelay(delay, min, fallback) {
if (min === void 0) {
min = 0;
}
if (fallback === void 0) {
fallback = 0;
}
return Math.max(min, delay !== null && delay !== void 0 ? delay : fallback);
}
function getTouchFromResponderEvent(event) {
var _event$nativeEvent = event.nativeEvent,
changedTouches = _event$nativeEvent.changedTouches,
touches = _event$nativeEvent.touches;
if (touches != null && touches.length > 0) {
return touches[0];
}
if (changedTouches != null && changedTouches.length > 0) {
return changedTouches[0];
}
return event.nativeEvent;
}

View File

@ -0,0 +1,35 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
import PressResponder from './PressResponder';
import { useDebugValue, useEffect, useRef } from 'react';
export default function usePressEvents(hostRef, config) {
var pressResponderRef = useRef(null);
if (pressResponderRef.current == null) {
pressResponderRef.current = new PressResponder(config);
}
var pressResponder = pressResponderRef.current; // Re-configure to use the current node and configuration.
useEffect(function () {
pressResponder.configure(config);
}, [config, pressResponder]); // Reset the `pressResponder` when cleanup needs to occur. This is
// a separate effect because we do not want to rest the responder when `config` changes.
useEffect(function () {
return function () {
pressResponder.reset();
};
}, [pressResponder]);
useDebugValue(config);
return pressResponder.getEventHandlers();
}

View File

@ -0,0 +1,40 @@
/**
* Copyright (c) Nicolas Gallagher
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
export var BLUR = 'blur';
export var CONTEXT_MENU = 'contextmenu';
export var FOCUS_OUT = 'focusout';
export var MOUSE_DOWN = 'mousedown';
export var MOUSE_MOVE = 'mousemove';
export var MOUSE_UP = 'mouseup';
export var MOUSE_CANCEL = 'dragstart';
export var TOUCH_START = 'touchstart';
export var TOUCH_MOVE = 'touchmove';
export var TOUCH_END = 'touchend';
export var TOUCH_CANCEL = 'touchcancel';
export var SCROLL = 'scroll';
export var SELECT = 'select';
export var SELECTION_CHANGE = 'selectionchange';
export function isStartish(eventType) {
return eventType === TOUCH_START || eventType === MOUSE_DOWN;
}
export function isMoveish(eventType) {
return eventType === TOUCH_MOVE || eventType === MOUSE_MOVE;
}
export function isEndish(eventType) {
return eventType === TOUCH_END || eventType === MOUSE_UP || isCancelish(eventType);
}
export function isCancelish(eventType) {
return eventType === TOUCH_CANCEL || eventType === MOUSE_CANCEL;
}
export function isScroll(eventType) {
return eventType === SCROLL;
}
export function isSelectionChange(eventType) {
return eventType === SELECT || eventType === SELECTION_CHANGE;
}

View File

@ -0,0 +1,584 @@
/**
* Copyright (c) Nicolas Gallagher
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
/**
* RESPONDER EVENT SYSTEM
*
* A single, global "interaction lock" on views. For a view to be the "responder" means
* that pointer interactions are exclusive to that view and none other. The "interaction
* lock" can be transferred (only) to ancestors of the current "responder" as long as
* pointers continue to be active.
*
* Responder being granted:
*
* A view can become the "responder" after the following events:
* * "pointerdown" (implemented using "touchstart", "mousedown")
* * "pointermove" (implemented using "touchmove", "mousemove")
* * "scroll" (while a pointer is down)
* * "selectionchange" (while a pointer is down)
*
* If nothing is already the "responder", the event propagates to (capture) and from
* (bubble) the event target until a view returns `true` for
* `on*ShouldSetResponder(Capture)`.
*
* If something is already the responder, the event propagates to (capture) and from
* (bubble) the lowest common ancestor of the event target and the current "responder".
* Then negotiation happens between the current "responder" and a view that wants to
* become the "responder": see the timing diagram below.
*
* (NOTE: Scrolled views either automatically become the "responder" or release the
* "interaction lock". A native scroll view that isn't built on top of the responder
* system must result in the current "responder" being notified that it no longer has
* the "interaction lock" - the native system has taken over.
*
* Responder being released:
*
* As soon as there are no more active pointers that *started* inside descendants
* of the *current* "responder", an `onResponderRelease` event is dispatched to the
* current "responder", and the responder lock is released.
*
* Typical sequence of events:
* * startShouldSetResponder
* * responderGrant/Reject
* * responderStart
* * responderMove
* * responderEnd
* * responderRelease
*/
/* Negotiation Performed
+-----------------------+
/ \
Process low level events to + Current Responder + wantsResponderID
determine who to perform negot-| (if any exists at all) |
iation/transition | Otherwise just pass through|
-------------------------------+----------------------------+------------------+
Bubble to find first ID | |
to return true:wantsResponderID| |
| |
+--------------+ | |
| onTouchStart | | |
+------+-------+ none | |
| return| |
+-----------v-------------+true| +------------------------+ |
|onStartShouldSetResponder|----->| onResponderStart (cur) |<-----------+
+-----------+-------------+ | +------------------------+ | |
| | | +--------+-------+
| returned true for| false:REJECT +-------->|onResponderReject
| wantsResponderID | | | +----------------+
| (now attempt | +------------------+-----+ |
| handoff) | | onResponder | |
+------------------->| TerminationRequest | |
| +------------------+-----+ |
| | | +----------------+
| true:GRANT +-------->|onResponderGrant|
| | +--------+-------+
| +------------------------+ | |
| | onResponderTerminate |<-----------+
| +------------------+-----+ |
| | | +----------------+
| +-------->|onResponderStart|
| | +----------------+
Bubble to find first ID | |
to return true:wantsResponderID| |
| |
+-------------+ | |
| onTouchMove | | |
+------+------+ none | |
| return| |
+-----------v-------------+true| +------------------------+ |
|onMoveShouldSetResponder |----->| onResponderMove (cur) |<-----------+
+-----------+-------------+ | +------------------------+ | |
| | | +--------+-------+
| returned true for| false:REJECT +-------->|onResponderReject
| wantsResponderID | | | +----------------+
| (now attempt | +------------------+-----+ |
| handoff) | | onResponder | |
+------------------->| TerminationRequest| |
| +------------------+-----+ |
| | | +----------------+
| true:GRANT +-------->|onResponderGrant|
| | +--------+-------+
| +------------------------+ | |
| | onResponderTerminate |<-----------+
| +------------------+-----+ |
| | | +----------------+
| +-------->|onResponderMove |
| | +----------------+
| |
| |
Some active touch started| |
inside current responder | +------------------------+ |
+------------------------->| onResponderEnd | |
| | +------------------------+ |
+---+---------+ | |
| onTouchEnd | | |
+---+---------+ | |
| | +------------------------+ |
+------------------------->| onResponderEnd | |
No active touches started| +-----------+------------+ |
inside current responder | | |
| v |
| +------------------------+ |
| | onResponderRelease | |
| +------------------------+ |
| |
+ + */
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import createResponderEvent from './createResponderEvent';
import { isCancelish, isEndish, isMoveish, isScroll, isSelectionChange, isStartish } from './ResponderEventTypes';
import { getLowestCommonAncestor, getResponderPaths, hasTargetTouches, hasValidSelection, isPrimaryPointerDown, setResponderId } from './utils';
import ResponderTouchHistoryStore from './ResponderTouchHistoryStore';
/* ------------ TYPES ------------ */
var emptyObject = {};
/* ------------ IMPLEMENTATION ------------ */
var startRegistration = ['onStartShouldSetResponderCapture', 'onStartShouldSetResponder', {
bubbles: true
}];
var moveRegistration = ['onMoveShouldSetResponderCapture', 'onMoveShouldSetResponder', {
bubbles: true
}];
var scrollRegistration = ['onScrollShouldSetResponderCapture', 'onScrollShouldSetResponder', {
bubbles: false
}];
var shouldSetResponderEvents = {
touchstart: startRegistration,
mousedown: startRegistration,
touchmove: moveRegistration,
mousemove: moveRegistration,
scroll: scrollRegistration
};
var emptyResponder = {
id: null,
idPath: null,
node: null
};
var responderListenersMap = new Map();
var isEmulatingMouseEvents = false;
var trackedTouchCount = 0;
var currentResponder = {
id: null,
node: null,
idPath: null
};
function changeCurrentResponder(responder) {
currentResponder = responder;
}
function getResponderConfig(id) {
var config = responderListenersMap.get(id);
return config != null ? config : emptyObject;
}
/**
* Process native events
*
* A single event listener is used to manage the responder system.
* All pointers are tracked in the ResponderTouchHistoryStore. Native events
* are interpreted in terms of the Responder System and checked to see if
* the responder should be transferred. Each host node that is attached to
* the Responder System has an ID, which is used to look up its associated
* callbacks.
*/
function eventListener(domEvent) {
var eventType = domEvent.type;
var eventTarget = domEvent.target;
/**
* Manage emulated events and early bailout.
* Since PointerEvent is not used yet (lack of support in older Safari), it's
* necessary to manually manage the mess of browser touch/mouse events.
* And bailout early for termination events when there is no active responder.
*/
// Flag when browser may produce emulated events
if (eventType === 'touchstart') {
isEmulatingMouseEvents = true;
} // Remove flag when browser will not produce emulated events
if (eventType === 'touchmove' || trackedTouchCount > 1) {
isEmulatingMouseEvents = false;
} // Ignore various events in particular circumstances
if ( // Ignore browser emulated mouse events
eventType === 'mousedown' && isEmulatingMouseEvents || eventType === 'mousemove' && isEmulatingMouseEvents || // Ignore mousemove if a mousedown didn't occur first
eventType === 'mousemove' && trackedTouchCount < 1) {
return;
} // Remove flag after emulated events are finished
if (isEmulatingMouseEvents && eventType === 'mouseup') {
if (trackedTouchCount === 0) {
isEmulatingMouseEvents = false;
}
return;
}
var isStartEvent = isStartish(eventType) && isPrimaryPointerDown(domEvent);
var isMoveEvent = isMoveish(eventType);
var isEndEvent = isEndish(eventType);
var isScrollEvent = isScroll(eventType);
var isSelectionChangeEvent = isSelectionChange(eventType);
var responderEvent = createResponderEvent(domEvent);
/**
* Record the state of active pointers
*/
if (isStartEvent || isMoveEvent || isEndEvent) {
if (domEvent.touches) {
trackedTouchCount = domEvent.touches.length;
} else {
if (isStartEvent) {
trackedTouchCount = 1;
} else if (isEndEvent) {
trackedTouchCount = 0;
}
}
ResponderTouchHistoryStore.recordTouchTrack(eventType, responderEvent.nativeEvent);
}
/**
* Responder System logic
*/
var eventPaths = getResponderPaths(domEvent);
var wasNegotiated = false;
var wantsResponder; // If an event occured that might change the current responder...
if (isStartEvent || isMoveEvent || isScrollEvent && trackedTouchCount > 0) {
// If there is already a responder, prune the event paths to the lowest common ancestor
// of the existing responder and deepest target of the event.
var currentResponderIdPath = currentResponder.idPath;
var eventIdPath = eventPaths.idPath;
if (currentResponderIdPath != null && eventIdPath != null) {
var lowestCommonAncestor = getLowestCommonAncestor(currentResponderIdPath, eventIdPath);
if (lowestCommonAncestor != null) {
var indexOfLowestCommonAncestor = eventIdPath.indexOf(lowestCommonAncestor); // Skip the current responder so it doesn't receive unexpected "shouldSet" events.
var index = indexOfLowestCommonAncestor + (lowestCommonAncestor === currentResponder.id ? 1 : 0);
eventPaths = {
idPath: eventIdPath.slice(index),
nodePath: eventPaths.nodePath.slice(index)
};
} else {
eventPaths = null;
}
}
if (eventPaths != null) {
// If a node wants to become the responder, attempt to transfer.
wantsResponder = findWantsResponder(eventPaths, domEvent, responderEvent);
if (wantsResponder != null) {
// Sets responder if none exists, or negotates with existing responder.
attemptTransfer(responderEvent, wantsResponder);
wasNegotiated = true;
}
}
} // If there is now a responder, invoke its callbacks for the lifecycle of the gesture.
if (currentResponder.id != null && currentResponder.node != null) {
var _currentResponder = currentResponder,
id = _currentResponder.id,
node = _currentResponder.node;
var _getResponderConfig = getResponderConfig(id),
onResponderStart = _getResponderConfig.onResponderStart,
onResponderMove = _getResponderConfig.onResponderMove,
onResponderEnd = _getResponderConfig.onResponderEnd,
onResponderRelease = _getResponderConfig.onResponderRelease,
onResponderTerminate = _getResponderConfig.onResponderTerminate,
onResponderTerminationRequest = _getResponderConfig.onResponderTerminationRequest;
responderEvent.bubbles = false;
responderEvent.cancelable = false;
responderEvent.currentTarget = node; // Start
if (isStartEvent) {
if (onResponderStart != null) {
onResponderStart(responderEvent);
}
} // Move
else if (isMoveEvent) {
if (onResponderMove != null) {
onResponderMove(responderEvent);
}
} else {
var isTerminateEvent = isCancelish(eventType) || // native context menu
eventType === 'contextmenu' || // window blur
eventType === 'blur' && eventTarget === window || // responder (or ancestors) blur
eventType === 'blur' && eventTarget.contains(node) && domEvent.relatedTarget !== node || // native scroll without using a pointer
isScrollEvent && trackedTouchCount === 0 || // native scroll on node that is parent of the responder (allow siblings to scroll)
isScrollEvent && eventTarget.contains(node) && eventTarget !== node || // native select/selectionchange on node
isSelectionChangeEvent && hasValidSelection(domEvent);
var isReleaseEvent = isEndEvent && !isTerminateEvent && !hasTargetTouches(node, domEvent.touches); // End
if (isEndEvent) {
if (onResponderEnd != null) {
onResponderEnd(responderEvent);
}
} // Release
if (isReleaseEvent) {
if (onResponderRelease != null) {
onResponderRelease(responderEvent);
}
changeCurrentResponder(emptyResponder);
} // Terminate
if (isTerminateEvent) {
var shouldTerminate = true; // Responders can still avoid termination but only for these events.
if (eventType === 'contextmenu' || eventType === 'scroll' || eventType === 'selectionchange') {
if (wasNegotiated || // Only call this function is it wasn't already called during negotiation.
onResponderTerminationRequest != null && onResponderTerminationRequest(responderEvent) === false) {
shouldTerminate = false;
}
}
if (shouldTerminate) {
if (onResponderTerminate != null) {
onResponderTerminate(responderEvent);
}
changeCurrentResponder(emptyResponder);
isEmulatingMouseEvents = false;
trackedTouchCount = 0;
}
}
}
}
}
/**
* Walk the event path to/from the target node. At each node, stop and call the
* relevant "shouldSet" functions for the given event type. If any of those functions
* call "stopPropagation" on the event, stop searching for a responder.
*/
function findWantsResponder(eventPaths, domEvent, responderEvent) {
var shouldSetCallbacks = shouldSetResponderEvents[domEvent.type]; // for Flow
if (shouldSetCallbacks != null) {
var idPath = eventPaths.idPath,
nodePath = eventPaths.nodePath;
var shouldSetCallbackCaptureName = shouldSetCallbacks[0];
var shouldSetCallbackBubbleName = shouldSetCallbacks[1];
var bubbles = shouldSetCallbacks[2].bubbles;
var check = function check(id, node, callbackName) {
var config = getResponderConfig(id);
var shouldSetCallback = config[callbackName];
if (shouldSetCallback != null) {
if (shouldSetCallback(responderEvent) === true) {
return {
id: id,
node: node,
idPath: idPath
};
}
}
}; // capture
for (var i = idPath.length - 1; i >= 0; i--) {
var id = idPath[i];
var node = nodePath[i];
var result = check(id, node, shouldSetCallbackCaptureName);
if (result != null) {
return result;
}
if (responderEvent.isPropagationStopped() === true) {
return;
}
} // bubble
if (bubbles) {
for (var _i = 0; _i < idPath.length; _i++) {
var _id = idPath[_i];
var _node = nodePath[_i];
var _result = check(_id, _node, shouldSetCallbackBubbleName);
if (_result != null) {
return _result;
}
if (responderEvent.isPropagationStopped() === true) {
return;
}
}
} else {
var _id2 = idPath[0];
var _node2 = nodePath[0];
var target = domEvent.target;
if (target === _node2) {
return check(_id2, _node2, shouldSetCallbackBubbleName);
}
}
}
}
/**
* Attempt to transfer the responder.
*/
function attemptTransfer(responderEvent, wantsResponder) {
var _currentResponder2 = currentResponder,
currentId = _currentResponder2.id,
currentNode = _currentResponder2.node;
var id = wantsResponder.id,
node = wantsResponder.node;
var _getResponderConfig2 = getResponderConfig(id),
onResponderGrant = _getResponderConfig2.onResponderGrant,
onResponderReject = _getResponderConfig2.onResponderReject;
responderEvent.bubbles = false;
responderEvent.cancelable = false;
responderEvent.currentTarget = node; // Set responder
if (currentId == null) {
if (onResponderGrant != null) {
responderEvent.currentTarget = node;
responderEvent.dispatchConfig.registrationName = 'onResponderGrant';
onResponderGrant(responderEvent);
}
changeCurrentResponder(wantsResponder);
} // Negotiate with current responder
else {
var _getResponderConfig3 = getResponderConfig(currentId),
onResponderTerminate = _getResponderConfig3.onResponderTerminate,
onResponderTerminationRequest = _getResponderConfig3.onResponderTerminationRequest;
var allowTransfer = onResponderTerminationRequest != null && onResponderTerminationRequest(responderEvent);
if (allowTransfer) {
// Terminate existing responder
if (onResponderTerminate != null) {
responderEvent.currentTarget = currentNode;
onResponderTerminate(responderEvent);
} // Grant next responder
if (onResponderGrant != null) {
onResponderGrant(responderEvent);
}
changeCurrentResponder(wantsResponder);
} else {
// Reject responder request
if (onResponderReject != null) {
onResponderReject(responderEvent);
}
}
}
}
/* ------------ PUBLIC API ------------ */
/**
* Attach Listeners
*
* Use native events as ReactDOM doesn't have a non-plugin API to implement
* this system.
*/
var documentEventsCapturePhase = ['blur', 'scroll'];
var documentEventsBubblePhase = [// mouse
'mousedown', 'mousemove', 'mouseup', 'dragstart', // touch
'touchstart', 'touchmove', 'touchend', 'touchcancel', // other
'contextmenu', 'select', 'selectionchange'];
export function attachListeners() {
if (canUseDOM && window.__reactResponderSystemActive == null) {
window.addEventListener('blur', eventListener);
documentEventsBubblePhase.forEach(function (eventType) {
document.addEventListener(eventType, eventListener);
});
documentEventsCapturePhase.forEach(function (eventType) {
document.addEventListener(eventType, eventListener, true);
});
window.__reactResponderSystemActive = true;
}
}
/**
* Register a node with the ResponderSystem.
*/
export function addNode(id, node, config) {
setResponderId(node, id);
responderListenersMap.set(id, config);
}
/**
* Unregister a node with the ResponderSystem.
*/
export function removeNode(id) {
if (currentResponder.id === id) {
terminateResponder();
}
if (responderListenersMap.has(id)) {
responderListenersMap.delete(id);
}
}
/**
* Allow the current responder to be terminated from within components to support
* more complex requirements, such as use with other React libraries for working
* with scroll views, input views, etc.
*/
export function terminateResponder() {
var _currentResponder3 = currentResponder,
id = _currentResponder3.id,
node = _currentResponder3.node;
if (id != null && node != null) {
var _getResponderConfig4 = getResponderConfig(id),
onResponderTerminate = _getResponderConfig4.onResponderTerminate;
if (onResponderTerminate != null) {
var event = createResponderEvent({});
event.currentTarget = node;
onResponderTerminate(event);
}
changeCurrentResponder(emptyResponder);
}
isEmulatingMouseEvents = false;
trackedTouchCount = 0;
}
/**
* Allow unit tests to inspect the current responder in the system.
* FOR TESTING ONLY.
*/
export function getResponderNode() {
return currentResponder.node;
}

View File

@ -0,0 +1,188 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import { isStartish, isMoveish, isEndish } from './ResponderEventTypes';
/**
* Tracks the position and time of each active touch by `touch.identifier`. We
* should typically only see IDs in the range of 1-20 because IDs get recycled
* when touches end and start again.
*/
var __DEV__ = process.env.NODE_ENV !== 'production';
var MAX_TOUCH_BANK = 20;
var touchBank = [];
var touchHistory = {
touchBank: touchBank,
numberActiveTouches: 0,
// If there is only one active touch, we remember its location. This prevents
// us having to loop through all of the touches all the time in the most
// common case.
indexOfSingleActiveTouch: -1,
mostRecentTimeStamp: 0
};
function timestampForTouch(touch) {
// The legacy internal implementation provides "timeStamp", which has been
// renamed to "timestamp".
return touch.timeStamp || touch.timestamp;
}
/**
* TODO: Instead of making gestures recompute filtered velocity, we could
* include a built in velocity computation that can be reused globally.
*/
function createTouchRecord(touch) {
return {
touchActive: true,
startPageX: touch.pageX,
startPageY: touch.pageY,
startTimeStamp: timestampForTouch(touch),
currentPageX: touch.pageX,
currentPageY: touch.pageY,
currentTimeStamp: timestampForTouch(touch),
previousPageX: touch.pageX,
previousPageY: touch.pageY,
previousTimeStamp: timestampForTouch(touch)
};
}
function resetTouchRecord(touchRecord, touch) {
touchRecord.touchActive = true;
touchRecord.startPageX = touch.pageX;
touchRecord.startPageY = touch.pageY;
touchRecord.startTimeStamp = timestampForTouch(touch);
touchRecord.currentPageX = touch.pageX;
touchRecord.currentPageY = touch.pageY;
touchRecord.currentTimeStamp = timestampForTouch(touch);
touchRecord.previousPageX = touch.pageX;
touchRecord.previousPageY = touch.pageY;
touchRecord.previousTimeStamp = timestampForTouch(touch);
}
function getTouchIdentifier(_ref) {
var identifier = _ref.identifier;
if (identifier == null) {
console.error('Touch object is missing identifier.');
}
if (__DEV__) {
if (identifier > MAX_TOUCH_BANK) {
console.error('Touch identifier %s is greater than maximum supported %s which causes ' + 'performance issues backfilling array locations for all of the indices.', identifier, MAX_TOUCH_BANK);
}
}
return identifier;
}
function recordTouchStart(touch) {
var identifier = getTouchIdentifier(touch);
var touchRecord = touchBank[identifier];
if (touchRecord) {
resetTouchRecord(touchRecord, touch);
} else {
touchBank[identifier] = createTouchRecord(touch);
}
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
}
function recordTouchMove(touch) {
var touchRecord = touchBank[getTouchIdentifier(touch)];
if (touchRecord) {
touchRecord.touchActive = true;
touchRecord.previousPageX = touchRecord.currentPageX;
touchRecord.previousPageY = touchRecord.currentPageY;
touchRecord.previousTimeStamp = touchRecord.currentTimeStamp;
touchRecord.currentPageX = touch.pageX;
touchRecord.currentPageY = touch.pageY;
touchRecord.currentTimeStamp = timestampForTouch(touch);
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
} else {
console.warn('Cannot record touch move without a touch start.\n', "Touch Move: " + printTouch(touch) + "\n", "Touch Bank: " + printTouchBank());
}
}
function recordTouchEnd(touch) {
var touchRecord = touchBank[getTouchIdentifier(touch)];
if (touchRecord) {
touchRecord.touchActive = false;
touchRecord.previousPageX = touchRecord.currentPageX;
touchRecord.previousPageY = touchRecord.currentPageY;
touchRecord.previousTimeStamp = touchRecord.currentTimeStamp;
touchRecord.currentPageX = touch.pageX;
touchRecord.currentPageY = touch.pageY;
touchRecord.currentTimeStamp = timestampForTouch(touch);
touchHistory.mostRecentTimeStamp = timestampForTouch(touch);
} else {
console.warn('Cannot record touch end without a touch start.\n', "Touch End: " + printTouch(touch) + "\n", "Touch Bank: " + printTouchBank());
}
}
function printTouch(touch) {
return JSON.stringify({
identifier: touch.identifier,
pageX: touch.pageX,
pageY: touch.pageY,
timestamp: timestampForTouch(touch)
});
}
function printTouchBank() {
var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK));
if (touchBank.length > MAX_TOUCH_BANK) {
printed += ' (original size: ' + touchBank.length + ')';
}
return printed;
}
var ResponderTouchHistoryStore = {
recordTouchTrack: function recordTouchTrack(topLevelType, nativeEvent) {
if (isMoveish(topLevelType)) {
nativeEvent.changedTouches.forEach(recordTouchMove);
} else if (isStartish(topLevelType)) {
nativeEvent.changedTouches.forEach(recordTouchStart);
touchHistory.numberActiveTouches = nativeEvent.touches.length;
if (touchHistory.numberActiveTouches === 1) {
touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier;
}
} else if (isEndish(topLevelType)) {
nativeEvent.changedTouches.forEach(recordTouchEnd);
touchHistory.numberActiveTouches = nativeEvent.touches.length;
if (touchHistory.numberActiveTouches === 1) {
for (var i = 0; i < touchBank.length; i++) {
var touchTrackToCheck = touchBank[i];
if (touchTrackToCheck != null && touchTrackToCheck.touchActive) {
touchHistory.indexOfSingleActiveTouch = i;
break;
}
}
if (__DEV__) {
var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch];
if (!(activeRecord != null && activeRecord.touchActive)) {
console.error('Cannot find single active touch.');
}
}
}
}
},
touchHistory: touchHistory
};
export default ResponderTouchHistoryStore;

View File

@ -0,0 +1,164 @@
/**
* Copyright (c) Nicolas Gallagher
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import getBoundingClientRect from '../../modules/getBoundingClientRect';
import ResponderTouchHistoryStore from './ResponderTouchHistoryStore';
var emptyFunction = function emptyFunction() {};
var emptyObject = {};
var emptyArray = [];
/**
* Safari produces very large identifiers that would cause the `touchBank` array
* length to be so large as to crash the browser, if not normalized like this.
* In the future the `touchBank` should use an object/map instead.
*/
function normalizeIdentifier(identifier) {
return identifier > 20 ? identifier % 20 : identifier;
}
/**
* Converts a native DOM event to a ResponderEvent.
* Mouse events are transformed into fake touch events.
*/
export default function createResponderEvent(domEvent) {
var rect;
var propagationWasStopped = false;
var changedTouches;
var touches;
var domEventChangedTouches = domEvent.changedTouches;
var domEventType = domEvent.type;
var metaKey = domEvent.metaKey === true;
var shiftKey = domEvent.shiftKey === true;
var force = domEventChangedTouches && domEventChangedTouches[0].force || 0;
var identifier = normalizeIdentifier(domEventChangedTouches && domEventChangedTouches[0].identifier || 0);
var clientX = domEventChangedTouches && domEventChangedTouches[0].clientX || domEvent.clientX;
var clientY = domEventChangedTouches && domEventChangedTouches[0].clientY || domEvent.clientY;
var pageX = domEventChangedTouches && domEventChangedTouches[0].pageX || domEvent.pageX;
var pageY = domEventChangedTouches && domEventChangedTouches[0].pageY || domEvent.pageY;
var preventDefault = typeof domEvent.preventDefault === 'function' ? domEvent.preventDefault.bind(domEvent) : emptyFunction;
var timestamp = domEvent.timeStamp;
function normalizeTouches(touches) {
return Array.prototype.slice.call(touches).map(function (touch) {
return {
force: touch.force,
identifier: normalizeIdentifier(touch.identifier),
get locationX() {
return locationX(touch.clientX);
},
get locationY() {
return locationY(touch.clientY);
},
pageX: touch.pageX,
pageY: touch.pageY,
target: touch.target,
timestamp: timestamp
};
});
}
if (domEventChangedTouches != null) {
changedTouches = normalizeTouches(domEventChangedTouches);
touches = normalizeTouches(domEvent.touches);
} else {
var emulatedTouches = [{
force: force,
identifier: identifier,
get locationX() {
return locationX(clientX);
},
get locationY() {
return locationY(clientY);
},
pageX: pageX,
pageY: pageY,
target: domEvent.target,
timestamp: timestamp
}];
changedTouches = emulatedTouches;
touches = domEventType === 'mouseup' || domEventType === 'dragstart' ? emptyArray : emulatedTouches;
}
var responderEvent = {
bubbles: true,
cancelable: true,
// `currentTarget` is set before dispatch
currentTarget: null,
defaultPrevented: domEvent.defaultPrevented,
dispatchConfig: emptyObject,
eventPhase: domEvent.eventPhase,
isDefaultPrevented: function isDefaultPrevented() {
return domEvent.defaultPrevented;
},
isPropagationStopped: function isPropagationStopped() {
return propagationWasStopped;
},
isTrusted: domEvent.isTrusted,
nativeEvent: {
altKey: false,
ctrlKey: false,
metaKey: metaKey,
shiftKey: shiftKey,
changedTouches: changedTouches,
force: force,
identifier: identifier,
get locationX() {
return locationX(clientX);
},
get locationY() {
return locationY(clientY);
},
pageX: pageX,
pageY: pageY,
target: domEvent.target,
timestamp: timestamp,
touches: touches,
type: domEventType
},
persist: emptyFunction,
preventDefault: preventDefault,
stopPropagation: function stopPropagation() {
propagationWasStopped = true;
},
target: domEvent.target,
timeStamp: timestamp,
touchHistory: ResponderTouchHistoryStore.touchHistory
}; // Using getters and functions serves two purposes:
// 1) The value of `currentTarget` is not initially available.
// 2) Measuring the clientRect may cause layout jank and should only be done on-demand.
function locationX(x) {
rect = rect || getBoundingClientRect(responderEvent.currentTarget);
if (rect) {
return x - rect.left;
}
}
function locationY(y) {
rect = rect || getBoundingClientRect(responderEvent.currentTarget);
if (rect) {
return y - rect.top;
}
}
return responderEvent;
}

View File

@ -0,0 +1,78 @@
/**
* Copyright (c) Nicolas Gallagher
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
/**
* Hook for integrating the Responder System into React
*
* function SomeComponent({ onStartShouldSetResponder }) {
* const ref = useRef(null);
* useResponderEvents(ref, { onStartShouldSetResponder });
* return <div ref={ref} />
* }
*/
import * as React from 'react';
import * as ResponderSystem from './ResponderSystem';
var emptyObject = {};
var idCounter = 0;
function useStable(getInitialValue) {
var ref = React.useRef(null);
if (ref.current == null) {
ref.current = getInitialValue();
}
return ref.current;
}
export default function useResponderEvents(hostRef, config) {
if (config === void 0) {
config = emptyObject;
}
var id = useStable(function () {
return idCounter++;
});
var isAttachedRef = React.useRef(false); // This is a separate effects so it doesn't run when the config changes.
// On initial mount, attach global listeners if needed.
// On unmount, remove node potentially attached to the Responder System.
React.useEffect(function () {
ResponderSystem.attachListeners();
return function () {
ResponderSystem.removeNode(id);
};
}, [id]); // Register and unregister with the Responder System as necessary
React.useEffect(function () {
var _config = config,
onMoveShouldSetResponder = _config.onMoveShouldSetResponder,
onMoveShouldSetResponderCapture = _config.onMoveShouldSetResponderCapture,
onScrollShouldSetResponder = _config.onScrollShouldSetResponder,
onScrollShouldSetResponderCapture = _config.onScrollShouldSetResponderCapture,
onSelectionChangeShouldSetResponder = _config.onSelectionChangeShouldSetResponder,
onSelectionChangeShouldSetResponderCapture = _config.onSelectionChangeShouldSetResponderCapture,
onStartShouldSetResponder = _config.onStartShouldSetResponder,
onStartShouldSetResponderCapture = _config.onStartShouldSetResponderCapture;
var requiresResponderSystem = onMoveShouldSetResponder != null || onMoveShouldSetResponderCapture != null || onScrollShouldSetResponder != null || onScrollShouldSetResponderCapture != null || onSelectionChangeShouldSetResponder != null || onSelectionChangeShouldSetResponderCapture != null || onStartShouldSetResponder != null || onStartShouldSetResponderCapture != null;
var node = hostRef.current;
if (requiresResponderSystem) {
ResponderSystem.addNode(id, node, config);
isAttachedRef.current = true;
} else if (isAttachedRef.current) {
ResponderSystem.removeNode(id);
isAttachedRef.current = false;
}
}, [config, hostRef, id]);
React.useDebugValue({
isResponder: hostRef.current === ResponderSystem.getResponderNode()
});
React.useDebugValue(config);
}

View File

@ -0,0 +1,182 @@
/**
* Copyright (c) Nicolas Gallagher
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import isSelectionValid from '../../modules/isSelectionValid';
var keyName = '__reactResponderId';
function getEventPath(domEvent) {
// The 'selectionchange' event always has the 'document' as the target.
// Use the anchor node as the initial target to reconstruct a path.
// (We actually only need the first "responder" node in practice.)
if (domEvent.type === 'selectionchange') {
var target = window.getSelection().anchorNode;
return composedPathFallback(target);
} else {
var path = domEvent.composedPath != null ? domEvent.composedPath() : composedPathFallback(domEvent.target);
return path;
}
}
function composedPathFallback(target) {
var path = [];
while (target != null && target !== document.body) {
path.push(target);
target = target.parentNode;
}
return path;
}
/**
* Retrieve the responderId from a host node
*/
function getResponderId(node) {
if (node != null) {
return node[keyName];
}
return null;
}
/**
* Store the responderId on a host node
*/
export function setResponderId(node, id) {
if (node != null) {
node[keyName] = id;
}
}
/**
* Filter the event path to contain only the nodes attached to the responder system
*/
export function getResponderPaths(domEvent) {
var idPath = [];
var nodePath = [];
var eventPath = getEventPath(domEvent);
for (var i = 0; i < eventPath.length; i++) {
var node = eventPath[i];
var id = getResponderId(node);
if (id != null) {
idPath.push(id);
nodePath.push(node);
}
}
return {
idPath: idPath,
nodePath: nodePath
};
}
/**
* Walk the paths and find the first common ancestor
*/
export function getLowestCommonAncestor(pathA, pathB) {
var pathALength = pathA.length;
var pathBLength = pathB.length;
if ( // If either path is empty
pathALength === 0 || pathBLength === 0 || // If the last elements aren't the same there can't be a common ancestor
// that is connected to the responder system
pathA[pathALength - 1] !== pathB[pathBLength - 1]) {
return null;
}
var itemA = pathA[0];
var indexA = 0;
var itemB = pathB[0];
var indexB = 0; // If A is deeper, skip indices that can't match.
if (pathALength - pathBLength > 0) {
indexA = pathALength - pathBLength;
itemA = pathA[indexA];
pathALength = pathBLength;
} // If B is deeper, skip indices that can't match
if (pathBLength - pathALength > 0) {
indexB = pathBLength - pathALength;
itemB = pathB[indexB];
pathBLength = pathALength;
} // Walk in lockstep until a match is found
var depth = pathALength;
while (depth--) {
if (itemA === itemB) {
return itemA;
}
itemA = pathA[indexA++];
itemB = pathB[indexB++];
}
return null;
}
/**
* Determine whether any of the active touches are within the current responder.
* This cannot rely on W3C `targetTouches`, as neither IE11 nor Safari implement it.
*/
export function hasTargetTouches(target, touches) {
if (!touches || touches.length === 0) {
return false;
}
for (var i = 0; i < touches.length; i++) {
var node = touches[i].target;
if (node != null) {
if (target.contains(node)) {
return true;
}
}
}
return false;
}
/**
* Ignore 'selectionchange' events that don't correspond with a person's intent to
* select text.
*/
export function hasValidSelection(domEvent) {
if (domEvent.type === 'selectionchange') {
return isSelectionValid();
}
return domEvent.type === 'select';
}
/**
* Events are only valid if the primary button was used without specific modifier keys.
*/
export function isPrimaryPointerDown(domEvent) {
var altKey = domEvent.altKey,
button = domEvent.button,
buttons = domEvent.buttons,
ctrlKey = domEvent.ctrlKey,
type = domEvent.type;
var isTouch = type === 'touchstart' || type === 'touchmove';
var isPrimaryMouseDown = type === 'mousedown' && (button === 0 || buttons === 1);
var isPrimaryMouseMove = type === 'mousemove' && buttons === 1;
var noModifiers = altKey === false && ctrlKey === false;
if (isTouch || isPrimaryMouseDown && noModifiers || isPrimaryMouseMove && noModifiers) {
return true;
}
return false;
}