diff --git a/.gitignore b/.gitignore index d77e8f191b..269fec9bfe 100644 --- a/.gitignore +++ b/.gitignore @@ -57,6 +57,3 @@ jsconfig.json # TS dist/ - -# generated by bob -/lib/ diff --git a/android/build.gradle b/android/build.gradle index 9ddfa57ca2..b2cfcdabd6 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -67,7 +67,7 @@ dependencies { //noinspection GradleDynamicVersion if (shouldUseCommonInterfaceFromReanimated()) { // Include Reanimated as dependency to load the common interface - implementation project(':react-native-reanimated') + implementation project(':react:react-native-reanimated') } implementation 'com.facebook.react:react-native:+' implementation 'androidx.appcompat:appcompat:1.2.0' diff --git a/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerEnabledRootView.kt b/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerEnabledRootView.kt index 7de0492f42..93d9e1b917 100644 --- a/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerEnabledRootView.kt +++ b/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerEnabledRootView.kt @@ -8,7 +8,7 @@ import com.facebook.react.ReactInstanceManager import com.facebook.react.ReactRootView @Deprecated(message = "Use component instead. Check gesture handler installation instructions in documentation for more information.") -class RNGestureHandlerEnabledRootView : ReactRootView { +open class RNGestureHandlerEnabledRootView : ReactRootView { private lateinit var _reactInstanceManager: ReactInstanceManager private var gestureRootHelper: RNGestureHandlerRootHelper? = null diff --git a/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootView.kt b/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootView.kt index b6f3dbb467..ac5edf58b1 100644 --- a/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootView.kt +++ b/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootView.kt @@ -12,7 +12,7 @@ import com.facebook.react.uimanager.RootView import com.facebook.react.views.modal.ReactModalHostView import com.facebook.react.views.view.ReactViewGroup -class RNGestureHandlerRootView(context: Context?) : ReactViewGroup(context) { +open class RNGestureHandlerRootView(context: Context?) : ReactViewGroup(context) { private var _enabled = false private var rootHelper: RNGestureHandlerRootHelper? = null // TODO: resettable lateinit override fun onAttachedToWindow() { diff --git a/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootViewManager.kt b/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootViewManager.kt index 20129baaef..272d00045e 100644 --- a/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootViewManager.kt +++ b/android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerRootViewManager.kt @@ -10,7 +10,7 @@ import com.facebook.react.uimanager.ViewGroupManager * to be provided. */ @ReactModule(name = RNGestureHandlerRootViewManager.REACT_CLASS) -class RNGestureHandlerRootViewManager : ViewGroupManager() { +open class RNGestureHandlerRootViewManager : ViewGroupManager() { override fun getName() = REACT_CLASS override fun createViewInstance(reactContext: ThemedReactContext) = RNGestureHandlerRootView(reactContext) diff --git a/lib/commonjs/Directions.js b/lib/commonjs/Directions.js new file mode 100644 index 0000000000..0a648c898b --- /dev/null +++ b/lib/commonjs/Directions.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Directions = void 0; +const Directions = { + RIGHT: 1, + LEFT: 2, + UP: 4, + DOWN: 8 +}; // eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; it can be used as a type and as a value + +exports.Directions = Directions; +//# sourceMappingURL=Directions.js.map \ No newline at end of file diff --git a/lib/commonjs/Directions.js.map b/lib/commonjs/Directions.js.map new file mode 100644 index 0000000000..b2d0f8d8f5 --- /dev/null +++ b/lib/commonjs/Directions.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["Directions.ts"],"names":["Directions","RIGHT","LEFT","UP","DOWN"],"mappings":";;;;;;AAAO,MAAMA,UAAU,GAAG;AACxBC,EAAAA,KAAK,EAAE,CADiB;AAExBC,EAAAA,IAAI,EAAE,CAFkB;AAGxBC,EAAAA,EAAE,EAAE,CAHoB;AAIxBC,EAAAA,IAAI,EAAE;AAJkB,CAAnB,C,CAOP","sourcesContent":["export const Directions = {\n RIGHT: 1,\n LEFT: 2,\n UP: 4,\n DOWN: 8,\n} as const;\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; it can be used as a type and as a value\nexport type Directions = typeof Directions[keyof typeof Directions];\n"]} \ No newline at end of file diff --git a/lib/commonjs/EventType.js b/lib/commonjs/EventType.js new file mode 100644 index 0000000000..b9466dc210 --- /dev/null +++ b/lib/commonjs/EventType.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.EventType = void 0; +const EventType = { + UNDETERMINED: 0, + TOUCHES_DOWN: 1, + TOUCHES_MOVE: 2, + TOUCHES_UP: 3, + TOUCHES_CANCELLED: 4 +}; // eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; it can be used as a type and as a value + +exports.EventType = EventType; +//# sourceMappingURL=EventType.js.map \ No newline at end of file diff --git a/lib/commonjs/EventType.js.map b/lib/commonjs/EventType.js.map new file mode 100644 index 0000000000..61c638d85e --- /dev/null +++ b/lib/commonjs/EventType.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["EventType.ts"],"names":["EventType","UNDETERMINED","TOUCHES_DOWN","TOUCHES_MOVE","TOUCHES_UP","TOUCHES_CANCELLED"],"mappings":";;;;;;AAAO,MAAMA,SAAS,GAAG;AACvBC,EAAAA,YAAY,EAAE,CADS;AAEvBC,EAAAA,YAAY,EAAE,CAFS;AAGvBC,EAAAA,YAAY,EAAE,CAHS;AAIvBC,EAAAA,UAAU,EAAE,CAJW;AAKvBC,EAAAA,iBAAiB,EAAE;AALI,CAAlB,C,CAQP","sourcesContent":["export const EventType = {\n UNDETERMINED: 0,\n TOUCHES_DOWN: 1,\n TOUCHES_MOVE: 2,\n TOUCHES_UP: 3,\n TOUCHES_CANCELLED: 4,\n} as const;\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; it can be used as a type and as a value\nexport type EventType = typeof EventType[keyof typeof EventType];\n"]} \ No newline at end of file diff --git a/lib/commonjs/GestureHandlerRootView.android.js b/lib/commonjs/GestureHandlerRootView.android.js new file mode 100644 index 0000000000..91fe5f54f4 --- /dev/null +++ b/lib/commonjs/GestureHandlerRootView.android.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = GestureHandlerRootView; + +var React = _interopRequireWildcard(require("react")); + +var _reactNative = require("react-native"); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +const GestureHandlerRootViewNative = (0, _reactNative.requireNativeComponent)('GestureHandlerRootView'); + +function GestureHandlerRootView({ + children, + ...rest +}) { + return /*#__PURE__*/React.createElement(GestureHandlerRootViewNative, rest, children); +} +//# sourceMappingURL=GestureHandlerRootView.android.js.map \ No newline at end of file diff --git a/lib/commonjs/GestureHandlerRootView.android.js.map b/lib/commonjs/GestureHandlerRootView.android.js.map new file mode 100644 index 0000000000..2eb1cedb29 --- /dev/null +++ b/lib/commonjs/GestureHandlerRootView.android.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureHandlerRootView.android.tsx"],"names":["GestureHandlerRootViewNative","GestureHandlerRootView","children","rest"],"mappings":";;;;;;;AAAA;;AACA;;;;;;AAGA,MAAMA,4BAA4B,GAAG,yCACnC,wBADmC,CAArC;;AAIe,SAASC,sBAAT,CAAgC;AAC7CC,EAAAA,QAD6C;AAE7C,KAAGC;AAF0C,CAAhC,EAGiB;AAC9B,sBACE,oBAAC,4BAAD,EAAkCA,IAAlC,EACGD,QADH,CADF;AAKD","sourcesContent":["import * as React from 'react';\nimport { requireNativeComponent } from 'react-native';\nimport { GestureHandlerRootViewProps } from './GestureHandlerRootView';\n\nconst GestureHandlerRootViewNative = requireNativeComponent(\n 'GestureHandlerRootView'\n);\n\nexport default function GestureHandlerRootView({\n children,\n ...rest\n}: GestureHandlerRootViewProps) {\n return (\n \n {children}\n \n );\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/GestureHandlerRootView.js b/lib/commonjs/GestureHandlerRootView.js new file mode 100644 index 0000000000..94486dd7c9 --- /dev/null +++ b/lib/commonjs/GestureHandlerRootView.js @@ -0,0 +1,20 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = GestureHandlerRootView; + +var React = _interopRequireWildcard(require("react")); + +var _reactNative = require("react-native"); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function GestureHandlerRootView({ ...rest +}) { + return /*#__PURE__*/React.createElement(_reactNative.View, rest); +} +//# sourceMappingURL=GestureHandlerRootView.js.map \ No newline at end of file diff --git a/lib/commonjs/GestureHandlerRootView.js.map b/lib/commonjs/GestureHandlerRootView.js.map new file mode 100644 index 0000000000..7f71aac6de --- /dev/null +++ b/lib/commonjs/GestureHandlerRootView.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureHandlerRootView.tsx"],"names":["GestureHandlerRootView","rest"],"mappings":";;;;;;;AAAA;;AAEA;;;;;;AAKe,SAASA,sBAAT,CAAgC,EAC7C,GAAGC;AAD0C,CAAhC,EAEiB;AAC9B,sBAAO,oBAAC,iBAAD,EAAUA,IAAV,CAAP;AACD","sourcesContent":["import * as React from 'react';\nimport { PropsWithChildren } from 'react';\nimport { View, ViewProps } from 'react-native';\n\nexport interface GestureHandlerRootViewProps\n extends PropsWithChildren {}\n\nexport default function GestureHandlerRootView({\n ...rest\n}: GestureHandlerRootViewProps) {\n return ;\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/PlatformConstants.js b/lib/commonjs/PlatformConstants.js new file mode 100644 index 0000000000..ae712688f9 --- /dev/null +++ b/lib/commonjs/PlatformConstants.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _reactNative = require("react-native"); + +var _NativeModules$Platfo; + +var _default = (_NativeModules$Platfo = _reactNative.NativeModules === null || _reactNative.NativeModules === void 0 ? void 0 : _reactNative.NativeModules.PlatformConstants) !== null && _NativeModules$Platfo !== void 0 ? _NativeModules$Platfo : _reactNative.Platform.constants; + +exports.default = _default; +//# sourceMappingURL=PlatformConstants.js.map \ No newline at end of file diff --git a/lib/commonjs/PlatformConstants.js.map b/lib/commonjs/PlatformConstants.js.map new file mode 100644 index 0000000000..934a9b9076 --- /dev/null +++ b/lib/commonjs/PlatformConstants.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PlatformConstants.ts"],"names":["NativeModules","PlatformConstants","Platform","constants"],"mappings":";;;;;;;AAAA;;;;wCAMgBA,0B,aAAAA,0B,uBAAAA,2BAAeC,iB,yEAC7BC,sBAASC,S","sourcesContent":["import { NativeModules, Platform } from 'react-native';\n\ntype PlatformConstants = {\n forceTouchAvailable: boolean;\n};\n\nexport default (NativeModules?.PlatformConstants ??\n Platform.constants) as PlatformConstants;\n"]} \ No newline at end of file diff --git a/lib/commonjs/PlatformConstants.web.js b/lib/commonjs/PlatformConstants.web.js new file mode 100644 index 0000000000..d45ae5bd67 --- /dev/null +++ b/lib/commonjs/PlatformConstants.web.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = { + get forceTouchAvailable() { + return false; + } + +}; +exports.default = _default; +//# sourceMappingURL=PlatformConstants.web.js.map \ No newline at end of file diff --git a/lib/commonjs/PlatformConstants.web.js.map b/lib/commonjs/PlatformConstants.web.js.map new file mode 100644 index 0000000000..7d37762681 --- /dev/null +++ b/lib/commonjs/PlatformConstants.web.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PlatformConstants.web.ts"],"names":["forceTouchAvailable"],"mappings":";;;;;;eAAe;AACb,MAAIA,mBAAJ,GAA0B;AACxB,WAAO,KAAP;AACD;;AAHY,C","sourcesContent":["export default {\n get forceTouchAvailable() {\n return false;\n },\n};\n"]} \ No newline at end of file diff --git a/lib/commonjs/RNGestureHandlerModule.js b/lib/commonjs/RNGestureHandlerModule.js new file mode 100644 index 0000000000..3d75573506 --- /dev/null +++ b/lib/commonjs/RNGestureHandlerModule.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _reactNative = require("react-native"); + +const { + RNGestureHandlerModule +} = _reactNative.NativeModules; + +if (RNGestureHandlerModule == null) { + console.error(`react-native-gesture-handler module was not found. Make sure you're running your app on the native platform and your code is linked properly (cd ios && pod install && cd ..). + + For installation instructions, please refer to https://docs.swmansion.com/react-native-gesture-handler/docs/#installation`.split('\n').map(line => line.trim()).join('\n')); +} + +var _default = RNGestureHandlerModule; +exports.default = _default; +//# sourceMappingURL=RNGestureHandlerModule.js.map \ No newline at end of file diff --git a/lib/commonjs/RNGestureHandlerModule.js.map b/lib/commonjs/RNGestureHandlerModule.js.map new file mode 100644 index 0000000000..9e18c5a821 --- /dev/null +++ b/lib/commonjs/RNGestureHandlerModule.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["RNGestureHandlerModule.ts"],"names":["RNGestureHandlerModule","NativeModules","console","error","split","map","line","trim","join"],"mappings":";;;;;;;AAAA;;AACA,MAAM;AAAEA,EAAAA;AAAF,IAA6BC,0BAAnC;;AAEA,IAAID,sBAAsB,IAAI,IAA9B,EAAoC;AAClCE,EAAAA,OAAO,CAACC,KAAR,CACG;AACL;AACA,8HAFI,CAGGC,KAHH,CAGS,IAHT,EAIGC,GAJH,CAIQC,IAAD,IAAUA,IAAI,CAACC,IAAL,EAJjB,EAKGC,IALH,CAKQ,IALR,CADF;AAQD;;eAsBcR,sB","sourcesContent":["import { NativeModules } from 'react-native';\nconst { RNGestureHandlerModule } = NativeModules;\n\nif (RNGestureHandlerModule == null) {\n console.error(\n `react-native-gesture-handler module was not found. Make sure you're running your app on the native platform and your code is linked properly (cd ios && pod install && cd ..).\n\n For installation instructions, please refer to https://docs.swmansion.com/react-native-gesture-handler/docs/#installation`\n .split('\\n')\n .map((line) => line.trim())\n .join('\\n')\n );\n}\n\nexport type RNGestureHandlerModuleProps = {\n handleSetJSResponder: (tag: number, blockNativeResponder: boolean) => void;\n handleClearJSResponder: () => void;\n createGestureHandler: (\n handlerName: string,\n handlerTag: number,\n config: Readonly>\n ) => void;\n attachGestureHandler: (\n handlerTag: number,\n newView: number,\n usingDeviceEvents: boolean\n ) => void;\n updateGestureHandler: (\n handlerTag: number,\n newConfig: Readonly>\n ) => void;\n dropGestureHandler: (handlerTag: number) => void;\n};\n\nexport default RNGestureHandlerModule as RNGestureHandlerModuleProps;\n"]} \ No newline at end of file diff --git a/lib/commonjs/RNGestureHandlerModule.web.js b/lib/commonjs/RNGestureHandlerModule.web.js new file mode 100644 index 0000000000..712e6eca58 --- /dev/null +++ b/lib/commonjs/RNGestureHandlerModule.web.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.Gestures = void 0; + +var _constants = require("./web/constants"); + +var _FlingGestureHandler = _interopRequireDefault(require("./web/FlingGestureHandler")); + +var _LongPressGestureHandler = _interopRequireDefault(require("./web/LongPressGestureHandler")); + +var _NativeViewGestureHandler = _interopRequireDefault(require("./web/NativeViewGestureHandler")); + +var NodeManager = _interopRequireWildcard(require("./web/NodeManager")); + +var _PanGestureHandler = _interopRequireDefault(require("./web/PanGestureHandler")); + +var _PinchGestureHandler = _interopRequireDefault(require("./web/PinchGestureHandler")); + +var _RotationGestureHandler = _interopRequireDefault(require("./web/RotationGestureHandler")); + +var _TapGestureHandler = _interopRequireDefault(require("./web/TapGestureHandler")); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const Gestures = { + PanGestureHandler: _PanGestureHandler.default, + RotationGestureHandler: _RotationGestureHandler.default, + PinchGestureHandler: _PinchGestureHandler.default, + TapGestureHandler: _TapGestureHandler.default, + NativeViewGestureHandler: _NativeViewGestureHandler.default, + LongPressGestureHandler: _LongPressGestureHandler.default, + FlingGestureHandler: _FlingGestureHandler.default // ForceTouchGestureHandler, + +}; +exports.Gestures = Gestures; +var _default = { + Direction: _constants.Direction, + + handleSetJSResponder(tag, blockNativeResponder) { + console.warn('handleSetJSResponder: ', tag, blockNativeResponder); + }, + + handleClearJSResponder() { + console.warn('handleClearJSResponder: '); + }, + + createGestureHandler(handlerName, handlerTag, config) { + //TODO(TS) extends config + if (!(handlerName in Gestures)) throw new Error(`react-native-gesture-handler: ${handlerName} is not supported on web.`); + const GestureClass = Gestures[handlerName]; + NodeManager.createGestureHandler(handlerTag, new GestureClass()); + this.updateGestureHandler(handlerTag, config); + }, + + attachGestureHandler(handlerTag, newView, _usingDeviceEvents, propsRef) { + NodeManager.getHandler(handlerTag).setView(newView, propsRef); + }, + + updateGestureHandler(handlerTag, newConfig) { + NodeManager.getHandler(handlerTag).updateGestureConfig(newConfig); + }, + + getGestureHandlerNode(handlerTag) { + return NodeManager.getHandler(handlerTag); + }, + + dropGestureHandler(handlerTag) { + NodeManager.dropGestureHandler(handlerTag); + } + +}; +exports.default = _default; +//# sourceMappingURL=RNGestureHandlerModule.web.js.map \ No newline at end of file diff --git a/lib/commonjs/RNGestureHandlerModule.web.js.map b/lib/commonjs/RNGestureHandlerModule.web.js.map new file mode 100644 index 0000000000..afdf474ea9 --- /dev/null +++ b/lib/commonjs/RNGestureHandlerModule.web.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["RNGestureHandlerModule.web.ts"],"names":["Gestures","PanGestureHandler","RotationGestureHandler","PinchGestureHandler","TapGestureHandler","NativeViewGestureHandler","LongPressGestureHandler","FlingGestureHandler","Direction","handleSetJSResponder","tag","blockNativeResponder","console","warn","handleClearJSResponder","createGestureHandler","handlerName","handlerTag","config","Error","GestureClass","NodeManager","updateGestureHandler","attachGestureHandler","newView","_usingDeviceEvents","propsRef","getHandler","setView","newConfig","updateGestureConfig","getGestureHandlerNode","dropGestureHandler"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;;;;;;;AAEO,MAAMA,QAAQ,GAAG;AACtBC,EAAAA,iBAAiB,EAAjBA,0BADsB;AAEtBC,EAAAA,sBAAsB,EAAtBA,+BAFsB;AAGtBC,EAAAA,mBAAmB,EAAnBA,4BAHsB;AAItBC,EAAAA,iBAAiB,EAAjBA,0BAJsB;AAKtBC,EAAAA,wBAAwB,EAAxBA,iCALsB;AAMtBC,EAAAA,uBAAuB,EAAvBA,gCANsB;AAOtBC,EAAAA,mBAAmB,EAAnBA,4BAPsB,CAQtB;;AARsB,CAAjB;;eAWQ;AACbC,EAAAA,SAAS,EAATA,oBADa;;AAEbC,EAAAA,oBAAoB,CAACC,GAAD,EAAcC,oBAAd,EAA6C;AAC/DC,IAAAA,OAAO,CAACC,IAAR,CAAa,wBAAb,EAAuCH,GAAvC,EAA4CC,oBAA5C;AACD,GAJY;;AAKbG,EAAAA,sBAAsB,GAAG;AACvBF,IAAAA,OAAO,CAACC,IAAR,CAAa,0BAAb;AACD,GAPY;;AAQbE,EAAAA,oBAAoB,CAClBC,WADkB,EAElBC,UAFkB,EAGlBC,MAHkB,EAIlB;AACA;AACA,QAAI,EAAEF,WAAW,IAAIhB,QAAjB,CAAJ,EACE,MAAM,IAAImB,KAAJ,CACH,iCAAgCH,WAAY,2BADzC,CAAN;AAGF,UAAMI,YAAY,GAAGpB,QAAQ,CAACgB,WAAD,CAA7B;AACAK,IAAAA,WAAW,CAACN,oBAAZ,CAAiCE,UAAjC,EAA6C,IAAIG,YAAJ,EAA7C;AACA,SAAKE,oBAAL,CAA0BL,UAA1B,EAAsCC,MAAtC;AACD,GArBY;;AAsBbK,EAAAA,oBAAoB,CAClBN,UADkB,EAElBO,OAFkB,EAGlBC,kBAHkB,EAIlBC,QAJkB,EAKlB;AACAL,IAAAA,WAAW,CAACM,UAAZ,CAAuBV,UAAvB,EAAmCW,OAAnC,CAA2CJ,OAA3C,EAAoDE,QAApD;AACD,GA7BY;;AA8BbJ,EAAAA,oBAAoB,CAACL,UAAD,EAAqBY,SAArB,EAAqC;AACvDR,IAAAA,WAAW,CAACM,UAAZ,CAAuBV,UAAvB,EAAmCa,mBAAnC,CAAuDD,SAAvD;AACD,GAhCY;;AAiCbE,EAAAA,qBAAqB,CAACd,UAAD,EAAqB;AACxC,WAAOI,WAAW,CAACM,UAAZ,CAAuBV,UAAvB,CAAP;AACD,GAnCY;;AAoCbe,EAAAA,kBAAkB,CAACf,UAAD,EAAqB;AACrCI,IAAAA,WAAW,CAACW,kBAAZ,CAA+Bf,UAA/B;AACD;;AAtCY,C","sourcesContent":["import { Direction } from './web/constants';\nimport FlingGestureHandler from './web/FlingGestureHandler';\nimport LongPressGestureHandler from './web/LongPressGestureHandler';\nimport NativeViewGestureHandler from './web/NativeViewGestureHandler';\nimport * as NodeManager from './web/NodeManager';\nimport PanGestureHandler from './web/PanGestureHandler';\nimport PinchGestureHandler from './web/PinchGestureHandler';\nimport RotationGestureHandler from './web/RotationGestureHandler';\nimport TapGestureHandler from './web/TapGestureHandler';\n\nexport const Gestures = {\n PanGestureHandler,\n RotationGestureHandler,\n PinchGestureHandler,\n TapGestureHandler,\n NativeViewGestureHandler,\n LongPressGestureHandler,\n FlingGestureHandler,\n // ForceTouchGestureHandler,\n};\n\nexport default {\n Direction,\n handleSetJSResponder(tag: number, blockNativeResponder: boolean) {\n console.warn('handleSetJSResponder: ', tag, blockNativeResponder);\n },\n handleClearJSResponder() {\n console.warn('handleClearJSResponder: ');\n },\n createGestureHandler(\n handlerName: keyof typeof Gestures,\n handlerTag: number,\n config: T\n ) {\n //TODO(TS) extends config\n if (!(handlerName in Gestures))\n throw new Error(\n `react-native-gesture-handler: ${handlerName} is not supported on web.`\n );\n const GestureClass = Gestures[handlerName];\n NodeManager.createGestureHandler(handlerTag, new GestureClass());\n this.updateGestureHandler(handlerTag, config);\n },\n attachGestureHandler(\n handlerTag: number,\n newView: number,\n _usingDeviceEvents: boolean,\n propsRef: React.RefObject\n ) {\n NodeManager.getHandler(handlerTag).setView(newView, propsRef);\n },\n updateGestureHandler(handlerTag: number, newConfig: any) {\n NodeManager.getHandler(handlerTag).updateGestureConfig(newConfig);\n },\n getGestureHandlerNode(handlerTag: number) {\n return NodeManager.getHandler(handlerTag);\n },\n dropGestureHandler(handlerTag: number) {\n NodeManager.dropGestureHandler(handlerTag);\n },\n};\n"]} \ No newline at end of file diff --git a/lib/commonjs/State.js b/lib/commonjs/State.js new file mode 100644 index 0000000000..51e09c23ec --- /dev/null +++ b/lib/commonjs/State.js @@ -0,0 +1,18 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.State = void 0; +// TODO use State from RNModule +const State = { + UNDETERMINED: 0, + FAILED: 1, + BEGAN: 2, + CANCELLED: 3, + ACTIVE: 4, + END: 5 +}; // eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; it can be used as a type and as a value + +exports.State = State; +//# sourceMappingURL=State.js.map \ No newline at end of file diff --git a/lib/commonjs/State.js.map b/lib/commonjs/State.js.map new file mode 100644 index 0000000000..5cbd9b0684 --- /dev/null +++ b/lib/commonjs/State.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["State.ts"],"names":["State","UNDETERMINED","FAILED","BEGAN","CANCELLED","ACTIVE","END"],"mappings":";;;;;;AAAA;AAEO,MAAMA,KAAK,GAAG;AACnBC,EAAAA,YAAY,EAAE,CADK;AAEnBC,EAAAA,MAAM,EAAE,CAFW;AAGnBC,EAAAA,KAAK,EAAE,CAHY;AAInBC,EAAAA,SAAS,EAAE,CAJQ;AAKnBC,EAAAA,MAAM,EAAE,CALW;AAMnBC,EAAAA,GAAG,EAAE;AANc,CAAd,C,CASP","sourcesContent":["// TODO use State from RNModule\n\nexport const State = {\n UNDETERMINED: 0,\n FAILED: 1,\n BEGAN: 2,\n CANCELLED: 3,\n ACTIVE: 4,\n END: 5,\n} as const;\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; it can be used as a type and as a value\nexport type State = typeof State[keyof typeof State];\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/DrawerLayout.js b/lib/commonjs/components/DrawerLayout.js new file mode 100644 index 0000000000..3494f2722e --- /dev/null +++ b/lib/commonjs/components/DrawerLayout.js @@ -0,0 +1,535 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var React = _interopRequireWildcard(require("react")); + +var _invariant = _interopRequireDefault(require("invariant")); + +var _reactNative = require("react-native"); + +var _PanGestureHandler = require("../handlers/PanGestureHandler"); + +var _TapGestureHandler = require("../handlers/TapGestureHandler"); + +var _State = require("../State"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +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; } + +const DRAG_TOSS = 0.05; +const IDLE = 'Idle'; +const DRAGGING = 'Dragging'; +const SETTLING = 'Settling'; + +class DrawerLayout extends React.Component { + constructor(_props) { + super(_props); + + _defineProperty(this, "openValue", void 0); + + _defineProperty(this, "onGestureEvent", void 0); + + _defineProperty(this, "accessibilityIsModalView", /*#__PURE__*/React.createRef()); + + _defineProperty(this, "pointerEventsView", /*#__PURE__*/React.createRef()); + + _defineProperty(this, "panGestureHandler", /*#__PURE__*/React.createRef()); + + _defineProperty(this, "drawerShown", false); + + _defineProperty(this, "updateAnimatedEvent", (props, state) => { + // Event definition is based on + const { + drawerPosition, + drawerWidth, + drawerType + } = props; + const { + dragX: dragXValue, + touchX: touchXValue, + drawerTranslation, + containerWidth + } = state; + let dragX = dragXValue; + let touchX = touchXValue; + + if (drawerPosition !== 'left') { + // Most of the code is written in a way to handle left-side drawer. In + // order to handle right-side drawer the only thing we need to do is to + // reverse events coming from gesture handler in a way they emulate + // left-side drawer gestures. E.g. dragX is simply -dragX, and touchX is + // calulcated by subtracing real touchX from the width of the container + // (such that when touch happens at the right edge the value is simply 0) + dragX = _reactNative.Animated.multiply(new _reactNative.Animated.Value(-1), dragXValue); // TODO(TS): (for all "as" in this file) make sure we can map this + + touchX = _reactNative.Animated.add(new _reactNative.Animated.Value(containerWidth), _reactNative.Animated.multiply(new _reactNative.Animated.Value(-1), touchXValue)); // TODO(TS): make sure we can map this; + + touchXValue.setValue(containerWidth); + } else { + touchXValue.setValue(0); + } // While closing the drawer when user starts gesture outside of its area (in greyed + // out part of the window), we want the drawer to follow only once finger reaches the + // edge of the drawer. + // E.g. on the diagram below drawer is illustrate by X signs and the greyed out area by + // dots. The touch gesture starts at '*' and moves left, touch path is indicated by + // an arrow pointing left + // 1) +---------------+ 2) +---------------+ 3) +---------------+ 4) +---------------+ + // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| + // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| + // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| + // |XXXXXXXX|......| |XXXXXXXX|.<-*..| |XXXXXXXX|<--*..| |XXXXX|<-----*..| + // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| + // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| + // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| + // +---------------+ +---------------+ +---------------+ +---------------+ + // + // For the above to work properly we define animated value that will keep + // start position of the gesture. Then we use that value to calculate how + // much we need to subtract from the dragX. If the gesture started on the + // greyed out area we take the distance from the edge of the drawer to the + // start position. Otherwise we don't subtract at all and the drawer be + // pulled back as soon as you start the pan. + // + // This is used only when drawerType is "front" + // + + + let translationX = dragX; + + if (drawerType === 'front') { + const startPositionX = _reactNative.Animated.add(touchX, _reactNative.Animated.multiply(new _reactNative.Animated.Value(-1), dragX)); + + const dragOffsetFromOnStartPosition = startPositionX.interpolate({ + inputRange: [drawerWidth - 1, drawerWidth, drawerWidth + 1], + outputRange: [0, 0, 1] + }); + translationX = _reactNative.Animated.add(dragX, dragOffsetFromOnStartPosition); // TODO: as above + } + + this.openValue = _reactNative.Animated.add(translationX, drawerTranslation).interpolate({ + inputRange: [0, drawerWidth], + outputRange: [0, 1], + extrapolate: 'clamp' + }); + const gestureOptions = { + useNativeDriver: props.useNativeAnimations + }; + + if (this.props.onDrawerSlide) { + gestureOptions.listener = ev => { + var _this$props$onDrawerS, _this$props; + + const translationX = Math.floor(Math.abs(ev.nativeEvent.translationX)); + const position = translationX / this.state.containerWidth; + (_this$props$onDrawerS = (_this$props = this.props).onDrawerSlide) === null || _this$props$onDrawerS === void 0 ? void 0 : _this$props$onDrawerS.call(_this$props, position); + }; + } + + this.onGestureEvent = _reactNative.Animated.event([{ + nativeEvent: { + translationX: dragXValue, + x: touchXValue + } + }], gestureOptions); + }); + + _defineProperty(this, "handleContainerLayout", ({ + nativeEvent + }) => { + this.setState({ + containerWidth: nativeEvent.layout.width + }); + }); + + _defineProperty(this, "emitStateChanged", (newState, drawerWillShow) => { + var _this$props$onDrawerS2, _this$props2; + + (_this$props$onDrawerS2 = (_this$props2 = this.props).onDrawerStateChanged) === null || _this$props$onDrawerS2 === void 0 ? void 0 : _this$props$onDrawerS2.call(_this$props2, newState, drawerWillShow); + }); + + _defineProperty(this, "openingHandlerStateChange", ({ + nativeEvent + }) => { + if (nativeEvent.oldState === _State.State.ACTIVE) { + this.handleRelease({ + nativeEvent + }); + } else if (nativeEvent.state === _State.State.ACTIVE) { + this.emitStateChanged(DRAGGING, false); + + if (this.props.keyboardDismissMode === 'on-drag') { + _reactNative.Keyboard.dismiss(); + } + + if (this.props.hideStatusBar) { + _reactNative.StatusBar.setHidden(true, this.props.statusBarAnimation || 'slide'); + } + } + }); + + _defineProperty(this, "onTapHandlerStateChange", ({ + nativeEvent + }) => { + if (this.drawerShown && nativeEvent.oldState === _State.State.ACTIVE && this.props.drawerLockMode !== 'locked-open') { + this.closeDrawer(); + } + }); + + _defineProperty(this, "handleRelease", ({ + nativeEvent + }) => { + const { + drawerWidth, + drawerPosition, + drawerType + } = this.props; + const { + containerWidth + } = this.state; + let { + translationX: dragX, + velocityX, + x: touchX + } = nativeEvent; + + if (drawerPosition !== 'left') { + // See description in _updateAnimatedEvent about why events are flipped + // for right-side drawer + dragX = -dragX; + touchX = containerWidth - touchX; + velocityX = -velocityX; + } + + const gestureStartX = touchX - dragX; + let dragOffsetBasedOnStart = 0; + + if (drawerType === 'front') { + dragOffsetBasedOnStart = gestureStartX > drawerWidth ? gestureStartX - drawerWidth : 0; + } + + const startOffsetX = dragX + dragOffsetBasedOnStart + (this.drawerShown ? drawerWidth : 0); + const projOffsetX = startOffsetX + DRAG_TOSS * velocityX; + const shouldOpen = projOffsetX > drawerWidth / 2; + + if (shouldOpen) { + this.animateDrawer(startOffsetX, drawerWidth, velocityX); + } else { + this.animateDrawer(startOffsetX, 0, velocityX); + } + }); + + _defineProperty(this, "updateShowing", showing => { + var _this$accessibilityIs, _this$pointerEventsVi, _this$panGestureHandl; + + this.drawerShown = showing; + (_this$accessibilityIs = this.accessibilityIsModalView.current) === null || _this$accessibilityIs === void 0 ? void 0 : _this$accessibilityIs.setNativeProps({ + accessibilityViewIsModal: showing + }); + (_this$pointerEventsVi = this.pointerEventsView.current) === null || _this$pointerEventsVi === void 0 ? void 0 : _this$pointerEventsVi.setNativeProps({ + pointerEvents: showing ? 'auto' : 'none' + }); + const { + drawerPosition, + minSwipeDistance, + edgeWidth + } = this.props; + const fromLeft = drawerPosition === 'left'; // gestureOrientation is 1 if the expected gesture is from left to right and + // -1 otherwise e.g. when drawer is on the left and is closed we expect left + // to right gesture, thus orientation will be 1. + + const gestureOrientation = (fromLeft ? 1 : -1) * (this.drawerShown ? -1 : 1); // When drawer is closed we want the hitSlop to be horizontally shorter than + // the container size by the value of SLOP. This will make it only activate + // when gesture happens not further than SLOP away from the edge + + const hitSlop = fromLeft ? { + left: 0, + width: showing ? undefined : edgeWidth + } : { + right: 0, + width: showing ? undefined : edgeWidth + }; // @ts-ignore internal API, maybe could be fixed in handler types + + (_this$panGestureHandl = this.panGestureHandler.current) === null || _this$panGestureHandl === void 0 ? void 0 : _this$panGestureHandl.setNativeProps({ + hitSlop, + activeOffsetX: gestureOrientation * minSwipeDistance + }); + }); + + _defineProperty(this, "animateDrawer", (fromValue, toValue, velocity, speed) => { + this.state.dragX.setValue(0); + this.state.touchX.setValue(this.props.drawerPosition === 'left' ? 0 : this.state.containerWidth); + + if (fromValue != null) { + let nextFramePosition = fromValue; + + if (this.props.useNativeAnimations) { + // When using native driver, we predict the next position of the + // animation because it takes one frame of a roundtrip to pass RELEASE + // event from native driver to JS before we can start animating. Without + // it, it is more noticable that the frame is dropped. + if (fromValue < toValue && velocity > 0) { + nextFramePosition = Math.min(fromValue + velocity / 60.0, toValue); + } else if (fromValue > toValue && velocity < 0) { + nextFramePosition = Math.max(fromValue + velocity / 60.0, toValue); + } + } + + this.state.drawerTranslation.setValue(nextFramePosition); + } + + const willShow = toValue !== 0; + this.updateShowing(willShow); + this.emitStateChanged(SETTLING, willShow); + + if (this.props.hideStatusBar) { + _reactNative.StatusBar.setHidden(willShow, this.props.statusBarAnimation || 'slide'); + } + + _reactNative.Animated.spring(this.state.drawerTranslation, { + velocity, + bounciness: 0, + toValue, + useNativeDriver: this.props.useNativeAnimations, + speed: speed !== null && speed !== void 0 ? speed : undefined + }).start(({ + finished + }) => { + if (finished) { + this.emitStateChanged(IDLE, willShow); + + if (willShow) { + var _this$props$onDrawerO, _this$props3; + + (_this$props$onDrawerO = (_this$props3 = this.props).onDrawerOpen) === null || _this$props$onDrawerO === void 0 ? void 0 : _this$props$onDrawerO.call(_this$props3); + } else { + var _this$props$onDrawerC, _this$props4; + + (_this$props$onDrawerC = (_this$props4 = this.props).onDrawerClose) === null || _this$props$onDrawerC === void 0 ? void 0 : _this$props$onDrawerC.call(_this$props4); + } + } + }); + }); + + _defineProperty(this, "openDrawer", (options = {}) => { + this.animateDrawer( // TODO: decide if it should be null or undefined is the proper value + undefined, this.props.drawerWidth, options.velocity ? options.velocity : 0); // We need to force the update, otherwise the overlay is not rerendered and + // it would not be clickable + + this.forceUpdate(); + }); + + _defineProperty(this, "closeDrawer", (options = {}) => { + // TODO: decide if it should be null or undefined is the proper value + this.animateDrawer(undefined, 0, options.velocity ? options.velocity : 0); // We need to force the update, otherwise the overlay is not rerendered and + // it would be still clickable + + this.forceUpdate(); + }); + + _defineProperty(this, "renderOverlay", () => { + /* Overlay styles */ + (0, _invariant.default)(this.openValue, 'should be set'); + const overlayOpacity = this.openValue.interpolate({ + inputRange: [0, 1], + outputRange: [0, 1], + extrapolate: 'clamp' + }); + const dynamicOverlayStyles = { + opacity: overlayOpacity, + backgroundColor: this.props.overlayColor + }; + return /*#__PURE__*/React.createElement(_TapGestureHandler.TapGestureHandler, { + onHandlerStateChange: this.onTapHandlerStateChange + }, /*#__PURE__*/React.createElement(_reactNative.Animated.View, { + pointerEvents: this.drawerShown ? 'auto' : 'none', + ref: this.pointerEventsView, + style: [styles.overlay, dynamicOverlayStyles] + })); + }); + + _defineProperty(this, "renderDrawer", () => { + const { + drawerBackgroundColor, + drawerWidth, + drawerPosition, + drawerType, + drawerContainerStyle, + contentContainerStyle + } = this.props; + const fromLeft = drawerPosition === 'left'; + const drawerSlide = drawerType !== 'back'; + const containerSlide = drawerType !== 'front'; // we rely on row and row-reverse flex directions to position the drawer + // properly. Apparently for RTL these are flipped which requires us to use + // the opposite setting for the drawer to appear from left or right + // according to the drawerPosition prop + + const reverseContentDirection = _reactNative.I18nManager.isRTL ? fromLeft : !fromLeft; + const dynamicDrawerStyles = { + backgroundColor: drawerBackgroundColor, + width: drawerWidth + }; + const openValue = this.openValue; + (0, _invariant.default)(openValue, 'should be set'); + let containerStyles; + + if (containerSlide) { + const containerTranslateX = openValue.interpolate({ + inputRange: [0, 1], + outputRange: fromLeft ? [0, drawerWidth] : [0, -drawerWidth], + extrapolate: 'clamp' + }); + containerStyles = { + transform: [{ + translateX: containerTranslateX + }] + }; + } + + let drawerTranslateX = 0; + + if (drawerSlide) { + const closedDrawerOffset = fromLeft ? -drawerWidth : drawerWidth; + drawerTranslateX = openValue.interpolate({ + inputRange: [0, 1], + outputRange: [closedDrawerOffset, 0], + extrapolate: 'clamp' + }); + } + + const drawerStyles = { + transform: [{ + translateX: drawerTranslateX + }], + flexDirection: reverseContentDirection ? 'row-reverse' : 'row' + }; + return /*#__PURE__*/React.createElement(_reactNative.Animated.View, { + style: styles.main, + onLayout: this.handleContainerLayout + }, /*#__PURE__*/React.createElement(_reactNative.Animated.View, { + style: [drawerType === 'front' ? styles.containerOnBack : styles.containerInFront, containerStyles, contentContainerStyle], + importantForAccessibility: this.drawerShown ? 'no-hide-descendants' : 'yes' + }, typeof this.props.children === 'function' ? this.props.children(this.openValue) : this.props.children, this.renderOverlay()), /*#__PURE__*/React.createElement(_reactNative.Animated.View, { + pointerEvents: "box-none", + ref: this.accessibilityIsModalView, + accessibilityViewIsModal: this.drawerShown, + style: [styles.drawerContainer, drawerStyles, drawerContainerStyle] + }, /*#__PURE__*/React.createElement(_reactNative.View, { + style: dynamicDrawerStyles + }, this.props.renderNavigationView(this.openValue)))); + }); + + _defineProperty(this, "setPanGestureRef", ref => { + var _this$props$onGesture, _this$props5; + + // TODO(TS): make sure it is OK taken from + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31065#issuecomment-596081842 + this.panGestureHandler.current = ref; + (_this$props$onGesture = (_this$props5 = this.props).onGestureRef) === null || _this$props$onGesture === void 0 ? void 0 : _this$props$onGesture.call(_this$props5, ref); + }); + + const _dragX = new _reactNative.Animated.Value(0); + + const _touchX = new _reactNative.Animated.Value(0); + + const _drawerTranslation = new _reactNative.Animated.Value(0); + + this.state = { + dragX: _dragX, + touchX: _touchX, + drawerTranslation: _drawerTranslation, + containerWidth: 0 + }; + this.updateAnimatedEvent(_props, this.state); + } + + UNSAFE_componentWillUpdate(props, state) { + if (this.props.drawerPosition !== props.drawerPosition || this.props.drawerWidth !== props.drawerWidth || this.props.drawerType !== props.drawerType || this.state.containerWidth !== state.containerWidth) { + this.updateAnimatedEvent(props, state); + } + } + + render() { + const { + drawerPosition, + drawerLockMode, + edgeWidth, + minSwipeDistance + } = this.props; + const fromLeft = drawerPosition === 'left'; // gestureOrientation is 1 if the expected gesture is from left to right and + // -1 otherwise e.g. when drawer is on the left and is closed we expect left + // to right gesture, thus orientation will be 1. + + const gestureOrientation = (fromLeft ? 1 : -1) * (this.drawerShown ? -1 : 1); // When drawer is closed we want the hitSlop to be horizontally shorter than + // the container size by the value of SLOP. This will make it only activate + // when gesture happens not further than SLOP away from the edge + + const hitSlop = fromLeft ? { + left: 0, + width: this.drawerShown ? undefined : edgeWidth + } : { + right: 0, + width: this.drawerShown ? undefined : edgeWidth + }; + return /*#__PURE__*/React.createElement(_PanGestureHandler.PanGestureHandler // @ts-ignore could be fixed in handler types + , { + ref: this.setPanGestureRef, + hitSlop: hitSlop, + activeOffsetX: gestureOrientation * minSwipeDistance, + failOffsetY: [-15, 15], + onGestureEvent: this.onGestureEvent, + onHandlerStateChange: this.openingHandlerStateChange, + enableTrackpadTwoFingerGesture: this.props.enableTrackpadTwoFingerGesture, + enabled: drawerLockMode !== 'locked-closed' && drawerLockMode !== 'locked-open' + }, this.renderDrawer()); + } + +} + +exports.default = DrawerLayout; + +_defineProperty(DrawerLayout, "defaultProps", { + drawerWidth: 200, + drawerPosition: 'left', + useNativeAnimations: true, + drawerType: 'front', + edgeWidth: 20, + minSwipeDistance: 3, + overlayColor: 'rgba(0, 0, 0, 0.7)', + drawerLockMode: 'unlocked', + enableTrackpadTwoFingerGesture: false +}); + +_defineProperty(DrawerLayout, "positions", { + Left: 'left', + Right: 'right' +}); + +const styles = _reactNative.StyleSheet.create({ + drawerContainer: { ..._reactNative.StyleSheet.absoluteFillObject, + zIndex: 1001, + flexDirection: 'row' + }, + containerInFront: { ..._reactNative.StyleSheet.absoluteFillObject, + zIndex: 1002 + }, + containerOnBack: { ..._reactNative.StyleSheet.absoluteFillObject + }, + main: { + flex: 1, + zIndex: 0, + overflow: 'hidden' + }, + overlay: { ..._reactNative.StyleSheet.absoluteFillObject, + zIndex: 1000 + } +}); +//# sourceMappingURL=DrawerLayout.js.map \ No newline at end of file diff --git a/lib/commonjs/components/DrawerLayout.js.map b/lib/commonjs/components/DrawerLayout.js.map new file mode 100644 index 0000000000..a0abf4dec6 --- /dev/null +++ b/lib/commonjs/components/DrawerLayout.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["DrawerLayout.tsx"],"names":["DRAG_TOSS","IDLE","DRAGGING","SETTLING","DrawerLayout","Component","constructor","props","React","createRef","state","drawerPosition","drawerWidth","drawerType","dragX","dragXValue","touchX","touchXValue","drawerTranslation","containerWidth","Animated","multiply","Value","add","setValue","translationX","startPositionX","dragOffsetFromOnStartPosition","interpolate","inputRange","outputRange","openValue","extrapolate","gestureOptions","useNativeDriver","useNativeAnimations","onDrawerSlide","listener","ev","Math","floor","abs","nativeEvent","position","onGestureEvent","event","x","setState","layout","width","newState","drawerWillShow","onDrawerStateChanged","oldState","State","ACTIVE","handleRelease","emitStateChanged","keyboardDismissMode","Keyboard","dismiss","hideStatusBar","StatusBar","setHidden","statusBarAnimation","drawerShown","drawerLockMode","closeDrawer","velocityX","gestureStartX","dragOffsetBasedOnStart","startOffsetX","projOffsetX","shouldOpen","animateDrawer","showing","accessibilityIsModalView","current","setNativeProps","accessibilityViewIsModal","pointerEventsView","pointerEvents","minSwipeDistance","edgeWidth","fromLeft","gestureOrientation","hitSlop","left","undefined","right","panGestureHandler","activeOffsetX","fromValue","toValue","velocity","speed","nextFramePosition","min","max","willShow","updateShowing","spring","bounciness","start","finished","onDrawerOpen","onDrawerClose","options","forceUpdate","overlayOpacity","dynamicOverlayStyles","opacity","backgroundColor","overlayColor","onTapHandlerStateChange","styles","overlay","drawerBackgroundColor","drawerContainerStyle","contentContainerStyle","drawerSlide","containerSlide","reverseContentDirection","I18nManager","isRTL","dynamicDrawerStyles","containerStyles","containerTranslateX","transform","translateX","drawerTranslateX","closedDrawerOffset","drawerStyles","flexDirection","main","handleContainerLayout","containerOnBack","containerInFront","children","renderOverlay","drawerContainer","renderNavigationView","ref","onGestureRef","updateAnimatedEvent","UNSAFE_componentWillUpdate","render","setPanGestureRef","openingHandlerStateChange","enableTrackpadTwoFingerGesture","renderDrawer","Left","Right","StyleSheet","create","absoluteFillObject","zIndex","flex","overflow"],"mappings":";;;;;;;AAQA;;AAEA;;AACA;;AAkBA;;AAIA;;AAIA;;;;;;;;;;AAEA,MAAMA,SAAS,GAAG,IAAlB;AAEA,MAAMC,IAAiB,GAAG,MAA1B;AACA,MAAMC,QAAqB,GAAG,UAA9B;AACA,MAAMC,QAAqB,GAAG,UAA9B;;AAwHe,MAAMC,YAAN,SAA2BC,eAA3B,CAGb;AAaAC,EAAAA,WAAW,CAACC,MAAD,EAA2B;AACpC,UAAMA,MAAN;;AADoC;;AAAA;;AAAA,mEAmCHC,KAAK,CAACC,SAAN,EAnCG;;AAAA,4DA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D,EAAAA,cAAc,EAAE,MAFI;AAGpBwB,EAAAA,mBAAmB,EAAE,IAHD;AAIpBtB,EAAAA,UAAU,EAAE,OAJQ;AAKpBsE,EAAAA,SAAS,EAAE,EALS;AAMpBD,EAAAA,gBAAgB,EAAE,CANE;AAOpB+B,EAAAA,YAAY,EAAE,oBAPM;AAQpB/C,EAAAA,cAAc,EAAE,UARI;AASpBmF,EAAAA,8BAA8B,EAAE;AATZ,C;;gBAJHjJ,Y,eAwDA;AACjBmJ,EAAAA,IAAI,EAAE,MADW;AAEjBC,EAAAA,KAAK,EAAE;AAFU,C;;AAqcrB,MAAMrC,MAAM,GAAGsC,wBAAWC,MAAX,CAAkB;AAC/Bd,EAAAA,eAAe,EAAE,EACf,GAAGa,wBAAWE,kBADC;AAEfC,IAAAA,MAAM,EAAE,IAFO;AAGfvB,IAAAA,aAAa,EAAE;AAHA,GADc;AAM/BI,EAAAA,gBAAgB,EAAE,EAChB,GAAGgB,wBAAWE,kBADE;AAEhBC,IAAAA,MAAM,EAAE;AAFQ,GANa;AAU/BpB,EAAAA,eAAe,EAAE,EACf,GAAGiB,wBAAWE;AADC,GAVc;AAa/BrB,EAAAA,IAAI,EAAE;AACJuB,IAAAA,IAAI,EAAE,CADF;AAEJD,IAAAA,MAAM,EAAE,CAFJ;AAGJE,IAAAA,QAAQ,EAAE;AAHN,GAbyB;AAkB/B1C,EAAAA,OAAO,EAAE,EACP,GAAGqC,wBAAWE,kBADP;AAEPC,IAAAA,MAAM,EAAE;AAFD;AAlBsB,CAAlB,CAAf","sourcesContent":["// This component is based on RN's DrawerLayoutAndroid API\n//\n// It perhaps deserves to be put in a separate repo, but since it relies on\n// react-native-gesture-handler library which isn't very popular at the moment I\n// decided to keep it here for the time being. It will allow us to move faster\n// and fix issues that may arise in gesture handler library that could be found\n// when using the drawer component\n\nimport * as React from 'react';\nimport { Component } from 'react';\nimport invariant from 'invariant';\nimport {\n Animated,\n StyleSheet,\n View,\n Keyboard,\n StatusBar,\n I18nManager,\n StatusBarAnimation,\n StyleProp,\n ViewStyle,\n LayoutChangeEvent,\n NativeSyntheticEvent,\n} from 'react-native';\n\nimport {\n GestureEvent,\n HandlerStateChangeEvent,\n} from '../handlers/gestureHandlerCommon';\nimport {\n PanGestureHandler,\n PanGestureHandlerEventPayload,\n} from '../handlers/PanGestureHandler';\nimport {\n TapGestureHandler,\n TapGestureHandlerEventPayload,\n} from '../handlers/TapGestureHandler';\nimport { State } from '../State';\n\nconst DRAG_TOSS = 0.05;\n\nconst IDLE: DrawerState = 'Idle';\nconst DRAGGING: DrawerState = 'Dragging';\nconst SETTLING: DrawerState = 'Settling';\n\nexport type DrawerPosition = 'left' | 'right';\n\nexport type DrawerState = 'Idle' | 'Dragging' | 'Settling';\n\nexport type DrawerType = 'front' | 'back' | 'slide';\n\nexport type DrawerLockMode = 'unlocked' | 'locked-closed' | 'locked-open';\n\nexport type DrawerKeyboardDismissMode = 'none' | 'on-drag';\n\nexport interface DrawerLayoutProps {\n /**\n * This attribute is present in the standard implementation already and is one\n * of the required params. Gesture handler version of DrawerLayout make it\n * possible for the function passed as `renderNavigationView` to take an\n * Animated value as a parameter that indicates the progress of drawer\n * opening/closing animation (progress value is 0 when closed and 1 when\n * opened). This can be used by the drawer component to animated its children\n * while the drawer is opening or closing.\n */\n renderNavigationView: (\n progressAnimatedValue: Animated.Value\n ) => React.ReactNode;\n\n drawerPosition?: DrawerPosition;\n\n drawerWidth?: number;\n\n drawerBackgroundColor?: string;\n\n drawerLockMode?: DrawerLockMode;\n\n keyboardDismissMode?: DrawerKeyboardDismissMode;\n\n /**\n * Called when the drawer is closed.\n */\n onDrawerClose?: () => void;\n\n /**\n * Called when the drawer is opened.\n */\n onDrawerOpen?: () => void;\n\n /**\n * Called when the status of the drawer changes.\n */\n onDrawerStateChanged?: (\n newState: DrawerState,\n drawerWillShow: boolean\n ) => void;\n useNativeAnimations?: boolean;\n\n drawerType?: DrawerType;\n\n /**\n * Defines how far from the edge of the content view the gesture should\n * activate.\n */\n edgeWidth?: number;\n\n minSwipeDistance?: number;\n\n /**\n * When set to true Drawer component will use\n * {@link https://reactnative.dev/docs/statusbar StatusBar} API to hide the OS\n * status bar whenever the drawer is pulled or when its in an \"open\" state.\n */\n hideStatusBar?: boolean;\n\n /**\n * @default 'slide'\n *\n * Can be used when hideStatusBar is set to true and will select the animation\n * used for hiding/showing the status bar. See\n * {@link https://reactnative.dev/docs/statusbar StatusBar} documentation for\n * more details\n */\n statusBarAnimation?: StatusBarAnimation;\n\n /**\n * @default black\n *\n * Color of a semi-transparent overlay to be displayed on top of the content\n * view when drawer gets open. A solid color should be used as the opacity is\n * added by the Drawer itself and the opacity of the overlay is animated (from\n * 0% to 70%).\n */\n overlayColor?: string;\n\n contentContainerStyle?: StyleProp;\n\n drawerContainerStyle?: StyleProp;\n\n /**\n * Enables two-finger gestures on supported devices, for example iPads with\n * trackpads. If not enabled the gesture will require click + drag, with\n * `enableTrackpadTwoFingerGesture` swiping with two fingers will also trigger\n * the gesture.\n */\n enableTrackpadTwoFingerGesture?: boolean;\n\n onDrawerSlide?: (position: number) => void;\n\n onGestureRef?: (ref: PanGestureHandler) => void;\n}\n\nexport type DrawerLayoutState = {\n dragX: Animated.Value;\n touchX: Animated.Value;\n drawerTranslation: Animated.Value;\n containerWidth: number;\n};\n\nexport type DrawerMovementOption = {\n velocity?: number;\n speed?: number;\n};\nexport default class DrawerLayout extends Component<\n DrawerLayoutProps,\n DrawerLayoutState\n> {\n static defaultProps = {\n drawerWidth: 200,\n drawerPosition: 'left',\n useNativeAnimations: true,\n drawerType: 'front',\n edgeWidth: 20,\n minSwipeDistance: 3,\n overlayColor: 'rgba(0, 0, 0, 0.7)',\n drawerLockMode: 'unlocked',\n enableTrackpadTwoFingerGesture: false,\n };\n\n constructor(props: DrawerLayoutProps) {\n super(props);\n\n const dragX = new Animated.Value(0);\n const touchX = new Animated.Value(0);\n const drawerTranslation = new Animated.Value(0);\n\n this.state = {\n dragX,\n touchX,\n drawerTranslation,\n containerWidth: 0,\n };\n\n this.updateAnimatedEvent(props, this.state);\n }\n\n UNSAFE_componentWillUpdate(\n props: DrawerLayoutProps,\n state: DrawerLayoutState\n ) {\n if (\n this.props.drawerPosition !== props.drawerPosition ||\n this.props.drawerWidth !== props.drawerWidth ||\n this.props.drawerType !== props.drawerType ||\n this.state.containerWidth !== state.containerWidth\n ) {\n this.updateAnimatedEvent(props, state);\n }\n }\n\n private openValue?: Animated.AnimatedInterpolation;\n private onGestureEvent?: (\n event: GestureEvent\n ) => void;\n private accessibilityIsModalView = React.createRef();\n private pointerEventsView = React.createRef();\n private panGestureHandler = React.createRef();\n private drawerShown = false;\n\n static positions = {\n Left: 'left',\n Right: 'right',\n };\n\n private updateAnimatedEvent = (\n props: DrawerLayoutProps,\n state: DrawerLayoutState\n ) => {\n // Event definition is based on\n const { drawerPosition, drawerWidth, drawerType } = props;\n const {\n dragX: dragXValue,\n touchX: touchXValue,\n drawerTranslation,\n containerWidth,\n } = state;\n\n let dragX = dragXValue;\n let touchX = touchXValue;\n\n if (drawerPosition !== 'left') {\n // Most of the code is written in a way to handle left-side drawer. In\n // order to handle right-side drawer the only thing we need to do is to\n // reverse events coming from gesture handler in a way they emulate\n // left-side drawer gestures. E.g. dragX is simply -dragX, and touchX is\n // calulcated by subtracing real touchX from the width of the container\n // (such that when touch happens at the right edge the value is simply 0)\n dragX = Animated.multiply(\n new Animated.Value(-1),\n dragXValue\n ) as Animated.Value; // TODO(TS): (for all \"as\" in this file) make sure we can map this\n touchX = Animated.add(\n new Animated.Value(containerWidth),\n Animated.multiply(new Animated.Value(-1), touchXValue)\n ) as Animated.Value; // TODO(TS): make sure we can map this;\n touchXValue.setValue(containerWidth);\n } else {\n touchXValue.setValue(0);\n }\n\n // While closing the drawer when user starts gesture outside of its area (in greyed\n // out part of the window), we want the drawer to follow only once finger reaches the\n // edge of the drawer.\n // E.g. on the diagram below drawer is illustrate by X signs and the greyed out area by\n // dots. The touch gesture starts at '*' and moves left, touch path is indicated by\n // an arrow pointing left\n // 1) +---------------+ 2) +---------------+ 3) +---------------+ 4) +---------------+\n // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|\n // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|\n // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|\n // |XXXXXXXX|......| |XXXXXXXX|.<-*..| |XXXXXXXX|<--*..| |XXXXX|<-----*..|\n // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|\n // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|\n // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|\n // +---------------+ +---------------+ +---------------+ +---------------+\n //\n // For the above to work properly we define animated value that will keep\n // start position of the gesture. Then we use that value to calculate how\n // much we need to subtract from the dragX. If the gesture started on the\n // greyed out area we take the distance from the edge of the drawer to the\n // start position. Otherwise we don't subtract at all and the drawer be\n // pulled back as soon as you start the pan.\n //\n // This is used only when drawerType is \"front\"\n //\n let translationX = dragX;\n if (drawerType === 'front') {\n const startPositionX = Animated.add(\n touchX,\n Animated.multiply(new Animated.Value(-1), dragX)\n );\n\n const dragOffsetFromOnStartPosition = startPositionX.interpolate({\n inputRange: [drawerWidth! - 1, drawerWidth!, drawerWidth! + 1],\n outputRange: [0, 0, 1],\n });\n translationX = Animated.add(\n dragX,\n dragOffsetFromOnStartPosition\n ) as Animated.Value; // TODO: as above\n }\n\n this.openValue = Animated.add(translationX, drawerTranslation).interpolate({\n inputRange: [0, drawerWidth!],\n outputRange: [0, 1],\n extrapolate: 'clamp',\n });\n\n const gestureOptions: {\n useNativeDriver: boolean;\n // TODO: make sure it is correct\n listener?: (\n ev: NativeSyntheticEvent\n ) => void;\n } = {\n useNativeDriver: props.useNativeAnimations!,\n };\n\n if (this.props.onDrawerSlide) {\n gestureOptions.listener = (ev) => {\n const translationX = Math.floor(Math.abs(ev.nativeEvent.translationX));\n const position = translationX / this.state.containerWidth;\n\n this.props.onDrawerSlide?.(position);\n };\n }\n\n this.onGestureEvent = Animated.event(\n [{ nativeEvent: { translationX: dragXValue, x: touchXValue } }],\n gestureOptions\n );\n };\n\n private handleContainerLayout = ({ nativeEvent }: LayoutChangeEvent) => {\n this.setState({ containerWidth: nativeEvent.layout.width });\n };\n\n private emitStateChanged = (\n newState: DrawerState,\n drawerWillShow: boolean\n ) => {\n this.props.onDrawerStateChanged?.(newState, drawerWillShow);\n };\n\n private openingHandlerStateChange = ({\n nativeEvent,\n }: HandlerStateChangeEvent) => {\n if (nativeEvent.oldState === State.ACTIVE) {\n this.handleRelease({ nativeEvent });\n } else if (nativeEvent.state === State.ACTIVE) {\n this.emitStateChanged(DRAGGING, false);\n if (this.props.keyboardDismissMode === 'on-drag') {\n Keyboard.dismiss();\n }\n if (this.props.hideStatusBar) {\n StatusBar.setHidden(true, this.props.statusBarAnimation || 'slide');\n }\n }\n };\n\n private onTapHandlerStateChange = ({\n nativeEvent,\n }: HandlerStateChangeEvent) => {\n if (\n this.drawerShown &&\n nativeEvent.oldState === State.ACTIVE &&\n this.props.drawerLockMode !== 'locked-open'\n ) {\n this.closeDrawer();\n }\n };\n\n private handleRelease = ({\n nativeEvent,\n }: HandlerStateChangeEvent) => {\n const { drawerWidth, drawerPosition, drawerType } = this.props;\n const { containerWidth } = this.state;\n let { translationX: dragX, velocityX, x: touchX } = nativeEvent;\n\n if (drawerPosition !== 'left') {\n // See description in _updateAnimatedEvent about why events are flipped\n // for right-side drawer\n dragX = -dragX;\n touchX = containerWidth - touchX;\n velocityX = -velocityX;\n }\n\n const gestureStartX = touchX - dragX;\n let dragOffsetBasedOnStart = 0;\n\n if (drawerType === 'front') {\n dragOffsetBasedOnStart =\n gestureStartX > drawerWidth! ? gestureStartX - drawerWidth! : 0;\n }\n\n const startOffsetX =\n dragX + dragOffsetBasedOnStart + (this.drawerShown ? drawerWidth! : 0);\n const projOffsetX = startOffsetX + DRAG_TOSS * velocityX;\n\n const shouldOpen = projOffsetX > drawerWidth! / 2;\n\n if (shouldOpen) {\n this.animateDrawer(startOffsetX, drawerWidth!, velocityX);\n } else {\n this.animateDrawer(startOffsetX, 0, velocityX);\n }\n };\n\n private updateShowing = (showing: boolean) => {\n this.drawerShown = showing;\n this.accessibilityIsModalView.current?.setNativeProps({\n accessibilityViewIsModal: showing,\n });\n this.pointerEventsView.current?.setNativeProps({\n pointerEvents: showing ? 'auto' : 'none',\n });\n const { drawerPosition, minSwipeDistance, edgeWidth } = this.props;\n const fromLeft = drawerPosition === 'left';\n // gestureOrientation is 1 if the expected gesture is from left to right and\n // -1 otherwise e.g. when drawer is on the left and is closed we expect left\n // to right gesture, thus orientation will be 1.\n const gestureOrientation =\n (fromLeft ? 1 : -1) * (this.drawerShown ? -1 : 1);\n // When drawer is closed we want the hitSlop to be horizontally shorter than\n // the container size by the value of SLOP. This will make it only activate\n // when gesture happens not further than SLOP away from the edge\n const hitSlop = fromLeft\n ? { left: 0, width: showing ? undefined : edgeWidth }\n : { right: 0, width: showing ? undefined : edgeWidth };\n // @ts-ignore internal API, maybe could be fixed in handler types\n this.panGestureHandler.current?.setNativeProps({\n hitSlop,\n activeOffsetX: gestureOrientation * minSwipeDistance!,\n });\n };\n\n private animateDrawer = (\n fromValue: number | null | undefined,\n toValue: number,\n velocity: number,\n speed?: number\n ) => {\n this.state.dragX.setValue(0);\n this.state.touchX.setValue(\n this.props.drawerPosition === 'left' ? 0 : this.state.containerWidth\n );\n\n if (fromValue != null) {\n let nextFramePosition = fromValue;\n if (this.props.useNativeAnimations) {\n // When using native driver, we predict the next position of the\n // animation because it takes one frame of a roundtrip to pass RELEASE\n // event from native driver to JS before we can start animating. Without\n // it, it is more noticable that the frame is dropped.\n if (fromValue < toValue && velocity > 0) {\n nextFramePosition = Math.min(fromValue + velocity / 60.0, toValue);\n } else if (fromValue > toValue && velocity < 0) {\n nextFramePosition = Math.max(fromValue + velocity / 60.0, toValue);\n }\n }\n this.state.drawerTranslation.setValue(nextFramePosition);\n }\n\n const willShow = toValue !== 0;\n this.updateShowing(willShow);\n this.emitStateChanged(SETTLING, willShow);\n if (this.props.hideStatusBar) {\n StatusBar.setHidden(willShow, this.props.statusBarAnimation || 'slide');\n }\n Animated.spring(this.state.drawerTranslation, {\n velocity,\n bounciness: 0,\n toValue,\n useNativeDriver: this.props.useNativeAnimations!,\n speed: speed ?? undefined,\n }).start(({ finished }) => {\n if (finished) {\n this.emitStateChanged(IDLE, willShow);\n if (willShow) {\n this.props.onDrawerOpen?.();\n } else {\n this.props.onDrawerClose?.();\n }\n }\n });\n };\n\n openDrawer = (options: DrawerMovementOption = {}) => {\n this.animateDrawer(\n // TODO: decide if it should be null or undefined is the proper value\n undefined,\n this.props.drawerWidth!,\n options.velocity ? options.velocity : 0\n );\n\n // We need to force the update, otherwise the overlay is not rerendered and\n // it would not be clickable\n this.forceUpdate();\n };\n\n closeDrawer = (options: DrawerMovementOption = {}) => {\n // TODO: decide if it should be null or undefined is the proper value\n this.animateDrawer(undefined, 0, options.velocity ? options.velocity : 0);\n\n // We need to force the update, otherwise the overlay is not rerendered and\n // it would be still clickable\n this.forceUpdate();\n };\n\n private renderOverlay = () => {\n /* Overlay styles */\n invariant(this.openValue, 'should be set');\n const overlayOpacity = this.openValue.interpolate({\n inputRange: [0, 1],\n outputRange: [0, 1],\n extrapolate: 'clamp',\n });\n const dynamicOverlayStyles = {\n opacity: overlayOpacity,\n backgroundColor: this.props.overlayColor,\n };\n\n return (\n \n \n \n );\n };\n\n private renderDrawer = () => {\n const {\n drawerBackgroundColor,\n drawerWidth,\n drawerPosition,\n drawerType,\n drawerContainerStyle,\n contentContainerStyle,\n } = this.props;\n\n const fromLeft = drawerPosition === 'left';\n const drawerSlide = drawerType !== 'back';\n const containerSlide = drawerType !== 'front';\n\n // we rely on row and row-reverse flex directions to position the drawer\n // properly. Apparently for RTL these are flipped which requires us to use\n // the opposite setting for the drawer to appear from left or right\n // according to the drawerPosition prop\n const reverseContentDirection = I18nManager.isRTL ? fromLeft : !fromLeft;\n\n const dynamicDrawerStyles = {\n backgroundColor: drawerBackgroundColor,\n width: drawerWidth,\n };\n const openValue = this.openValue;\n invariant(openValue, 'should be set');\n\n let containerStyles;\n if (containerSlide) {\n const containerTranslateX = openValue.interpolate({\n inputRange: [0, 1],\n outputRange: fromLeft ? [0, drawerWidth!] : [0, -drawerWidth!],\n extrapolate: 'clamp',\n });\n containerStyles = {\n transform: [{ translateX: containerTranslateX }],\n };\n }\n\n let drawerTranslateX: number | Animated.AnimatedInterpolation = 0;\n if (drawerSlide) {\n const closedDrawerOffset = fromLeft ? -drawerWidth! : drawerWidth!;\n drawerTranslateX = openValue.interpolate({\n inputRange: [0, 1],\n outputRange: [closedDrawerOffset, 0],\n extrapolate: 'clamp',\n });\n }\n const drawerStyles: {\n transform: { translateX: number | Animated.AnimatedInterpolation }[];\n flexDirection: 'row-reverse' | 'row';\n } = {\n transform: [{ translateX: drawerTranslateX }],\n flexDirection: reverseContentDirection ? 'row-reverse' : 'row',\n };\n\n return (\n \n \n {typeof this.props.children === 'function'\n ? this.props.children(this.openValue)\n : this.props.children}\n {this.renderOverlay()}\n \n \n \n {this.props.renderNavigationView(this.openValue as Animated.Value)}\n \n \n \n );\n };\n\n private setPanGestureRef = (ref: PanGestureHandler) => {\n // TODO(TS): make sure it is OK taken from\n // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31065#issuecomment-596081842\n (this\n .panGestureHandler as React.MutableRefObject).current = ref;\n this.props.onGestureRef?.(ref);\n };\n\n render() {\n const {\n drawerPosition,\n drawerLockMode,\n edgeWidth,\n minSwipeDistance,\n } = this.props;\n\n const fromLeft = drawerPosition === 'left';\n\n // gestureOrientation is 1 if the expected gesture is from left to right and\n // -1 otherwise e.g. when drawer is on the left and is closed we expect left\n // to right gesture, thus orientation will be 1.\n const gestureOrientation =\n (fromLeft ? 1 : -1) * (this.drawerShown ? -1 : 1);\n\n // When drawer is closed we want the hitSlop to be horizontally shorter than\n // the container size by the value of SLOP. This will make it only activate\n // when gesture happens not further than SLOP away from the edge\n const hitSlop = fromLeft\n ? { left: 0, width: this.drawerShown ? undefined : edgeWidth }\n : { right: 0, width: this.drawerShown ? undefined : edgeWidth };\n\n return (\n \n {this.renderDrawer()}\n \n );\n }\n}\n\nconst styles = StyleSheet.create({\n drawerContainer: {\n ...StyleSheet.absoluteFillObject,\n zIndex: 1001,\n flexDirection: 'row',\n },\n containerInFront: {\n ...StyleSheet.absoluteFillObject,\n zIndex: 1002,\n },\n containerOnBack: {\n ...StyleSheet.absoluteFillObject,\n },\n main: {\n flex: 1,\n zIndex: 0,\n overflow: 'hidden',\n },\n overlay: {\n ...StyleSheet.absoluteFillObject,\n zIndex: 1000,\n },\n});\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/GestureButtons.js b/lib/commonjs/components/GestureButtons.js new file mode 100644 index 0000000000..fa2cee9194 --- /dev/null +++ b/lib/commonjs/components/GestureButtons.js @@ -0,0 +1,207 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "PureNativeButton", { + enumerable: true, + get: function () { + return _GestureHandlerButton.default; + } +}); +exports.BorderlessButton = exports.RectButton = exports.BaseButton = exports.RawButton = void 0; + +var React = _interopRequireWildcard(require("react")); + +var _reactNative = require("react-native"); + +var _createNativeWrapper = _interopRequireDefault(require("../handlers/createNativeWrapper")); + +var _GestureHandlerButton = _interopRequireDefault(require("./GestureHandlerButton")); + +var _State = require("../State"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +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; } + +const RawButton = (0, _createNativeWrapper.default)(_GestureHandlerButton.default, { + shouldCancelWhenOutside: false, + shouldActivateOnStart: false +}); +exports.RawButton = RawButton; + +class BaseButton extends React.Component { + constructor(props) { + super(props); + + _defineProperty(this, "lastActive", void 0); + + _defineProperty(this, "handleEvent", ({ + nativeEvent + }) => { + const { + state, + oldState, + pointerInside + } = nativeEvent; + const active = pointerInside && state === _State.State.ACTIVE; + + if (active !== this.lastActive && this.props.onActiveStateChange) { + this.props.onActiveStateChange(active); + } + + if (oldState === _State.State.ACTIVE && state !== _State.State.CANCELLED && this.lastActive && this.props.onPress) { + this.props.onPress(active); + } + + this.lastActive = active; + }); + + _defineProperty(this, "onHandlerStateChange", e => { + var _this$props$onHandler, _this$props; + + (_this$props$onHandler = (_this$props = this.props).onHandlerStateChange) === null || _this$props$onHandler === void 0 ? void 0 : _this$props$onHandler.call(_this$props, e); + this.handleEvent(e); + }); + + _defineProperty(this, "onGestureEvent", e => { + var _this$props$onGesture, _this$props2; + + (_this$props$onGesture = (_this$props2 = this.props).onGestureEvent) === null || _this$props$onGesture === void 0 ? void 0 : _this$props$onGesture.call(_this$props2, e); + this.handleEvent(e); // TODO: maybe it is not correct + }); + + this.lastActive = false; + } + + render() { + const { + rippleColor, + ...rest + } = this.props; + return /*#__PURE__*/React.createElement(RawButton, _extends({ + rippleColor: (0, _reactNative.processColor)(rippleColor) + }, rest, { + onGestureEvent: this.onGestureEvent, + onHandlerStateChange: this.onHandlerStateChange + })); + } + +} + +exports.BaseButton = BaseButton; + +const AnimatedBaseButton = _reactNative.Animated.createAnimatedComponent(BaseButton); + +const btnStyles = _reactNative.StyleSheet.create({ + underlay: { + position: 'absolute', + left: 0, + right: 0, + bottom: 0, + top: 0 + } +}); + +class RectButton extends React.Component { + constructor(props) { + super(props); + + _defineProperty(this, "opacity", void 0); + + _defineProperty(this, "onActiveStateChange", active => { + var _this$props$onActiveS, _this$props3; + + if (_reactNative.Platform.OS !== 'android') { + this.opacity.setValue(active ? this.props.activeOpacity : 0); + } + + (_this$props$onActiveS = (_this$props3 = this.props).onActiveStateChange) === null || _this$props$onActiveS === void 0 ? void 0 : _this$props$onActiveS.call(_this$props3, active); + }); + + this.opacity = new _reactNative.Animated.Value(0); + } + + render() { + const { + children, + style, + ...rest + } = this.props; + + const resolvedStyle = _reactNative.StyleSheet.flatten(style !== null && style !== void 0 ? style : {}); + + return /*#__PURE__*/React.createElement(BaseButton, _extends({}, rest, { + style: resolvedStyle, + onActiveStateChange: this.onActiveStateChange + }), /*#__PURE__*/React.createElement(_reactNative.Animated.View, { + style: [btnStyles.underlay, { + opacity: this.opacity, + backgroundColor: this.props.underlayColor, + borderRadius: resolvedStyle.borderRadius, + borderTopLeftRadius: resolvedStyle.borderTopLeftRadius, + borderTopRightRadius: resolvedStyle.borderTopRightRadius, + borderBottomLeftRadius: resolvedStyle.borderBottomLeftRadius, + borderBottomRightRadius: resolvedStyle.borderBottomRightRadius + }] + }), children); + } + +} + +exports.RectButton = RectButton; + +_defineProperty(RectButton, "defaultProps", { + activeOpacity: 0.105, + underlayColor: 'black' +}); + +class BorderlessButton extends React.Component { + constructor(props) { + super(props); + + _defineProperty(this, "opacity", void 0); + + _defineProperty(this, "onActiveStateChange", active => { + var _this$props$onActiveS2, _this$props4; + + if (_reactNative.Platform.OS !== 'android') { + this.opacity.setValue(active ? this.props.activeOpacity : 1); + } + + (_this$props$onActiveS2 = (_this$props4 = this.props).onActiveStateChange) === null || _this$props$onActiveS2 === void 0 ? void 0 : _this$props$onActiveS2.call(_this$props4, active); + }); + + this.opacity = new _reactNative.Animated.Value(1); + } + + render() { + const { + children, + style, + ...rest + } = this.props; + return /*#__PURE__*/React.createElement(AnimatedBaseButton, _extends({}, rest, { + onActiveStateChange: this.onActiveStateChange, + style: [style, _reactNative.Platform.OS === 'ios' && { + opacity: this.opacity + }] + }), children); + } + +} + +exports.BorderlessButton = BorderlessButton; + +_defineProperty(BorderlessButton, "defaultProps", { + activeOpacity: 0.3, + borderless: true +}); +//# sourceMappingURL=GestureButtons.js.map \ No newline at end of file diff --git a/lib/commonjs/components/GestureButtons.js.map b/lib/commonjs/components/GestureButtons.js.map new file mode 100644 index 0000000000..3525ec413c --- /dev/null +++ b/lib/commonjs/components/GestureButtons.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureButtons.tsx"],"names":["RawButton","GestureHandlerButton","shouldCancelWhenOutside","shouldActivateOnStart","BaseButton","React","Component","constructor","props","nativeEvent","state","oldState","pointerInside","active","State","ACTIVE","lastActive","onActiveStateChange","CANCELLED","onPress","e","onHandlerStateChange","handleEvent","onGestureEvent","render","rippleColor","rest","AnimatedBaseButton","Animated","createAnimatedComponent","btnStyles","StyleSheet","create","underlay","position","left","right","bottom","top","RectButton","Platform","OS","opacity","setValue","activeOpacity","Value","children","style","resolvedStyle","flatten","backgroundColor","underlayColor","borderRadius","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius","BorderlessButton","borderless"],"mappings":";;;;;;;;;;;;;AAAA;;AACA;;AASA;;AACA;;AACA;;;;;;;;;;;;AA0EO,MAAMA,SAAS,GAAG,kCAAoBC,6BAApB,E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AAEA,wBACE,oBAAC,kBAAD,eACMkB,IADN;AAEE,MAAA,mBAAmB,EAAE,KAAKT,mBAF5B;AAGE,MAAA,KAAK,EAAE,CAAC8B,KAAD,EAAQP,sBAASC,EAAT,KAAgB,KAAhB,IAAyB;AAAEC,QAAAA,OAAO,EAAE,KAAKA;AAAhB,OAAjC;AAHT,QAIGI,QAJH,CADF;AAQD;;AAhC0E;;;;gBAAhEW,gB,kBACW;AACpBb,EAAAA,aAAa,EAAE,GADK;AAEpBc,EAAAA,UAAU,EAAE;AAFQ,C","sourcesContent":["import * as React from 'react';\nimport {\n Animated,\n Platform,\n processColor,\n StyleSheet,\n StyleProp,\n ViewStyle,\n} from 'react-native';\n\nimport createNativeWrapper from '../handlers/createNativeWrapper';\nimport GestureHandlerButton from './GestureHandlerButton';\nimport { State } from '../State';\n\nimport {\n GestureEvent,\n HandlerStateChangeEvent,\n} from '../handlers/gestureHandlerCommon';\nimport {\n NativeViewGestureHandlerPayload,\n NativeViewGestureHandlerProps,\n} from '../handlers/NativeViewGestureHandler';\n\nexport interface RawButtonProps extends NativeViewGestureHandlerProps {\n /**\n * Defines if more than one button could be pressed simultaneously. By default\n * set true.\n */\n exclusive?: boolean;\n // TODO: we should transform props in `createNativeWrapper`\n\n /**\n * Android only.\n *\n * Defines color of native ripple animation used since API level 21.\n */\n rippleColor?: any; // it was present in BaseButtonProps before but is used here in code\n}\n\nexport interface BaseButtonProps extends RawButtonProps {\n /**\n * Called when the button gets pressed (analogous to `onPress` in\n * `TouchableHighlight` from RN core).\n */\n onPress?: (pointerInside: boolean) => void;\n\n /**\n * Called when button changes from inactive to active and vice versa. It\n * passes active state as a boolean variable as a first parameter for that\n * method.\n */\n onActiveStateChange?: (active: boolean) => void;\n style?: StyleProp;\n testID?: string;\n}\n\nexport interface RectButtonProps extends BaseButtonProps {\n /**\n * Background color that will be dimmed when button is in active state.\n */\n underlayColor?: string;\n\n /**\n * iOS only.\n *\n * Opacity applied to the underlay when button is in active state.\n */\n activeOpacity?: number;\n}\n\nexport interface BorderlessButtonProps extends BaseButtonProps {\n /**\n * Android only.\n *\n * Set this to false if you want the ripple animation to render only within view bounds.\n */\n borderless?: boolean;\n\n /**\n * iOS only.\n *\n * Opacity applied to the button when it is in an active state.\n */\n activeOpacity?: number;\n}\n\nexport const RawButton = createNativeWrapper(GestureHandlerButton, {\n shouldCancelWhenOutside: false,\n shouldActivateOnStart: false,\n});\n\nexport class BaseButton extends React.Component {\n private lastActive: boolean;\n\n constructor(props: BaseButtonProps) {\n super(props);\n this.lastActive = false;\n }\n\n private handleEvent = ({\n nativeEvent,\n }: HandlerStateChangeEvent) => {\n const { state, oldState, pointerInside } = nativeEvent;\n const active = pointerInside && state === State.ACTIVE;\n\n if (active !== this.lastActive && this.props.onActiveStateChange) {\n this.props.onActiveStateChange(active);\n }\n\n if (\n oldState === State.ACTIVE &&\n state !== State.CANCELLED &&\n this.lastActive &&\n this.props.onPress\n ) {\n this.props.onPress(active);\n }\n\n this.lastActive = active;\n };\n\n // Normally, the parent would execute it's handler first, then forward the\n // event to listeners. However, here our handler is virtually only forwarding\n // events to listeners, so we reverse the order to keep the proper order of\n // the callbacks (from \"raw\" ones to \"processed\").\n private onHandlerStateChange = (\n e: HandlerStateChangeEvent\n ) => {\n this.props.onHandlerStateChange?.(e);\n this.handleEvent(e);\n };\n\n private onGestureEvent = (\n e: GestureEvent\n ) => {\n this.props.onGestureEvent?.(e);\n this.handleEvent(\n e as HandlerStateChangeEvent\n ); // TODO: maybe it is not correct\n };\n\n render() {\n const { rippleColor, ...rest } = this.props;\n\n return (\n \n );\n }\n}\n\nconst AnimatedBaseButton = Animated.createAnimatedComponent(BaseButton);\n\nconst btnStyles = StyleSheet.create({\n underlay: {\n position: 'absolute',\n left: 0,\n right: 0,\n bottom: 0,\n top: 0,\n },\n});\n\nexport class RectButton extends React.Component {\n static defaultProps = {\n activeOpacity: 0.105,\n underlayColor: 'black',\n };\n\n private opacity: Animated.Value;\n\n constructor(props: RectButtonProps) {\n super(props);\n this.opacity = new Animated.Value(0);\n }\n\n private onActiveStateChange = (active: boolean) => {\n if (Platform.OS !== 'android') {\n this.opacity.setValue(active ? this.props.activeOpacity! : 0);\n }\n\n this.props.onActiveStateChange?.(active);\n };\n\n render() {\n const { children, style, ...rest } = this.props;\n\n const resolvedStyle = StyleSheet.flatten(style ?? {});\n\n return (\n \n \n {children}\n \n );\n }\n}\n\nexport class BorderlessButton extends React.Component {\n static defaultProps = {\n activeOpacity: 0.3,\n borderless: true,\n };\n\n private opacity: Animated.Value;\n\n constructor(props: BorderlessButtonProps) {\n super(props);\n this.opacity = new Animated.Value(1);\n }\n\n private onActiveStateChange = (active: boolean) => {\n if (Platform.OS !== 'android') {\n this.opacity.setValue(active ? this.props.activeOpacity! : 1);\n }\n\n this.props.onActiveStateChange?.(active);\n };\n\n render() {\n const { children, style, ...rest } = this.props;\n\n return (\n \n {children}\n \n );\n }\n}\n\nexport { default as PureNativeButton } from './GestureHandlerButton';\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/GestureComponents.js b/lib/commonjs/components/GestureComponents.js new file mode 100644 index 0000000000..dc8e6391d6 --- /dev/null +++ b/lib/commonjs/components/GestureComponents.js @@ -0,0 +1,76 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FlatList = exports.DrawerLayoutAndroid = exports.TextInput = exports.Switch = exports.ScrollView = void 0; + +var React = _interopRequireWildcard(require("react")); + +var _reactNative = require("react-native"); + +var _createNativeWrapper = _interopRequireDefault(require("../handlers/createNativeWrapper")); + +var _NativeViewGestureHandler = require("../handlers/NativeViewGestureHandler"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +const ScrollView = (0, _createNativeWrapper.default)(_reactNative.ScrollView, { + disallowInterruption: true, + shouldCancelWhenOutside: false +}); // backward type compatibility with https://github.com/software-mansion/react-native-gesture-handler/blob/db78d3ca7d48e8ba57482d3fe9b0a15aa79d9932/react-native-gesture-handler.d.ts#L440-L457 +// include methods of wrapped components by creating an intersection type with the RN component instead of duplicating them. +// eslint-disable-next-line @typescript-eslint/no-redeclare + +exports.ScrollView = ScrollView; +const Switch = (0, _createNativeWrapper.default)(_reactNative.Switch, { + shouldCancelWhenOutside: false, + shouldActivateOnStart: true, + disallowInterruption: true +}); // eslint-disable-next-line @typescript-eslint/no-redeclare + +exports.Switch = Switch; +const TextInput = (0, _createNativeWrapper.default)(_reactNative.TextInput); // eslint-disable-next-line @typescript-eslint/no-redeclare + +exports.TextInput = TextInput; +const DrawerLayoutAndroid = (0, _createNativeWrapper.default)(_reactNative.DrawerLayoutAndroid, { + disallowInterruption: true +}); // eslint-disable-next-line @typescript-eslint/no-redeclare + +exports.DrawerLayoutAndroid = DrawerLayoutAndroid; +const FlatList = /*#__PURE__*/React.forwardRef((props, ref) => { + const flatListProps = {}; + const scrollViewProps = {}; + + for (const [propName, value] of Object.entries(props)) { + // https://github.com/microsoft/TypeScript/issues/26255 + if (_NativeViewGestureHandler.nativeViewProps.includes(propName)) { + // @ts-ignore - this function cannot have generic type so we have to ignore this error + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + scrollViewProps[propName] = value; + } else { + // @ts-ignore - this function cannot have generic type so we have to ignore this error + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + flatListProps[propName] = value; + } + } + + return ( + /*#__PURE__*/ + // @ts-ignore - this function cannot have generic type so we have to ignore this error + React.createElement(_reactNative.FlatList, _extends({ + ref: ref + }, flatListProps, { + renderScrollComponent: scrollProps => /*#__PURE__*/React.createElement(ScrollView, _extends({}, scrollProps, scrollViewProps)) + })) + ); +}); // eslint-disable-next-line @typescript-eslint/no-redeclare + +exports.FlatList = FlatList; +//# sourceMappingURL=GestureComponents.js.map \ No newline at end of file diff --git a/lib/commonjs/components/GestureComponents.js.map b/lib/commonjs/components/GestureComponents.js.map new file mode 100644 index 0000000000..f19ae1b994 --- /dev/null +++ b/lib/commonjs/components/GestureComponents.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureComponents.tsx"],"names":["ScrollView","RNScrollView","disallowInterruption","shouldCancelWhenOutside","Switch","RNSwitch","shouldActivateOnStart","TextInput","RNTextInput","DrawerLayoutAndroid","RNDrawerLayoutAndroid","FlatList","React","forwardRef","props","ref","flatListProps","scrollViewProps","propName","value","Object","entries","nativeViewProps","includes","scrollProps"],"mappings":";;;;;;;AAAA;;AAOA;;AAaA;;AAEA;;;;;;;;;;AAKO,MAAMA,UAAU,GAAG,kCAExBC,uBAFwB,EAEV;AACdC,EAAAA,oBAAoB,EAAE,IADR;AAEdC,EAAAA,uBAAuB,EAAE;AAFX,CAFU,CAAnB,C,CAMP;AACA;AACA;;;AAGO,MAAMC,MAAM,GAAG,kCAAmCC,mBAAnC,EAA6C;AACjEF,EAAAA,uBAAuB,EAAE,KADwC;AAEjEG,EAAAA,qBAAqB,EAAE,IAF0C;AAGjEJ,EAAAA,oBAAoB,EAAE;AAH2C,CAA7C,CAAf,C,CAKP;;;AAGO,MAAMK,SAAS,GAAG,kCAAsCC,sBAAtC,CAAlB,C,CACP;;;AAGO,MAAMC,mBAAmB,GAAG,kCAEjCC,gCAFiC,EAEV;AAAER,EAAAA,oBAAoB,EAAE;AAAxB,CAFU,CAA5B,C,CAGP;;;AAIO,MAAMS,QAAQ,gBAAGC,KAAK,CAACC,UAAN,CAAiB,CAACC,KAAD,EAAQC,GAAR,KAAgB;AACvD,QAAMC,aAAa,GAAG,EAAtB;AACA,QAAMC,eAAe,GAAG,EAAxB;;AACA,OAAK,MAAM,CAACC,QAAD,EAAWC,KAAX,CAAX,IAAgCC,MAAM,CAACC,OAAP,CAAeP,KAAf,CAAhC,EAAuD;AACrD;AACA,QAAKQ,yCAAD,CAAuCC,QAAvC,CAAgDL,QAAhD,CAAJ,EAA+D;AAC7D;AACA;AACAD,MAAAA,eAAe,CAACC,QAAD,CAAf,GAA4BC,KAA5B;AACD,KAJD,MAIO;AACL;AACA;AACAH,MAAAA,aAAa,CAACE,QAAD,CAAb,GAA0BC,KAA1B;AACD;AACF;;AACD;AAAA;AACE;AACA,wBAAC,qBAAD;AACE,MAAA,GAAG,EAAEJ;AADP,OAEMC,aAFN;AAGE,MAAA,qBAAqB,EAAGQ,WAAD,iBACrB,oBAAC,UAAD,eAAqBA,WAArB,EAAqCP,eAArC;AAJJ;AAFF;AAUD,CAzBuB,CAAjB,C,CAiCP","sourcesContent":["import * as React from 'react';\nimport {\n PropsWithChildren,\n ForwardedRef,\n RefAttributes,\n ReactElement,\n} from 'react';\nimport {\n ScrollView as RNScrollView,\n ScrollViewProps as RNScrollViewProps,\n Switch as RNSwitch,\n SwitchProps as RNSwitchProps,\n TextInput as RNTextInput,\n TextInputProps as RNTextInputProps,\n DrawerLayoutAndroid as RNDrawerLayoutAndroid,\n DrawerLayoutAndroidProps as RNDrawerLayoutAndroidProps,\n FlatList as RNFlatList,\n FlatListProps as RNFlatListProps,\n} from 'react-native';\n\nimport createNativeWrapper from '../handlers/createNativeWrapper';\n\nimport {\n NativeViewGestureHandlerProps,\n nativeViewProps,\n} from '../handlers/NativeViewGestureHandler';\n\nexport const ScrollView = createNativeWrapper<\n PropsWithChildren\n>(RNScrollView, {\n disallowInterruption: true,\n shouldCancelWhenOutside: false,\n});\n// backward type compatibility with https://github.com/software-mansion/react-native-gesture-handler/blob/db78d3ca7d48e8ba57482d3fe9b0a15aa79d9932/react-native-gesture-handler.d.ts#L440-L457\n// include methods of wrapped components by creating an intersection type with the RN component instead of duplicating them.\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type ScrollView = typeof ScrollView & RNScrollView;\n\nexport const Switch = createNativeWrapper(RNSwitch, {\n shouldCancelWhenOutside: false,\n shouldActivateOnStart: true,\n disallowInterruption: true,\n});\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type Switch = typeof Switch & RNSwitch;\n\nexport const TextInput = createNativeWrapper(RNTextInput);\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type TextInput = typeof TextInput & RNTextInput;\n\nexport const DrawerLayoutAndroid = createNativeWrapper<\n PropsWithChildren\n>(RNDrawerLayoutAndroid, { disallowInterruption: true });\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type DrawerLayoutAndroid = typeof DrawerLayoutAndroid &\n RNDrawerLayoutAndroid;\n\nexport const FlatList = React.forwardRef((props, ref) => {\n const flatListProps = {};\n const scrollViewProps = {};\n for (const [propName, value] of Object.entries(props)) {\n // https://github.com/microsoft/TypeScript/issues/26255\n if ((nativeViewProps as readonly string[]).includes(propName)) {\n // @ts-ignore - this function cannot have generic type so we have to ignore this error\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n scrollViewProps[propName] = value;\n } else {\n // @ts-ignore - this function cannot have generic type so we have to ignore this error\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n flatListProps[propName] = value;\n }\n }\n return (\n // @ts-ignore - this function cannot have generic type so we have to ignore this error\n (\n \n )}\n />\n );\n}) as (\n props: PropsWithChildren<\n RNFlatListProps &\n RefAttributes> &\n NativeViewGestureHandlerProps\n >,\n ref: ForwardedRef>\n) => ReactElement | null;\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type FlatList = typeof FlatList & RNFlatList;\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/GestureComponents.web.js b/lib/commonjs/components/GestureComponents.web.js new file mode 100644 index 0000000000..c6feace282 --- /dev/null +++ b/lib/commonjs/components/GestureComponents.web.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FlatList = exports.DrawerLayoutAndroid = exports.TextInput = exports.Switch = exports.ScrollView = void 0; + +var React = _interopRequireWildcard(require("react")); + +var _reactNative = require("react-native"); + +var _createNativeWrapper = _interopRequireDefault(require("../handlers/createNativeWrapper")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +const ScrollView = (0, _createNativeWrapper.default)(_reactNative.ScrollView, { + disallowInterruption: true +}); +exports.ScrollView = ScrollView; +const Switch = (0, _createNativeWrapper.default)(_reactNative.Switch, { + shouldCancelWhenOutside: false, + shouldActivateOnStart: true, + disallowInterruption: true +}); +exports.Switch = Switch; +const TextInput = (0, _createNativeWrapper.default)(_reactNative.TextInput); +exports.TextInput = TextInput; +const DrawerLayoutAndroid = (0, _createNativeWrapper.default)(_reactNative.DrawerLayoutAndroid, { + disallowInterruption: true +}); // @ts-ignore -- TODO(TS) to investigate if it's needed + +exports.DrawerLayoutAndroid = DrawerLayoutAndroid; +DrawerLayoutAndroid.positions = _reactNative.DrawerLayoutAndroid.positions; +const FlatList = /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/React.createElement(_reactNative.FlatList, _extends({ + ref: ref +}, props, { + renderScrollComponent: scrollProps => /*#__PURE__*/React.createElement(ScrollView, scrollProps) +}))); +exports.FlatList = FlatList; +//# sourceMappingURL=GestureComponents.web.js.map \ No newline at end of file diff --git a/lib/commonjs/components/GestureComponents.web.js.map b/lib/commonjs/components/GestureComponents.web.js.map new file mode 100644 index 0000000000..4c28bb21bb --- /dev/null +++ b/lib/commonjs/components/GestureComponents.web.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureComponents.web.tsx"],"names":["ScrollView","RNScrollView","disallowInterruption","Switch","RNSwitch","shouldCancelWhenOutside","shouldActivateOnStart","TextInput","RNTextInput","DrawerLayoutAndroid","RNDrawerLayoutAndroid","positions","FlatList","React","forwardRef","props","ref","scrollProps"],"mappings":";;;;;;;AAAA;;AACA;;AASA;;;;;;;;;;AAEO,MAAMA,UAAU,GAAG,kCAAoBC,uBAApB,EAAkC;AAC1DC,EAAAA,oBAAoB,EAAE;AADoC,CAAlC,CAAnB;;AAIA,MAAMC,MAAM,GAAG,kCAAoBC,mBAApB,EAA8B;AAClDC,EAAAA,uBAAuB,EAAE,KADyB;AAElDC,EAAAA,qBAAqB,EAAE,IAF2B;AAGlDJ,EAAAA,oBAAoB,EAAE;AAH4B,CAA9B,CAAf;;AAKA,MAAMK,SAAS,GAAG,kCAAoBC,sBAApB,CAAlB;;AACA,MAAMC,mBAAmB,GAAG,kCAAoBC,gCAApB,EAA2C;AAC5ER,EAAAA,oBAAoB,EAAE;AADsD,CAA3C,CAA5B,C,CAGP;;;AACAO,mBAAmB,CAACE,SAApB,GAAgCD,iCAAsBC,SAAtD;AAEO,MAAMC,QAAQ,gBAAGC,KAAK,CAACC,UAAN,CACtB,CAAoBC,KAApB,EAAiDC,GAAjD,kBACE,oBAAC,qBAAD;AACE,EAAA,GAAG,EAAEA;AADP,GAEMD,KAFN;AAGE,EAAA,qBAAqB,EAAGE,WAAD,iBAAiB,oBAAC,UAAD,EAAgBA,WAAhB;AAH1C,GAFoB,CAAjB","sourcesContent":["import * as React from 'react';\nimport {\n DrawerLayoutAndroid as RNDrawerLayoutAndroid,\n FlatList as RNFlatList,\n Switch as RNSwitch,\n TextInput as RNTextInput,\n ScrollView as RNScrollView,\n FlatListProps,\n} from 'react-native';\n\nimport createNativeWrapper from '../handlers/createNativeWrapper';\n\nexport const ScrollView = createNativeWrapper(RNScrollView, {\n disallowInterruption: true,\n});\n\nexport const Switch = createNativeWrapper(RNSwitch, {\n shouldCancelWhenOutside: false,\n shouldActivateOnStart: true,\n disallowInterruption: true,\n});\nexport const TextInput = createNativeWrapper(RNTextInput);\nexport const DrawerLayoutAndroid = createNativeWrapper(RNDrawerLayoutAndroid, {\n disallowInterruption: true,\n});\n// @ts-ignore -- TODO(TS) to investigate if it's needed\nDrawerLayoutAndroid.positions = RNDrawerLayoutAndroid.positions;\n\nexport const FlatList = React.forwardRef(\n (props: FlatListProps, ref: any) => (\n }\n />\n )\n);\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/GestureHandlerButton.js b/lib/commonjs/components/GestureHandlerButton.js new file mode 100644 index 0000000000..623d71d361 --- /dev/null +++ b/lib/commonjs/components/GestureHandlerButton.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _reactNative = require("react-native"); + +const RNGestureHandlerButton = (0, _reactNative.requireNativeComponent)('RNGestureHandlerButton'); +var _default = RNGestureHandlerButton; +exports.default = _default; +//# sourceMappingURL=GestureHandlerButton.js.map \ No newline at end of file diff --git a/lib/commonjs/components/GestureHandlerButton.js.map b/lib/commonjs/components/GestureHandlerButton.js.map new file mode 100644 index 0000000000..05c90ff121 --- /dev/null +++ b/lib/commonjs/components/GestureHandlerButton.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureHandlerButton.tsx"],"names":["RNGestureHandlerButton"],"mappings":";;;;;;;AAAA;;AAEA,MAAMA,sBAAqD,GAAG,yCAC5D,wBAD4D,CAA9D;eAIeA,sB","sourcesContent":["import { HostComponent, requireNativeComponent } from 'react-native';\nimport { RawButtonProps } from './GestureButtons';\nconst RNGestureHandlerButton: HostComponent = requireNativeComponent(\n 'RNGestureHandlerButton'\n);\n\nexport default RNGestureHandlerButton;\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/GestureHandlerButton.web.js b/lib/commonjs/components/GestureHandlerButton.web.js new file mode 100644 index 0000000000..d26da0d581 --- /dev/null +++ b/lib/commonjs/components/GestureHandlerButton.web.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var React = _interopRequireWildcard(require("react")); + +var _reactNative = require("react-native"); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +var _default = /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/React.createElement(_reactNative.View, _extends({ + ref: ref, + accessibilityRole: "button" +}, props))); + +exports.default = _default; +//# sourceMappingURL=GestureHandlerButton.web.js.map \ No newline at end of file diff --git a/lib/commonjs/components/GestureHandlerButton.web.js.map b/lib/commonjs/components/GestureHandlerButton.web.js.map new file mode 100644 index 0000000000..920df0c401 --- /dev/null +++ b/lib/commonjs/components/GestureHandlerButton.web.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureHandlerButton.web.tsx"],"names":["React","forwardRef","props","ref"],"mappings":";;;;;;;AAAA;;AACA;;;;;;;;4BAEeA,KAAK,CAACC,UAAN,CAAuB,CAACC,KAAD,EAAQC,GAAR,kBACpC,oBAAC,iBAAD;AAAM,EAAA,GAAG,EAAEA,GAAX;AAAgB,EAAA,iBAAiB,EAAC;AAAlC,GAA+CD,KAA/C,EADa,C","sourcesContent":["import * as React from 'react';\nimport { View } from 'react-native';\n\nexport default React.forwardRef((props, ref) => (\n \n));\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/Swipeable.js b/lib/commonjs/components/Swipeable.js new file mode 100644 index 0000000000..90027931ef --- /dev/null +++ b/lib/commonjs/components/Swipeable.js @@ -0,0 +1,365 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var React = _interopRequireWildcard(require("react")); + +var _reactNative = require("react-native"); + +var _PanGestureHandler = require("../handlers/PanGestureHandler"); + +var _TapGestureHandler = require("../handlers/TapGestureHandler"); + +var _State = require("../State"); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +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; } + +const DRAG_TOSS = 0.05; + +class Swipeable extends React.Component { + constructor(_props) { + super(_props); + + _defineProperty(this, "onGestureEvent", void 0); + + _defineProperty(this, "transX", void 0); + + _defineProperty(this, "showLeftAction", void 0); + + _defineProperty(this, "leftActionTranslate", void 0); + + _defineProperty(this, "showRightAction", void 0); + + _defineProperty(this, "rightActionTranslate", void 0); + + _defineProperty(this, "updateAnimatedEvent", (props, state) => { + const { + friction, + overshootFriction + } = props; + const { + dragX, + rowTranslation, + leftWidth = 0, + rowWidth = 0 + } = state; + const { + rightOffset = rowWidth + } = state; + const rightWidth = Math.max(0, rowWidth - rightOffset); + const { + overshootLeft = leftWidth > 0, + overshootRight = rightWidth > 0 + } = props; + + const transX = _reactNative.Animated.add(rowTranslation, dragX.interpolate({ + inputRange: [0, friction], + outputRange: [0, 1] + })).interpolate({ + inputRange: [-rightWidth - 1, -rightWidth, leftWidth, leftWidth + 1], + outputRange: [-rightWidth - (overshootRight ? 1 / overshootFriction : 0), -rightWidth, leftWidth, leftWidth + (overshootLeft ? 1 / overshootFriction : 0)] + }); + + this.transX = transX; + this.showLeftAction = leftWidth > 0 ? transX.interpolate({ + inputRange: [-1, 0, leftWidth], + outputRange: [0, 0, 1] + }) : new _reactNative.Animated.Value(0); + this.leftActionTranslate = this.showLeftAction.interpolate({ + inputRange: [0, Number.MIN_VALUE], + outputRange: [-10000, 0], + extrapolate: 'clamp' + }); + this.showRightAction = rightWidth > 0 ? transX.interpolate({ + inputRange: [-rightWidth, 0, 1], + outputRange: [1, 0, 0] + }) : new _reactNative.Animated.Value(0); + this.rightActionTranslate = this.showRightAction.interpolate({ + inputRange: [0, Number.MIN_VALUE], + outputRange: [-10000, 0], + extrapolate: 'clamp' + }); + }); + + _defineProperty(this, "onTapHandlerStateChange", ({ + nativeEvent + }) => { + if (nativeEvent.oldState === _State.State.ACTIVE) { + this.close(); + } + }); + + _defineProperty(this, "onHandlerStateChange", ev => { + if (ev.nativeEvent.oldState === _State.State.ACTIVE) { + this.handleRelease(ev); + } + }); + + _defineProperty(this, "handleRelease", ev => { + const { + velocityX, + translationX: dragX + } = ev.nativeEvent; + const { + leftWidth = 0, + rowWidth = 0, + rowState + } = this.state; + const { + rightOffset = rowWidth + } = this.state; + const rightWidth = rowWidth - rightOffset; + const { + friction, + leftThreshold = leftWidth / 2, + rightThreshold = rightWidth / 2 + } = this.props; + const startOffsetX = this.currentOffset() + dragX / friction; + const translationX = (dragX + DRAG_TOSS * velocityX) / friction; + let toValue = 0; + + if (rowState === 0) { + if (translationX > leftThreshold) { + toValue = leftWidth; + } else if (translationX < -rightThreshold) { + toValue = -rightWidth; + } + } else if (rowState === 1) { + // swiped to left + if (translationX > -leftThreshold) { + toValue = leftWidth; + } + } else { + // swiped to right + if (translationX < rightThreshold) { + toValue = -rightWidth; + } + } + + this.animateRow(startOffsetX, toValue, velocityX / friction); + }); + + _defineProperty(this, "animateRow", (fromValue, toValue, velocityX) => { + const { + dragX, + rowTranslation + } = this.state; + dragX.setValue(0); + rowTranslation.setValue(fromValue); + this.setState({ + rowState: Math.sign(toValue) + }); + + _reactNative.Animated.spring(rowTranslation, { + restSpeedThreshold: 1.7, + restDisplacementThreshold: 0.4, + velocity: velocityX, + bounciness: 0, + toValue, + useNativeDriver: this.props.useNativeAnimations, + ...this.props.animationOptions + }).start(({ + finished + }) => { + if (finished) { + if (toValue > 0 && this.props.onSwipeableLeftOpen) { + this.props.onSwipeableLeftOpen(); + } else if (toValue < 0 && this.props.onSwipeableRightOpen) { + this.props.onSwipeableRightOpen(); + } + + if (toValue === 0) { + var _this$props$onSwipeab, _this$props; + + (_this$props$onSwipeab = (_this$props = this.props).onSwipeableClose) === null || _this$props$onSwipeab === void 0 ? void 0 : _this$props$onSwipeab.call(_this$props); + } else { + var _this$props$onSwipeab2, _this$props2; + + (_this$props$onSwipeab2 = (_this$props2 = this.props).onSwipeableOpen) === null || _this$props$onSwipeab2 === void 0 ? void 0 : _this$props$onSwipeab2.call(_this$props2); + } + } + }); + + if (toValue > 0 && this.props.onSwipeableLeftWillOpen) { + this.props.onSwipeableLeftWillOpen(); + } else if (toValue < 0 && this.props.onSwipeableRightWillOpen) { + this.props.onSwipeableRightWillOpen(); + } + + if (toValue === 0) { + var _this$props$onSwipeab3, _this$props3; + + (_this$props$onSwipeab3 = (_this$props3 = this.props).onSwipeableWillClose) === null || _this$props$onSwipeab3 === void 0 ? void 0 : _this$props$onSwipeab3.call(_this$props3); + } else { + var _this$props$onSwipeab4, _this$props4; + + (_this$props$onSwipeab4 = (_this$props4 = this.props).onSwipeableWillOpen) === null || _this$props$onSwipeab4 === void 0 ? void 0 : _this$props$onSwipeab4.call(_this$props4); + } + }); + + _defineProperty(this, "onRowLayout", ({ + nativeEvent + }) => { + this.setState({ + rowWidth: nativeEvent.layout.width + }); + }); + + _defineProperty(this, "currentOffset", () => { + const { + leftWidth = 0, + rowWidth = 0, + rowState + } = this.state; + const { + rightOffset = rowWidth + } = this.state; + const rightWidth = rowWidth - rightOffset; + + if (rowState === 1) { + return leftWidth; + } else if (rowState === -1) { + return -rightWidth; + } + + return 0; + }); + + _defineProperty(this, "close", () => { + this.animateRow(this.currentOffset(), 0); + }); + + _defineProperty(this, "openLeft", () => { + const { + leftWidth = 0 + } = this.state; + this.animateRow(this.currentOffset(), leftWidth); + }); + + _defineProperty(this, "openRight", () => { + const { + rowWidth = 0 + } = this.state; + const { + rightOffset = rowWidth + } = this.state; + const rightWidth = rowWidth - rightOffset; + this.animateRow(this.currentOffset(), -rightWidth); + }); + + const _dragX = new _reactNative.Animated.Value(0); + + this.state = { + dragX: _dragX, + rowTranslation: new _reactNative.Animated.Value(0), + rowState: 0, + leftWidth: undefined, + rightOffset: undefined, + rowWidth: undefined + }; + this.updateAnimatedEvent(_props, this.state); + this.onGestureEvent = _reactNative.Animated.event([{ + nativeEvent: { + translationX: _dragX + } + }], { + useNativeDriver: _props.useNativeAnimations + }); + } + + UNSAFE_componentWillUpdate(props, state) { + if (this.props.friction !== props.friction || this.props.overshootLeft !== props.overshootLeft || this.props.overshootRight !== props.overshootRight || this.props.overshootFriction !== props.overshootFriction || this.state.leftWidth !== state.leftWidth || this.state.rightOffset !== state.rightOffset || this.state.rowWidth !== state.rowWidth) { + this.updateAnimatedEvent(props, state); + } + } + + render() { + const { + rowState + } = this.state; + const { + children, + renderLeftActions, + renderRightActions + } = this.props; + const left = renderLeftActions && /*#__PURE__*/React.createElement(_reactNative.Animated.View, { + style: [styles.leftActions, // all those and below parameters can have ! since they are all + // asigned in constructor in `updateAnimatedEvent` but TS cannot spot + // it for some reason + { + transform: [{ + translateX: this.leftActionTranslate + }] + }] + }, renderLeftActions(this.showLeftAction, this.transX), /*#__PURE__*/React.createElement(_reactNative.View, { + onLayout: ({ + nativeEvent + }) => this.setState({ + leftWidth: nativeEvent.layout.x + }) + })); + const right = renderRightActions && /*#__PURE__*/React.createElement(_reactNative.Animated.View, { + style: [styles.rightActions, { + transform: [{ + translateX: this.rightActionTranslate + }] + }] + }, renderRightActions(this.showRightAction, this.transX), /*#__PURE__*/React.createElement(_reactNative.View, { + onLayout: ({ + nativeEvent + }) => this.setState({ + rightOffset: nativeEvent.layout.x + }) + })); + return /*#__PURE__*/React.createElement(_PanGestureHandler.PanGestureHandler, _extends({ + activeOffsetX: [-10, 10] + }, this.props, { + onGestureEvent: this.onGestureEvent, + onHandlerStateChange: this.onHandlerStateChange + }), /*#__PURE__*/React.createElement(_reactNative.Animated.View, { + onLayout: this.onRowLayout, + style: [styles.container, this.props.containerStyle] + }, left, right, /*#__PURE__*/React.createElement(_TapGestureHandler.TapGestureHandler, { + enabled: rowState !== 0, + onHandlerStateChange: this.onTapHandlerStateChange + }, /*#__PURE__*/React.createElement(_reactNative.Animated.View, { + pointerEvents: rowState === 0 ? 'auto' : 'box-only', + style: [{ + transform: [{ + translateX: this.transX + }] + }, this.props.childrenContainerStyle] + }, children)))); + } + +} + +exports.default = Swipeable; + +_defineProperty(Swipeable, "defaultProps", { + friction: 1, + overshootFriction: 1, + useNativeAnimations: true +}); + +const styles = _reactNative.StyleSheet.create({ + container: { + overflow: 'hidden' + }, + leftActions: { ..._reactNative.StyleSheet.absoluteFillObject, + flexDirection: _reactNative.I18nManager.isRTL ? 'row-reverse' : 'row' + }, + rightActions: { ..._reactNative.StyleSheet.absoluteFillObject, + flexDirection: _reactNative.I18nManager.isRTL ? 'row' : 'row-reverse' + } +}); +//# sourceMappingURL=Swipeable.js.map \ No newline at end of file diff --git a/lib/commonjs/components/Swipeable.js.map b/lib/commonjs/components/Swipeable.js.map new file mode 100644 index 0000000000..16b8238fcd --- /dev/null +++ b/lib/commonjs/components/Swipeable.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["Swipeable.tsx"],"names":["DRAG_TOSS","Swipeable","Component","constructor","props","state","friction","overshootFriction","dragX","rowTranslation","leftWidth","rowWidth","rightOffset","rightWidth","Math","max","overshootLeft","overshootRight","transX","Animated","add","interpolate","inputRange","outputRange","showLeftAction","Value","leftActionTranslate","Number","MIN_VALUE","extrapolate","showRightAction","rightActionTranslate","nativeEvent","oldState","State","ACTIVE","close","ev","handleRelease","velocityX","translationX","rowState","leftThreshold","rightThreshold","startOffsetX","currentOffset","toValue","animateRow","fromValue","setValue","setState","sign","spring","restSpeedThreshold","restDisplacementThreshold","velocity","bounciness","useNativeDriver","useNativeAnimations","animationOptions","start","finished","onSwipeableLeftOpen","onSwipeableRightOpen","onSwipeableClose","onSwipeableOpen","onSwipeableLeftWillOpen","onSwipeableRightWillOpen","onSwipeableWillClose","onSwipeableWillOpen","layout","width","undefined","updateAnimatedEvent","onGestureEvent","event","UNSAFE_componentWillUpdate","render","children","renderLeftActions","renderRightActions","left","styles","leftActions","transform","translateX","x","right","rightActions","onHandlerStateChange","onRowLayout","container","containerStyle","onTapHandlerStateChange","childrenContainerStyle","StyleSheet","create","overflow","absoluteFillObject","flexDirection","I18nManager","isRTL"],"mappings":";;;;;;;AAIA;;AAEA;;AAcA;;AAKA;;AAIA;;;;;;;;;;AAEA,MAAMA,SAAS,GAAG,IAAlB;;AAyJe,MAAMC,SAAN,SAAwBC,eAAxB,CAGb;AAOAC,EAAAA,WAAW,CAACC,MAAD,EAAwB;AACjC,UAAMA,MAAN;;AADiC;;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;;AAAA,iDA0CL,CAC5BA,KAD4B,EAE5BC,KAF4B,KAGzB;AACH,YAAM;AAAEC,QAAAA,QAAF;AAAYC,QAAAA;AAAZ,UAAkCH,KAAxC;AACA,YAAM;AAAEI,QAAAA,KAAF;AAASC,QAAAA,cAAT;AAAyBC,QAAAA,SAAS,GAAG,CAArC;AAAwCC,QAAAA,QAAQ,GAAG;AAAnD,UAAyDN,KAA/D;AACA,YAAM;AAAEO,QAAAA,WAAW,GAAGD;AAAhB,UAA6BN,KAAnC;AACA,YAAMQ,UAAU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["// Similarily to the DrawerLayout component this deserves to be put in a\n// separate repo. Although, keeping it here for the time being will allow us to\n// move faster and fix possible issues quicker\n\nimport * as React from 'react';\nimport { Component } from 'react';\nimport {\n Animated,\n StyleSheet,\n View,\n I18nManager,\n LayoutChangeEvent,\n StyleProp,\n ViewStyle,\n} from 'react-native';\n\nimport {\n GestureEvent,\n HandlerStateChangeEvent,\n} from '../handlers/gestureHandlerCommon';\nimport {\n PanGestureHandler,\n PanGestureHandlerEventPayload,\n PanGestureHandlerProps,\n} from '../handlers/PanGestureHandler';\nimport {\n TapGestureHandler,\n TapGestureHandlerEventPayload,\n} from '../handlers/TapGestureHandler';\nimport { State } from '../State';\n\nconst DRAG_TOSS = 0.05;\n\ntype SwipeableExcludes = Exclude<\n keyof PanGestureHandlerProps,\n 'onGestureEvent' | 'onHandlerStateChange'\n>;\n\nexport interface SwipeableProps\n extends Pick {\n /**\n * Enables two-finger gestures on supported devices, for example iPads with\n * trackpads. If not enabled the gesture will require click + drag, with\n * `enableTrackpadTwoFingerGesture` swiping with two fingers will also trigger\n * the gesture.\n */\n enableTrackpadTwoFingerGesture?: boolean;\n\n /**\n * Specifies how much the visual interaction will be delayed compared to the\n * gesture distance. e.g. value of 1 will indicate that the swipeable panel\n * should exactly follow the gesture, 2 means it is going to be two times\n * \"slower\".\n */\n friction?: number;\n\n /**\n * Distance from the left edge at which released panel will animate to the\n * open state (or the open panel will animate into the closed state). By\n * default it's a half of the panel's width.\n */\n leftThreshold?: number;\n\n /**\n * Distance from the right edge at which released panel will animate to the\n * open state (or the open panel will animate into the closed state). By\n * default it's a half of the panel's width.\n */\n rightThreshold?: number;\n\n /**\n * Value indicating if the swipeable panel can be pulled further than the left\n * actions panel's width. It is set to true by default as long as the left\n * panel render method is present.\n */\n overshootLeft?: boolean;\n\n /**\n * Value indicating if the swipeable panel can be pulled further than the\n * right actions panel's width. It is set to true by default as long as the\n * right panel render method is present.\n */\n overshootRight?: boolean;\n\n /**\n * Specifies how much the visual interaction will be delayed compared to the\n * gesture distance at overshoot. Default value is 1, it mean no friction, for\n * a native feel, try 8 or above.\n */\n overshootFriction?: number;\n\n /**\n * Called when left action panel gets open.\n */\n onSwipeableLeftOpen?: () => void;\n\n /**\n * Called when right action panel gets open.\n */\n onSwipeableRightOpen?: () => void;\n\n /**\n * Called when action panel gets open (either right or left).\n */\n onSwipeableOpen?: () => void;\n\n /**\n * Called when action panel is closed.\n */\n onSwipeableClose?: () => void;\n\n /**\n * Called when left action panel starts animating on open.\n */\n onSwipeableLeftWillOpen?: () => void;\n\n /**\n * Called when right action panel starts animating on open.\n */\n onSwipeableRightWillOpen?: () => void;\n\n /**\n * Called when action panel starts animating on open (either right or left).\n */\n onSwipeableWillOpen?: () => void;\n\n /**\n * Called when action panel starts animating on close.\n */\n onSwipeableWillClose?: () => void;\n\n /**\n *\n * This map describes the values to use as inputRange for extra interpolation:\n * AnimatedValue: [startValue, endValue]\n *\n * progressAnimatedValue: [0, 1] dragAnimatedValue: [0, +]\n *\n * To support `rtl` flexbox layouts use `flexDirection` styling.\n * */\n renderLeftActions?: (\n progressAnimatedValue: Animated.AnimatedInterpolation,\n dragAnimatedValue: Animated.AnimatedInterpolation\n ) => React.ReactNode;\n /**\n *\n * This map describes the values to use as inputRange for extra interpolation:\n * AnimatedValue: [startValue, endValue]\n *\n * progressAnimatedValue: [0, 1] dragAnimatedValue: [0, -]\n *\n * To support `rtl` flexbox layouts use `flexDirection` styling.\n * */\n renderRightActions?: (\n progressAnimatedValue: Animated.AnimatedInterpolation,\n dragAnimatedValue: Animated.AnimatedInterpolation\n ) => React.ReactNode;\n\n useNativeAnimations?: boolean;\n\n animationOptions?: Record;\n\n /**\n * Style object for the container (`Animated.View`), for example to override\n * `overflow: 'hidden'`.\n */\n containerStyle?: StyleProp;\n\n /**\n * Style object for the children container (`Animated.View`), for example to\n * apply `flex: 1`\n */\n childrenContainerStyle?: StyleProp;\n}\n\ntype SwipeableState = {\n dragX: Animated.Value;\n rowTranslation: Animated.Value;\n rowState: number;\n leftWidth?: number;\n rightOffset?: number;\n rowWidth?: number;\n};\n\nexport default class Swipeable extends Component<\n SwipeableProps,\n SwipeableState\n> {\n static defaultProps = {\n friction: 1,\n overshootFriction: 1,\n useNativeAnimations: true,\n };\n\n constructor(props: SwipeableProps) {\n super(props);\n const dragX = new Animated.Value(0);\n this.state = {\n dragX,\n rowTranslation: new Animated.Value(0),\n rowState: 0,\n leftWidth: undefined,\n rightOffset: undefined,\n rowWidth: undefined,\n };\n this.updateAnimatedEvent(props, this.state);\n\n this.onGestureEvent = Animated.event(\n [{ nativeEvent: { translationX: dragX } }],\n { useNativeDriver: props.useNativeAnimations! }\n );\n }\n\n UNSAFE_componentWillUpdate(props: SwipeableProps, state: SwipeableState) {\n if (\n this.props.friction !== props.friction ||\n this.props.overshootLeft !== props.overshootLeft ||\n this.props.overshootRight !== props.overshootRight ||\n this.props.overshootFriction !== props.overshootFriction ||\n this.state.leftWidth !== state.leftWidth ||\n this.state.rightOffset !== state.rightOffset ||\n this.state.rowWidth !== state.rowWidth\n ) {\n this.updateAnimatedEvent(props, state);\n }\n }\n\n private onGestureEvent?: (\n event: GestureEvent\n ) => void;\n private transX?: Animated.AnimatedInterpolation;\n private showLeftAction?: Animated.AnimatedInterpolation | Animated.Value;\n private leftActionTranslate?: Animated.AnimatedInterpolation;\n private showRightAction?: Animated.AnimatedInterpolation | Animated.Value;\n private rightActionTranslate?: Animated.AnimatedInterpolation;\n\n private updateAnimatedEvent = (\n props: SwipeableProps,\n state: SwipeableState\n ) => {\n const { friction, overshootFriction } = props;\n const { dragX, rowTranslation, leftWidth = 0, rowWidth = 0 } = state;\n const { rightOffset = rowWidth } = state;\n const rightWidth = Math.max(0, rowWidth - rightOffset);\n\n const {\n overshootLeft = leftWidth > 0,\n overshootRight = rightWidth > 0,\n } = props;\n\n const transX = Animated.add(\n rowTranslation,\n dragX.interpolate({\n inputRange: [0, friction!],\n outputRange: [0, 1],\n })\n ).interpolate({\n inputRange: [-rightWidth - 1, -rightWidth, leftWidth, leftWidth + 1],\n outputRange: [\n -rightWidth - (overshootRight ? 1 / overshootFriction! : 0),\n -rightWidth,\n leftWidth,\n leftWidth + (overshootLeft ? 1 / overshootFriction! : 0),\n ],\n });\n this.transX = transX;\n this.showLeftAction =\n leftWidth > 0\n ? transX.interpolate({\n inputRange: [-1, 0, leftWidth],\n outputRange: [0, 0, 1],\n })\n : new Animated.Value(0);\n this.leftActionTranslate = this.showLeftAction.interpolate({\n inputRange: [0, Number.MIN_VALUE],\n outputRange: [-10000, 0],\n extrapolate: 'clamp',\n });\n this.showRightAction =\n rightWidth > 0\n ? transX.interpolate({\n inputRange: [-rightWidth, 0, 1],\n outputRange: [1, 0, 0],\n })\n : new Animated.Value(0);\n this.rightActionTranslate = this.showRightAction.interpolate({\n inputRange: [0, Number.MIN_VALUE],\n outputRange: [-10000, 0],\n extrapolate: 'clamp',\n });\n };\n\n private onTapHandlerStateChange = ({\n nativeEvent,\n }: HandlerStateChangeEvent) => {\n if (nativeEvent.oldState === State.ACTIVE) {\n this.close();\n }\n };\n\n private onHandlerStateChange = (\n ev: HandlerStateChangeEvent\n ) => {\n if (ev.nativeEvent.oldState === State.ACTIVE) {\n this.handleRelease(ev);\n }\n };\n\n private handleRelease = (\n ev: HandlerStateChangeEvent\n ) => {\n const { velocityX, translationX: dragX } = ev.nativeEvent;\n const { leftWidth = 0, rowWidth = 0, rowState } = this.state;\n const { rightOffset = rowWidth } = this.state;\n const rightWidth = rowWidth - rightOffset;\n const {\n friction,\n leftThreshold = leftWidth / 2,\n rightThreshold = rightWidth / 2,\n } = this.props;\n\n const startOffsetX = this.currentOffset() + dragX / friction!;\n const translationX = (dragX + DRAG_TOSS * velocityX) / friction!;\n\n let toValue = 0;\n if (rowState === 0) {\n if (translationX > leftThreshold) {\n toValue = leftWidth;\n } else if (translationX < -rightThreshold) {\n toValue = -rightWidth;\n }\n } else if (rowState === 1) {\n // swiped to left\n if (translationX > -leftThreshold) {\n toValue = leftWidth;\n }\n } else {\n // swiped to right\n if (translationX < rightThreshold) {\n toValue = -rightWidth;\n }\n }\n\n this.animateRow(startOffsetX, toValue, velocityX / friction!);\n };\n\n private animateRow = (\n fromValue: number,\n toValue: number,\n velocityX?:\n | number\n | {\n x: number;\n y: number;\n }\n ) => {\n const { dragX, rowTranslation } = this.state;\n dragX.setValue(0);\n rowTranslation.setValue(fromValue);\n\n this.setState({ rowState: Math.sign(toValue) });\n Animated.spring(rowTranslation, {\n restSpeedThreshold: 1.7,\n restDisplacementThreshold: 0.4,\n velocity: velocityX,\n bounciness: 0,\n toValue,\n useNativeDriver: this.props.useNativeAnimations!,\n ...this.props.animationOptions,\n }).start(({ finished }) => {\n if (finished) {\n if (toValue > 0 && this.props.onSwipeableLeftOpen) {\n this.props.onSwipeableLeftOpen();\n } else if (toValue < 0 && this.props.onSwipeableRightOpen) {\n this.props.onSwipeableRightOpen();\n }\n\n if (toValue === 0) {\n this.props.onSwipeableClose?.();\n } else {\n this.props.onSwipeableOpen?.();\n }\n }\n });\n if (toValue > 0 && this.props.onSwipeableLeftWillOpen) {\n this.props.onSwipeableLeftWillOpen();\n } else if (toValue < 0 && this.props.onSwipeableRightWillOpen) {\n this.props.onSwipeableRightWillOpen();\n }\n\n if (toValue === 0) {\n this.props.onSwipeableWillClose?.();\n } else {\n this.props.onSwipeableWillOpen?.();\n }\n };\n\n private onRowLayout = ({ nativeEvent }: LayoutChangeEvent) => {\n this.setState({ rowWidth: nativeEvent.layout.width });\n };\n\n private currentOffset = () => {\n const { leftWidth = 0, rowWidth = 0, rowState } = this.state;\n const { rightOffset = rowWidth } = this.state;\n const rightWidth = rowWidth - rightOffset;\n if (rowState === 1) {\n return leftWidth;\n } else if (rowState === -1) {\n return -rightWidth;\n }\n return 0;\n };\n\n close = () => {\n this.animateRow(this.currentOffset(), 0);\n };\n\n openLeft = () => {\n const { leftWidth = 0 } = this.state;\n this.animateRow(this.currentOffset(), leftWidth);\n };\n\n openRight = () => {\n const { rowWidth = 0 } = this.state;\n const { rightOffset = rowWidth } = this.state;\n const rightWidth = rowWidth - rightOffset;\n this.animateRow(this.currentOffset(), -rightWidth);\n };\n\n render() {\n const { rowState } = this.state;\n const { children, renderLeftActions, renderRightActions } = this.props;\n\n const left = renderLeftActions && (\n \n {renderLeftActions(this.showLeftAction!, this.transX!)}\n \n this.setState({ leftWidth: nativeEvent.layout.x })\n }\n />\n \n );\n\n const right = renderRightActions && (\n \n {renderRightActions(this.showRightAction!, this.transX!)}\n \n this.setState({ rightOffset: nativeEvent.layout.x })\n }\n />\n \n );\n\n return (\n \n \n {left}\n {right}\n \n \n {children}\n \n \n \n \n );\n }\n}\n\nconst styles = StyleSheet.create({\n container: {\n overflow: 'hidden',\n },\n leftActions: {\n ...StyleSheet.absoluteFillObject,\n flexDirection: I18nManager.isRTL ? 'row-reverse' : 'row',\n },\n rightActions: {\n ...StyleSheet.absoluteFillObject,\n flexDirection: I18nManager.isRTL ? 'row' : 'row-reverse',\n },\n});\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/touchables/GenericTouchable.js b/lib/commonjs/components/touchables/GenericTouchable.js new file mode 100644 index 0000000000..02731cd1a0 --- /dev/null +++ b/lib/commonjs/components/touchables/GenericTouchable.js @@ -0,0 +1,278 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = exports.TOUCHABLE_STATE = void 0; + +var React = _interopRequireWildcard(require("react")); + +var _reactNative = require("react-native"); + +var _State = require("../../State"); + +var _GestureButtons = require("../GestureButtons"); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +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; } + +/** + * Each touchable is a states' machine which preforms transitions. + * On very beginning (and on the very end or recognition) touchable is + * UNDETERMINED. Then it moves to BEGAN. If touchable recognizes that finger + * travel outside it transits to special MOVED_OUTSIDE state. Gesture recognition + * finishes in UNDETERMINED state. + */ +const TOUCHABLE_STATE = { + UNDETERMINED: 0, + BEGAN: 1, + MOVED_OUTSIDE: 2 +}; +exports.TOUCHABLE_STATE = TOUCHABLE_STATE; + +/** + * GenericTouchable is not intented to be used as it is. + * Should be treated as a source for the rest of touchables + */ +class GenericTouchable extends React.Component { + constructor(...args) { + super(...args); + + _defineProperty(this, "pressInTimeout", void 0); + + _defineProperty(this, "pressOutTimeout", void 0); + + _defineProperty(this, "longPressTimeout", void 0); + + _defineProperty(this, "longPressDetected", false); + + _defineProperty(this, "pointerInside", true); + + _defineProperty(this, "STATE", TOUCHABLE_STATE.UNDETERMINED); + + _defineProperty(this, "onGestureEvent", ({ + nativeEvent: { + pointerInside + } + }) => { + if (this.pointerInside !== pointerInside) { + if (pointerInside) { + this.onMoveIn(); + } else { + this.onMoveOut(); + } + } + + this.pointerInside = pointerInside; + }); + + _defineProperty(this, "onHandlerStateChange", ({ + nativeEvent + }) => { + const { + state + } = nativeEvent; + + if (state === _State.State.CANCELLED || state === _State.State.FAILED) { + // Need to handle case with external cancellation (e.g. by ScrollView) + this.moveToState(TOUCHABLE_STATE.UNDETERMINED); + } else if ( // This platform check is an implication of slightly different behavior of handlers on different platform. + // And Android "Active" state is achieving on first move of a finger, not on press in. + // On iOS event on "Began" is not delivered. + state === (_reactNative.Platform.OS !== 'android' ? _State.State.ACTIVE : _State.State.BEGAN) && this.STATE === TOUCHABLE_STATE.UNDETERMINED) { + // Moving inside requires + this.handlePressIn(); + } else if (state === _State.State.END) { + const shouldCallOnPress = !this.longPressDetected && this.STATE !== TOUCHABLE_STATE.MOVED_OUTSIDE && this.pressOutTimeout === null; + this.handleGoToUndetermined(); + + if (shouldCallOnPress) { + var _this$props$onPress, _this$props; + + // Calls only inside component whether no long press was called previously + (_this$props$onPress = (_this$props = this.props).onPress) === null || _this$props$onPress === void 0 ? void 0 : _this$props$onPress.call(_this$props); + } + } + }); + + _defineProperty(this, "onLongPressDetected", () => { + var _this$props$onLongPre, _this$props2; + + this.longPressDetected = true; // checked for in the caller of `onLongPressDetected`, but better to check twice + + (_this$props$onLongPre = (_this$props2 = this.props).onLongPress) === null || _this$props$onLongPre === void 0 ? void 0 : _this$props$onLongPre.call(_this$props2); + }); + } + + // handlePressIn in called on first touch on traveling inside component. + // Handles state transition with delay. + handlePressIn() { + if (this.props.delayPressIn) { + this.pressInTimeout = setTimeout(() => { + this.moveToState(TOUCHABLE_STATE.BEGAN); + this.pressInTimeout = null; + }, this.props.delayPressIn); + } else { + this.moveToState(TOUCHABLE_STATE.BEGAN); + } + + if (this.props.onLongPress) { + const time = (this.props.delayPressIn || 0) + (this.props.delayLongPress || 0); + this.longPressTimeout = setTimeout(this.onLongPressDetected, time); + } + } // handleMoveOutside in called on traveling outside component. + // Handles state transition with delay. + + + handleMoveOutside() { + if (this.props.delayPressOut) { + this.pressOutTimeout = this.pressOutTimeout || setTimeout(() => { + this.moveToState(TOUCHABLE_STATE.MOVED_OUTSIDE); + this.pressOutTimeout = null; + }, this.props.delayPressOut); + } else { + this.moveToState(TOUCHABLE_STATE.MOVED_OUTSIDE); + } + } // handleGoToUndetermined transits to UNDETERMINED state with proper delay + + + handleGoToUndetermined() { + clearTimeout(this.pressOutTimeout); // TODO: maybe it can be undefined + + if (this.props.delayPressOut) { + this.pressOutTimeout = setTimeout(() => { + if (this.STATE === TOUCHABLE_STATE.UNDETERMINED) { + this.moveToState(TOUCHABLE_STATE.BEGAN); + } + + this.moveToState(TOUCHABLE_STATE.UNDETERMINED); + this.pressOutTimeout = null; + }, this.props.delayPressOut); + } else { + if (this.STATE === TOUCHABLE_STATE.UNDETERMINED) { + this.moveToState(TOUCHABLE_STATE.BEGAN); + } + + this.moveToState(TOUCHABLE_STATE.UNDETERMINED); + } + } + + componentDidMount() { + this.reset(); + } // reset timeout to prevent memory leaks. + + + reset() { + this.longPressDetected = false; + this.pointerInside = true; + clearTimeout(this.pressInTimeout); + clearTimeout(this.pressOutTimeout); + clearTimeout(this.longPressTimeout); + this.pressOutTimeout = null; + this.longPressTimeout = null; + this.pressInTimeout = null; + } // All states' transitions are defined here. + + + moveToState(newState) { + var _this$props$onStateCh, _this$props6; + + if (newState === this.STATE) { + // Ignore dummy transitions + return; + } + + if (newState === TOUCHABLE_STATE.BEGAN) { + var _this$props$onPressIn, _this$props3; + + // First touch and moving inside + (_this$props$onPressIn = (_this$props3 = this.props).onPressIn) === null || _this$props$onPressIn === void 0 ? void 0 : _this$props$onPressIn.call(_this$props3); + } else if (newState === TOUCHABLE_STATE.MOVED_OUTSIDE) { + var _this$props$onPressOu, _this$props4; + + // Moving outside + (_this$props$onPressOu = (_this$props4 = this.props).onPressOut) === null || _this$props$onPressOu === void 0 ? void 0 : _this$props$onPressOu.call(_this$props4); + } else if (newState === TOUCHABLE_STATE.UNDETERMINED) { + // Need to reset each time on transition to UNDETERMINED + this.reset(); + + if (this.STATE === TOUCHABLE_STATE.BEGAN) { + var _this$props$onPressOu2, _this$props5; + + // ... and if it happens inside button. + (_this$props$onPressOu2 = (_this$props5 = this.props).onPressOut) === null || _this$props$onPressOu2 === void 0 ? void 0 : _this$props$onPressOu2.call(_this$props5); + } + } // Finally call lister (used by subclasses) + + + (_this$props$onStateCh = (_this$props6 = this.props).onStateChange) === null || _this$props$onStateCh === void 0 ? void 0 : _this$props$onStateCh.call(_this$props6, this.STATE, newState); // ... and make transition. + + this.STATE = newState; + } + + componentWillUnmount() { + // to prevent memory leaks + this.reset(); + } + + onMoveIn() { + if (this.STATE === TOUCHABLE_STATE.MOVED_OUTSIDE) { + // This call is not throttled with delays (like in RN's implementation). + this.moveToState(TOUCHABLE_STATE.BEGAN); + } + } + + onMoveOut() { + // long press should no longer be detected + clearTimeout(this.longPressTimeout); + this.longPressTimeout = null; + + if (this.STATE === TOUCHABLE_STATE.BEGAN) { + this.handleMoveOutside(); + } + } + + render() { + const coreProps = { + accessible: this.props.accessible !== false, + accessibilityLabel: this.props.accessibilityLabel, + accessibilityHint: this.props.accessibilityHint, + accessibilityRole: this.props.accessibilityRole, + // TODO: check if changed to no 's' correctly, also removed 2 props that are no longer available: `accessibilityComponentType` and `accessibilityTraits`, + // would be good to check if it is ok for sure, see: https://github.com/facebook/react-native/issues/24016 + accessibilityState: this.props.accessibilityState, + nativeID: this.props.nativeID, + onLayout: this.props.onLayout, + hitSlop: this.props.hitSlop + }; + return /*#__PURE__*/React.createElement(_GestureButtons.BaseButton, _extends({ + style: this.props.containerStyle, + onHandlerStateChange: // TODO: not sure if it can be undefined instead of null + this.props.disabled ? undefined : this.onHandlerStateChange, + onGestureEvent: this.onGestureEvent, + hitSlop: this.props.hitSlop, + shouldActivateOnStart: this.props.shouldActivateOnStart, + disallowInterruption: this.props.disallowInterruption, + testID: this.props.testID + }, this.props.extraButtonProps), /*#__PURE__*/React.createElement(_reactNative.Animated.View, _extends({}, coreProps, { + style: this.props.style + }), this.props.children)); + } + +} + +exports.default = GenericTouchable; + +_defineProperty(GenericTouchable, "defaultProps", { + delayLongPress: 600, + extraButtonProps: { + rippleColor: 'transparent', + exclusive: true + } +}); +//# sourceMappingURL=GenericTouchable.js.map \ No newline at end of file diff --git a/lib/commonjs/components/touchables/GenericTouchable.js.map b/lib/commonjs/components/touchables/GenericTouchable.js.map new file mode 100644 index 0000000000..da2410b6be --- /dev/null +++ b/lib/commonjs/components/touchables/GenericTouchable.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GenericTouchable.tsx"],"names":["TOUCHABLE_STATE","UNDETERMINED","BEGAN","MOVED_OUTSIDE","GenericTouchable","Component","nativeEvent","pointerInside","onMoveIn","onMoveOut","state","State","CANCELLED","FAILED","moveToState","Platform","OS","ACTIVE","STATE","handlePressIn","END","shouldCallOnPress","longPressDetected","pressOutTimeout","handleGoToUndetermined","props","onPress","onLongPress","delayPressIn","pressInTimeout","setTimeout","time","delayLongPress","longPressTimeout","onLongPressDetected","handleMoveOutside","delayPressOut","clearTimeout","componentDidMount","reset","newState","onPressIn","onPressOut","onStateChange","componentWillUnmount","render","coreProps","accessible","accessibilityLabel","accessibilityHint","accessibilityRole","accessibilityState","nativeID","onLayout","hitSlop","containerStyle","disabled","undefined","onHandlerStateChange","onGestureEvent","shouldActivateOnStart","disallowInterruption","testID","extraButtonProps","style","children","rippleColor","exclusive"],"mappings":";;;;;;;AAAA;;AAEA;;AAQA;;AACA;;;;;;;;;;AASA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMA,eAAe,GAAG;AAC7BC,EAAAA,YAAY,EAAE,CADe;AAE7BC,EAAAA,KAAK,EAAE,CAFsB;AAG7BC,EAAAA,aAAa,EAAE;AAHc,CAAxB;;;AAkCP;AACA;AACA;AACA;AAEe,MAAMC,gBAAN,SAA+BC,eAA/B,CAEb;AAAA;AAAA;;AAAA;;AAAA;;AAAA;;AAAA,+CAeoB,KAfpB;;AAAA,2CAiBgB,IAjBhB;;AAAA,mCAoBwBL,eAAe,CAACC,YApBxC;;AAAA,4CAkHiB,CAAC;AAChBK,MAAAA,WAAW,EAAE;AAAEC,QAAAA;AAAF;AADG,KAAD,KAEoC;AACnD,UAA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AAKC,cANvB;AAOE,MAAA,OAAO,EAAE,KAAKlC,KAAL,CAAW6B,OAPtB;AAQE,MAAA,qBAAqB,EAAE,KAAK7B,KAAL,CAAWmC,qBARpC;AASE,MAAA,oBAAoB,EAAE,KAAKnC,KAAL,CAAWoC,oBATnC;AAUE,MAAA,MAAM,EAAE,KAAKpC,KAAL,CAAWqC;AAVrB,OAWM,KAAKrC,KAAL,CAAWsC,gBAXjB,gBAYE,oBAAC,qBAAD,CAAU,IAAV,eAAmBjB,SAAnB;AAA8B,MAAA,KAAK,EAAE,KAAKrB,KAAL,CAAWuC;AAAhD,QACG,KAAKvC,KAAL,CAAWwC,QADd,CAZF,CADF;AAkBD;;AAvND;;;;gBAFmB7D,gB,kBAGG;AACpB4B,EAAAA,cAAc,EAAE,GADI;AAEpB+B,EAAAA,gBAAgB,EAAE;AAChBG,IAAAA,WAAW,EAAE,aADG;AAEhBC,IAAAA,SAAS,EAAE;AAFK;AAFE,C","sourcesContent":["import * as React from 'react';\nimport { Component } from 'react';\nimport {\n Animated,\n Platform,\n StyleProp,\n ViewStyle,\n TouchableWithoutFeedbackProps,\n} from 'react-native';\n\nimport { State } from '../../State';\nimport { BaseButton } from '../GestureButtons';\n\nimport {\n GestureEvent,\n HandlerStateChangeEvent,\n} from '../../handlers/gestureHandlerCommon';\nimport { NativeViewGestureHandlerPayload } from '../../handlers/NativeViewGestureHandler';\nimport { TouchableNativeFeedbackExtraProps } from './TouchableNativeFeedback.android';\n\n/**\n * Each touchable is a states' machine which preforms transitions.\n * On very beginning (and on the very end or recognition) touchable is\n * UNDETERMINED. Then it moves to BEGAN. If touchable recognizes that finger\n * travel outside it transits to special MOVED_OUTSIDE state. Gesture recognition\n * finishes in UNDETERMINED state.\n */\nexport const TOUCHABLE_STATE = {\n UNDETERMINED: 0,\n BEGAN: 1,\n MOVED_OUTSIDE: 2,\n} as const;\n\ntype TouchableState = typeof TOUCHABLE_STATE[keyof typeof TOUCHABLE_STATE];\n\nexport interface GenericTouchableProps extends TouchableWithoutFeedbackProps {\n // Decided to drop not used fields from RN's implementation.\n // e.g. onBlur and onFocus as well as deprecated props. - TODO: this comment may be unuseful in this moment\n\n // TODO: in RN these events get native event parameter, which prolly could be used in our implementation too\n onPress?: () => void;\n onPressIn?: () => void;\n onPressOut?: () => void;\n onLongPress?: () => void;\n\n nativeID?: string;\n shouldActivateOnStart?: boolean;\n disallowInterruption?: boolean;\n\n containerStyle?: StyleProp;\n}\n\ninterface InternalProps {\n extraButtonProps: TouchableNativeFeedbackExtraProps;\n onStateChange?: (oldState: TouchableState, newState: TouchableState) => void;\n}\n\n// TODO: maybe can be better\n// TODO: all clearTimeout have ! added, maybe they shouldn't ?\ntype Timeout = ReturnType | null | undefined;\n\n/**\n * GenericTouchable is not intented to be used as it is.\n * Should be treated as a source for the rest of touchables\n */\n\nexport default class GenericTouchable extends Component<\n GenericTouchableProps & InternalProps\n> {\n static defaultProps = {\n delayLongPress: 600,\n extraButtonProps: {\n rippleColor: 'transparent',\n exclusive: true,\n },\n };\n\n // timeout handlers\n pressInTimeout: Timeout;\n pressOutTimeout: Timeout;\n longPressTimeout: Timeout;\n\n // This flag is required since recognition of longPress implies not-invoking onPress\n longPressDetected = false;\n\n pointerInside = true;\n\n // State of touchable\n STATE: TouchableState = TOUCHABLE_STATE.UNDETERMINED;\n\n // handlePressIn in called on first touch on traveling inside component.\n // Handles state transition with delay.\n handlePressIn() {\n if (this.props.delayPressIn) {\n this.pressInTimeout = setTimeout(() => {\n this.moveToState(TOUCHABLE_STATE.BEGAN);\n this.pressInTimeout = null;\n }, this.props.delayPressIn);\n } else {\n this.moveToState(TOUCHABLE_STATE.BEGAN);\n }\n if (this.props.onLongPress) {\n const time =\n (this.props.delayPressIn || 0) + (this.props.delayLongPress || 0);\n this.longPressTimeout = setTimeout(this.onLongPressDetected, time);\n }\n }\n // handleMoveOutside in called on traveling outside component.\n // Handles state transition with delay.\n handleMoveOutside() {\n if (this.props.delayPressOut) {\n this.pressOutTimeout =\n this.pressOutTimeout ||\n setTimeout(() => {\n this.moveToState(TOUCHABLE_STATE.MOVED_OUTSIDE);\n this.pressOutTimeout = null;\n }, this.props.delayPressOut);\n } else {\n this.moveToState(TOUCHABLE_STATE.MOVED_OUTSIDE);\n }\n }\n\n // handleGoToUndetermined transits to UNDETERMINED state with proper delay\n handleGoToUndetermined() {\n clearTimeout(this.pressOutTimeout!); // TODO: maybe it can be undefined\n if (this.props.delayPressOut) {\n this.pressOutTimeout = setTimeout(() => {\n if (this.STATE === TOUCHABLE_STATE.UNDETERMINED) {\n this.moveToState(TOUCHABLE_STATE.BEGAN);\n }\n this.moveToState(TOUCHABLE_STATE.UNDETERMINED);\n this.pressOutTimeout = null;\n }, this.props.delayPressOut);\n } else {\n if (this.STATE === TOUCHABLE_STATE.UNDETERMINED) {\n this.moveToState(TOUCHABLE_STATE.BEGAN);\n }\n this.moveToState(TOUCHABLE_STATE.UNDETERMINED);\n }\n }\n\n componentDidMount() {\n this.reset();\n }\n // reset timeout to prevent memory leaks.\n reset() {\n this.longPressDetected = false;\n this.pointerInside = true;\n clearTimeout(this.pressInTimeout!);\n clearTimeout(this.pressOutTimeout!);\n clearTimeout(this.longPressTimeout!);\n this.pressOutTimeout = null;\n this.longPressTimeout = null;\n this.pressInTimeout = null;\n }\n\n // All states' transitions are defined here.\n moveToState(newState: TouchableState) {\n if (newState === this.STATE) {\n // Ignore dummy transitions\n return;\n }\n if (newState === TOUCHABLE_STATE.BEGAN) {\n // First touch and moving inside\n this.props.onPressIn?.();\n } else if (newState === TOUCHABLE_STATE.MOVED_OUTSIDE) {\n // Moving outside\n this.props.onPressOut?.();\n } else if (newState === TOUCHABLE_STATE.UNDETERMINED) {\n // Need to reset each time on transition to UNDETERMINED\n this.reset();\n if (this.STATE === TOUCHABLE_STATE.BEGAN) {\n // ... and if it happens inside button.\n this.props.onPressOut?.();\n }\n }\n // Finally call lister (used by subclasses)\n this.props.onStateChange?.(this.STATE, newState);\n // ... and make transition.\n this.STATE = newState;\n }\n\n onGestureEvent = ({\n nativeEvent: { pointerInside },\n }: GestureEvent) => {\n if (this.pointerInside !== pointerInside) {\n if (pointerInside) {\n this.onMoveIn();\n } else {\n this.onMoveOut();\n }\n }\n this.pointerInside = pointerInside;\n };\n\n onHandlerStateChange = ({\n nativeEvent,\n }: HandlerStateChangeEvent) => {\n const { state } = nativeEvent;\n if (state === State.CANCELLED || state === State.FAILED) {\n // Need to handle case with external cancellation (e.g. by ScrollView)\n this.moveToState(TOUCHABLE_STATE.UNDETERMINED);\n } else if (\n // This platform check is an implication of slightly different behavior of handlers on different platform.\n // And Android \"Active\" state is achieving on first move of a finger, not on press in.\n // On iOS event on \"Began\" is not delivered.\n state === (Platform.OS !== 'android' ? State.ACTIVE : State.BEGAN) &&\n this.STATE === TOUCHABLE_STATE.UNDETERMINED\n ) {\n // Moving inside requires\n this.handlePressIn();\n } else if (state === State.END) {\n const shouldCallOnPress =\n !this.longPressDetected &&\n this.STATE !== TOUCHABLE_STATE.MOVED_OUTSIDE &&\n this.pressOutTimeout === null;\n this.handleGoToUndetermined();\n if (shouldCallOnPress) {\n // Calls only inside component whether no long press was called previously\n this.props.onPress?.();\n }\n }\n };\n\n onLongPressDetected = () => {\n this.longPressDetected = true;\n // checked for in the caller of `onLongPressDetected`, but better to check twice\n this.props.onLongPress?.();\n };\n\n componentWillUnmount() {\n // to prevent memory leaks\n this.reset();\n }\n\n onMoveIn() {\n if (this.STATE === TOUCHABLE_STATE.MOVED_OUTSIDE) {\n // This call is not throttled with delays (like in RN's implementation).\n this.moveToState(TOUCHABLE_STATE.BEGAN);\n }\n }\n\n onMoveOut() {\n // long press should no longer be detected\n clearTimeout(this.longPressTimeout!);\n this.longPressTimeout = null;\n if (this.STATE === TOUCHABLE_STATE.BEGAN) {\n this.handleMoveOutside();\n }\n }\n\n render() {\n const coreProps = {\n accessible: this.props.accessible !== false,\n accessibilityLabel: this.props.accessibilityLabel,\n accessibilityHint: this.props.accessibilityHint,\n accessibilityRole: this.props.accessibilityRole,\n // TODO: check if changed to no 's' correctly, also removed 2 props that are no longer available: `accessibilityComponentType` and `accessibilityTraits`,\n // would be good to check if it is ok for sure, see: https://github.com/facebook/react-native/issues/24016\n accessibilityState: this.props.accessibilityState,\n nativeID: this.props.nativeID,\n onLayout: this.props.onLayout,\n hitSlop: this.props.hitSlop,\n };\n\n return (\n \n \n {this.props.children}\n \n \n );\n }\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/touchables/TouchableHighlight.js b/lib/commonjs/components/touchables/TouchableHighlight.js new file mode 100644 index 0000000000..c792c9817c --- /dev/null +++ b/lib/commonjs/components/touchables/TouchableHighlight.js @@ -0,0 +1,109 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var React = _interopRequireWildcard(require("react")); + +var _GenericTouchable = _interopRequireWildcard(require("./GenericTouchable")); + +var _reactNative = require("react-native"); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +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; } + +/** + * TouchableHighlight follows RN's implementation + */ +class TouchableHighlight extends React.Component { + constructor(props) { + super(props); + + _defineProperty(this, "showUnderlay", () => { + var _this$props$onShowUnd, _this$props; + + if (!this.hasPressHandler()) { + return; + } + + this.setState({ + extraChildStyle: { + opacity: this.props.activeOpacity + }, + extraUnderlayStyle: { + backgroundColor: this.props.underlayColor + } + }); + (_this$props$onShowUnd = (_this$props = this.props).onShowUnderlay) === null || _this$props$onShowUnd === void 0 ? void 0 : _this$props$onShowUnd.call(_this$props); + }); + + _defineProperty(this, "hasPressHandler", () => this.props.onPress || this.props.onPressIn || this.props.onPressOut || this.props.onLongPress); + + _defineProperty(this, "hideUnderlay", () => { + var _this$props$onHideUnd, _this$props2; + + this.setState({ + extraChildStyle: null, + extraUnderlayStyle: null + }); + (_this$props$onHideUnd = (_this$props2 = this.props).onHideUnderlay) === null || _this$props$onHideUnd === void 0 ? void 0 : _this$props$onHideUnd.call(_this$props2); + }); + + _defineProperty(this, "onStateChange", (_from, to) => { + if (to === _GenericTouchable.TOUCHABLE_STATE.BEGAN) { + this.showUnderlay(); + } else if (to === _GenericTouchable.TOUCHABLE_STATE.UNDETERMINED || to === _GenericTouchable.TOUCHABLE_STATE.MOVED_OUTSIDE) { + this.hideUnderlay(); + } + }); + + this.state = { + extraChildStyle: null, + extraUnderlayStyle: null + }; + } // Copied from RN + + + renderChildren() { + if (!this.props.children) { + return /*#__PURE__*/React.createElement(_reactNative.View, null); + } + + const child = React.Children.only(this.props.children); // TODO: not sure if OK but fixes error + + return /*#__PURE__*/React.cloneElement(child, { + style: _reactNative.StyleSheet.compose(child.props.style, this.state.extraChildStyle) + }); + } + + render() { + const { + style = {}, + ...rest + } = this.props; + const { + extraUnderlayStyle + } = this.state; + return /*#__PURE__*/React.createElement(_GenericTouchable.default, _extends({}, rest, { + style: [style, extraUnderlayStyle], + onStateChange: this.onStateChange + }), this.renderChildren()); + } + +} + +exports.default = TouchableHighlight; + +_defineProperty(TouchableHighlight, "defaultProps", { ..._GenericTouchable.default.defaultProps, + activeOpacity: 0.85, + delayPressOut: 100, + underlayColor: 'black' +}); +//# sourceMappingURL=TouchableHighlight.js.map \ No newline at end of file diff --git a/lib/commonjs/components/touchables/TouchableHighlight.js.map b/lib/commonjs/components/touchables/TouchableHighlight.js.map new file mode 100644 index 0000000000..d4c47d3168 --- /dev/null +++ b/lib/commonjs/components/touchables/TouchableHighlight.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TouchableHighlight.tsx"],"names":["TouchableHighlight","Component","constructor","props","hasPressHandler","setState","extraChildStyle","opacity","activeOpacity","extraUnderlayStyle","backgroundColor","underlayColor","onShowUnderlay","onPress","onPressIn","onPressOut","onLongPress","onHideUnderlay","_from","to","TOUCHABLE_STATE","BEGAN","showUnderlay","UNDETERMINED","MOVED_OUTSIDE","hideUnderlay","state","renderChildren","children","child","React","Children","only","cloneElement","style","StyleSheet","compose","render","rest","onStateChange","GenericTouchable","defaultProps","delayPressOut"],"mappings":";;;;;;;AAAA;;AAEA;;AAIA;;;;;;;;;;AAiBA;AACA;AACA;AACe,MAAMA,kBAAN,SAAiCC,eAAjC,CAGb;AAQAC,EAAAA,WAAW,CAACC,KAAD,EAAyD;AAClE,UAAMA,KAAN;;AADkE,0CASrD,MAAM;AAAA;;AACnB,UAAI,CAAC,KAAKC,eAAL,EAAL,EAA6B;AAC3B;AACD;;AACD,WAAKC,QAAL,CAAc;AACZC,QAAAA,eAAe,EAAE;AACfC,UAAAA,OAAO,EAAE,KAAKJ,KAAL,CAAWK;AADL,SADL;AAIZC,QAAAA,kBAAkB,EAAE;AAClBC,UAAAA,eAAe,EAAE,KAAKP,KAAL,CAAWQ;AADV;AAJR,OAAd;AAQA,mDAAKR,KAAL,EAAWS,cAAX;AACD,KAtBmE;;AAAA,6CAwBlD,MAChB,KAAKT,KAAL,CAAWU,OAAX,IACA,KAAKV,KAAL,CAAWW,S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E,oBAAC,yBAAD,eACMY,IADN;AAEE,MAAA,KAAK,EAAE,CAACJ,KAAD,EAAQzB,kBAAR,CAFT;AAGE,MAAA,aAAa,EAAE,KAAK8B;AAHtB,QAIG,KAAKZ,cAAL,EAJH,CADF;AAQD;;AAjFD;;;;gBAHmB3B,kB,kBAIG,EACpB,GAAGwC,0BAAiBC,YADA;AAEpBjC,EAAAA,aAAa,EAAE,IAFK;AAGpBkC,EAAAA,aAAa,EAAE,GAHK;AAIpB/B,EAAAA,aAAa,EAAE;AAJK,C","sourcesContent":["import * as React from 'react';\nimport { Component } from 'react';\nimport GenericTouchable, {\n GenericTouchableProps,\n TOUCHABLE_STATE,\n} from './GenericTouchable';\nimport {\n StyleSheet,\n View,\n TouchableHighlightProps,\n ColorValue,\n ViewProps,\n} from 'react-native';\n\ninterface State {\n extraChildStyle: null | {\n opacity?: number;\n };\n extraUnderlayStyle: null | {\n backgroundColor?: ColorValue;\n };\n}\n\n/**\n * TouchableHighlight follows RN's implementation\n */\nexport default class TouchableHighlight extends Component<\n TouchableHighlightProps & GenericTouchableProps,\n State\n> {\n static defaultProps = {\n ...GenericTouchable.defaultProps,\n activeOpacity: 0.85,\n delayPressOut: 100,\n underlayColor: 'black',\n };\n\n constructor(props: TouchableHighlightProps & GenericTouchableProps) {\n super(props);\n this.state = {\n extraChildStyle: null,\n extraUnderlayStyle: null,\n };\n }\n\n // Copied from RN\n showUnderlay = () => {\n if (!this.hasPressHandler()) {\n return;\n }\n this.setState({\n extraChildStyle: {\n opacity: this.props.activeOpacity,\n },\n extraUnderlayStyle: {\n backgroundColor: this.props.underlayColor,\n },\n });\n this.props.onShowUnderlay?.();\n };\n\n hasPressHandler = () =>\n this.props.onPress ||\n this.props.onPressIn ||\n this.props.onPressOut ||\n this.props.onLongPress;\n\n hideUnderlay = () => {\n this.setState({\n extraChildStyle: null,\n extraUnderlayStyle: null,\n });\n this.props.onHideUnderlay?.();\n };\n\n renderChildren() {\n if (!this.props.children) {\n return ;\n }\n\n const child = React.Children.only(\n this.props.children\n ) as React.ReactElement; // TODO: not sure if OK but fixes error\n return React.cloneElement(child, {\n style: StyleSheet.compose(child.props.style, this.state.extraChildStyle),\n });\n }\n\n onStateChange = (_from: number, to: number) => {\n if (to === TOUCHABLE_STATE.BEGAN) {\n this.showUnderlay();\n } else if (\n to === TOUCHABLE_STATE.UNDETERMINED ||\n to === TOUCHABLE_STATE.MOVED_OUTSIDE\n ) {\n this.hideUnderlay();\n }\n };\n\n render() {\n const { style = {}, ...rest } = this.props;\n const { extraUnderlayStyle } = this.state;\n return (\n \n {this.renderChildren()}\n \n );\n }\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/touchables/TouchableNativeFeedback.android.js b/lib/commonjs/components/touchables/TouchableNativeFeedback.android.js new file mode 100644 index 0000000000..c07b4e98a9 --- /dev/null +++ b/lib/commonjs/components/touchables/TouchableNativeFeedback.android.js @@ -0,0 +1,100 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _reactNative = require("react-native"); + +var React = _interopRequireWildcard(require("react")); + +var _GenericTouchable = _interopRequireDefault(require("./GenericTouchable")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +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; } + +/** + * TouchableNativeFeedback behaves slightly different than RN's TouchableNativeFeedback. + * There's small difference with handling long press ripple since RN's implementation calls + * ripple animation via bridge. This solution leaves all animations' handling for native components so + * it follows native behaviours. + */ +class TouchableNativeFeedback extends React.Component { + // could be taken as RNTouchableNativeFeedback.SelectableBackground etc. but the API may change + getExtraButtonProps() { + const extraProps = {}; + const { + background + } = this.props; + + if (background) { + // I changed type values to match those used in RN + // TODO(TS): check if it works the same as previous implementation - looks like it works the same as RN component, so it should be ok + if (background.type === 'RippleAndroid') { + extraProps['borderless'] = background.borderless; + extraProps['rippleColor'] = background.color; + } else if (background.type === 'ThemeAttrAndroid') { + extraProps['borderless'] = background.attribute === 'selectableItemBackgroundBorderless'; + } // I moved it from above since it should be available in all options + + + extraProps['rippleRadius'] = background.rippleRadius; + } + + extraProps['foreground'] = this.props.useForeground; + return extraProps; + } + + render() { + const { + style = {}, + ...rest + } = this.props; + return /*#__PURE__*/React.createElement(_GenericTouchable.default, _extends({}, rest, { + style: style, + extraButtonProps: this.getExtraButtonProps() + })); + } + +} + +exports.default = TouchableNativeFeedback; + +_defineProperty(TouchableNativeFeedback, "defaultProps", { ..._GenericTouchable.default.defaultProps, + useForeground: true, + extraButtonProps: { + // Disable hiding ripple on Android + rippleColor: null + } +}); + +_defineProperty(TouchableNativeFeedback, "SelectableBackground", rippleRadius => ({ + type: 'ThemeAttrAndroid', + // I added `attribute` prop to clone the implementation of RN and be able to use only 2 types + attribute: 'selectableItemBackground', + rippleRadius +})); + +_defineProperty(TouchableNativeFeedback, "SelectableBackgroundBorderless", rippleRadius => ({ + type: 'ThemeAttrAndroid', + attribute: 'selectableItemBackgroundBorderless', + rippleRadius +})); + +_defineProperty(TouchableNativeFeedback, "Ripple", (color, borderless, rippleRadius) => ({ + type: 'RippleAndroid', + color, + borderless, + rippleRadius +})); + +_defineProperty(TouchableNativeFeedback, "canUseNativeForeground", () => _reactNative.Platform.Version >= 23); +//# sourceMappingURL=TouchableNativeFeedback.android.js.map \ No newline at end of file diff --git a/lib/commonjs/components/touchables/TouchableNativeFeedback.android.js.map b/lib/commonjs/components/touchables/TouchableNativeFeedback.android.js.map new file mode 100644 index 0000000000..e7a57eba29 --- /dev/null +++ b/lib/commonjs/components/touchables/TouchableNativeFeedback.android.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TouchableNativeFeedback.android.tsx"],"names":["TouchableNativeFeedback","Component","getExtraButtonProps","extraProps","background","props","type","borderless","color","attribute","rippleRadius","useForeground","render","style","rest","GenericTouchable","defaultProps","extraButtonProps","rippleColor","Platform","Version"],"mappings":";;;;;;;AAAA;;AAKA;;AAEA;;;;;;;;;;;;AASA;AACA;AACA;AACA;AACA;AACA;AACe,MAAMA,uBAAN,SAAsCC,eAAtC,CAEb;AAUA;AAyBAC,EAAAA,mBAAmB,GAAG;AACpB,UAAMC,UAA6C,GAAG,EAAtD;AACA,UAAM;AAAEC,MAAAA;AAAF,QAAiB,KAAKC,KAA5B;;AACA,QAAID,UAAJ,EAAgB;AACd;AACA;AACA,UAAIA,UAAU,CAACE,IAAX,KAAoB,eAAxB,EAAyC;AACvCH,QAAAA,UAAU,CAAC,YAAD,CAAV,GAA2BC,UAAU,CAACG,UAAtC;AACAJ,QAAAA,UAAU,CAAC,aAAD,CAAV,GAA4BC,UAAU,CAACI,KAAvC;AACD,OAHD,MAGO,IAAIJ,UAAU,CAACE,IAAX,KAAoB,kBAAxB,EAA4C;AACjDH,QAAAA,UAAU,CAAC,YAAD,CAAV,GACEC,UAAU,CAACK,SAAX,KAAyB,oCAD3B;AAED,OATa,CAUd;;;AACAN,MAAAA,UAAU,CAAC,cAAD,CAAV,GAA6BC,UAAU,CAACM,YAAxC;AACD;;AACDP,IAAAA,UAAU,CAAC,YAAD,CAAV,GAA2B,KAAKE,KAAL,CAAWM,aAAtC;AACA,WAAOR,UAAP;AACD;;AACDS,EAAAA,MAAM,GAAG;AACP,UAAM;AAAEC,MAAAA,KAAK,GAAG,EAAV;AAAc,SAAGC;AAAjB,QAA0B,KAAKT,KAArC;AACA,wBACE,oBAAC,yBAAD,eACMS,IADN;AAEE,MAAA,KAAK,EAAED,KAFT;AAGE,MAAA,gBAAgB,EAAE,KAAKX,mBAAL;AAHpB,OADF;AAOD;;AA/DD;;;;gBAFmBF,uB,kBAGG,EACpB,GAAGe,0BAAiBC,YADA;AAEpBL,EAAAA,aAAa,EAAE,IAFK;AAGpBM,EAAAA,gBAAgB,EAAE;AAChB;AACAC,IAAAA,WAAW,EAAE;AAFG;AAHE,C;;gBAHHlB,uB,0BAaYU,YAAD,KAA4B;AACxDJ,EAAAA,IAAI,EAAE,kBADkD;AAExD;AACAG,EAAAA,SAAS,EAAE,0BAH6C;AAIxDC,EAAAA;AAJwD,CAA5B,C;;gBAbXV,uB,oCAmBsBU,YAAD,KAA4B;AAClEJ,EAAAA,IAAI,EAAE,kBAD4D;AAElEG,EAAAA,SAAS,EAAE,oCAFuD;AAGlEC,EAAAA;AAHkE,CAA5B,C;;gBAnBrBV,uB,YAwBH,CACdQ,KADc,EAEdD,UAFc,EAGdG,YAHc,MAIV;AACJJ,EAAAA,IAAI,EAAE,eADF;AAEJE,EAAAA,KAFI;AAGJD,EAAAA,UAHI;AAIJG,EAAAA;AAJI,CAJU,C;;gBAxBGV,uB,4BAmCa,MAAMmB,sBAASC,OAAT,IAAoB,E","sourcesContent":["import {\n Platform,\n TouchableNativeFeedbackProps,\n ColorValue,\n} from 'react-native';\nimport * as React from 'react';\nimport { Component } from 'react';\nimport GenericTouchable, { GenericTouchableProps } from './GenericTouchable';\n\nexport type TouchableNativeFeedbackExtraProps = {\n borderless?: boolean;\n rippleColor?: number | null;\n rippleRadius?: number | null;\n foreground?: boolean;\n};\n\n/**\n * TouchableNativeFeedback behaves slightly different than RN's TouchableNativeFeedback.\n * There's small difference with handling long press ripple since RN's implementation calls\n * ripple animation via bridge. This solution leaves all animations' handling for native components so\n * it follows native behaviours.\n */\nexport default class TouchableNativeFeedback extends Component<\n TouchableNativeFeedbackProps & GenericTouchableProps\n> {\n static defaultProps = {\n ...GenericTouchable.defaultProps,\n useForeground: true,\n extraButtonProps: {\n // Disable hiding ripple on Android\n rippleColor: null,\n },\n };\n\n // could be taken as RNTouchableNativeFeedback.SelectableBackground etc. but the API may change\n static SelectableBackground = (rippleRadius?: number) => ({\n type: 'ThemeAttrAndroid',\n // I added `attribute` prop to clone the implementation of RN and be able to use only 2 types\n attribute: 'selectableItemBackground',\n rippleRadius,\n });\n static SelectableBackgroundBorderless = (rippleRadius?: number) => ({\n type: 'ThemeAttrAndroid',\n attribute: 'selectableItemBackgroundBorderless',\n rippleRadius,\n });\n static Ripple = (\n color: ColorValue,\n borderless: boolean,\n rippleRadius?: number\n ) => ({\n type: 'RippleAndroid',\n color,\n borderless,\n rippleRadius,\n });\n\n static canUseNativeForeground = () => Platform.Version >= 23;\n\n getExtraButtonProps() {\n const extraProps: TouchableNativeFeedbackExtraProps = {};\n const { background } = this.props;\n if (background) {\n // I changed type values to match those used in RN\n // TODO(TS): check if it works the same as previous implementation - looks like it works the same as RN component, so it should be ok\n if (background.type === 'RippleAndroid') {\n extraProps['borderless'] = background.borderless;\n extraProps['rippleColor'] = background.color;\n } else if (background.type === 'ThemeAttrAndroid') {\n extraProps['borderless'] =\n background.attribute === 'selectableItemBackgroundBorderless';\n }\n // I moved it from above since it should be available in all options\n extraProps['rippleRadius'] = background.rippleRadius;\n }\n extraProps['foreground'] = this.props.useForeground;\n return extraProps;\n }\n render() {\n const { style = {}, ...rest } = this.props;\n return (\n \n );\n }\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/touchables/TouchableNativeFeedback.js b/lib/commonjs/components/touchables/TouchableNativeFeedback.js new file mode 100644 index 0000000000..419cc6e453 --- /dev/null +++ b/lib/commonjs/components/touchables/TouchableNativeFeedback.js @@ -0,0 +1,12 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _reactNative = require("react-native"); + +var _default = _reactNative.TouchableNativeFeedback; +exports.default = _default; +//# sourceMappingURL=TouchableNativeFeedback.js.map \ No newline at end of file diff --git a/lib/commonjs/components/touchables/TouchableNativeFeedback.js.map b/lib/commonjs/components/touchables/TouchableNativeFeedback.js.map new file mode 100644 index 0000000000..fb781ea45d --- /dev/null +++ b/lib/commonjs/components/touchables/TouchableNativeFeedback.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TouchableNativeFeedback.tsx"],"names":["TouchableNativeFeedback"],"mappings":";;;;;;;AAAA;;eAEeA,oC","sourcesContent":["import { TouchableNativeFeedback } from 'react-native';\n\nexport default TouchableNativeFeedback;\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/touchables/TouchableOpacity.js b/lib/commonjs/components/touchables/TouchableOpacity.js new file mode 100644 index 0000000000..faccc1c954 --- /dev/null +++ b/lib/commonjs/components/touchables/TouchableOpacity.js @@ -0,0 +1,75 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _reactNative = require("react-native"); + +var _GenericTouchable = _interopRequireWildcard(require("./GenericTouchable")); + +var React = _interopRequireWildcard(require("react")); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +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; } + +/** + * TouchableOpacity bases on timing animation which has been used in RN's core + */ +class TouchableOpacity extends React.Component { + constructor(...args) { + super(...args); + + _defineProperty(this, "getChildStyleOpacityWithDefault", () => { + const childStyle = _reactNative.StyleSheet.flatten(this.props.style) || {}; + return childStyle.opacity == null ? 1 : childStyle.opacity; + }); + + _defineProperty(this, "opacity", new _reactNative.Animated.Value(this.getChildStyleOpacityWithDefault())); + + _defineProperty(this, "setOpacityTo", (value, duration) => { + _reactNative.Animated.timing(this.opacity, { + toValue: value, + duration: duration, + easing: _reactNative.Easing.inOut(_reactNative.Easing.quad), + useNativeDriver: false + }).start(); + }); + + _defineProperty(this, "onStateChange", (_from, to) => { + if (to === _GenericTouchable.TOUCHABLE_STATE.BEGAN) { + this.setOpacityTo(this.props.activeOpacity, 0); + } else if (to === _GenericTouchable.TOUCHABLE_STATE.UNDETERMINED || to === _GenericTouchable.TOUCHABLE_STATE.MOVED_OUTSIDE) { + this.setOpacityTo(this.getChildStyleOpacityWithDefault(), 150); + } + }); + } + + render() { + const { + style = {}, + ...rest + } = this.props; + return /*#__PURE__*/React.createElement(_GenericTouchable.default, _extends({}, rest, { + style: [style, { + opacity: this.opacity // TODO: fix this + + }], + onStateChange: this.onStateChange + }), this.props.children ? this.props.children : /*#__PURE__*/React.createElement(_reactNative.View, null)); + } + +} + +exports.default = TouchableOpacity; + +_defineProperty(TouchableOpacity, "defaultProps", { ..._GenericTouchable.default.defaultProps, + activeOpacity: 0.2 +}); +//# sourceMappingURL=TouchableOpacity.js.map \ No newline at end of file diff --git a/lib/commonjs/components/touchables/TouchableOpacity.js.map b/lib/commonjs/components/touchables/TouchableOpacity.js.map new file mode 100644 index 0000000000..455a44988c --- /dev/null +++ b/lib/commonjs/components/touchables/TouchableOpacity.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TouchableOpacity.tsx"],"names":["TouchableOpacity","Component","childStyle","StyleSheet","flatten","props","style","opacity","Animated","Value","getChildStyleOpacityWithDefault","value","duration","timing","toValue","easing","Easing","inOut","quad","useNativeDriver","start","_from","to","TOUCHABLE_STATE","BEGAN","setOpacityTo","activeOpacity","UNDETERMINED","MOVED_OUTSIDE","render","rest","onStateChange","children","GenericTouchable","defaultProps"],"mappings":";;;;;;;AAAA;;AAOA;;AAIA;;;;;;;;;;AAGA;AACA;AACA;AACe,MAAMA,gBAAN,SAA+BC,eAA/B,CAEb;AAAA;AAAA;;AAAA,6DAOkC,MAAM;AACtC,YAAMC,UAAU,GAAGC,wBAAWC,OAAX,CAAmB,KAAKC,KAAL,CAAWC,KAA9B,KAAwC,EAA3D;AACA,aAAOJ,UAAU,CAACK,OAAX,IAAsB,IAAtB,GAA6B,CAA7B,GAAiCL,UAAU,CAACK,OAAnD;AACD,KAVD;;AAAA,qCAYU,IAAIC,sBAASC,KAAb,CAAmB,KAAKC,+BAAL,EAAnB,CAZV;;AAAA,0CAce,CAACC,KAAD,EAAgBC,QAAhB,KAAqC;AAClDJ,4BAASK,MAAT,CAAgB,KAAKN,OAArB,EAA8B;AAC5BO,QAAAA,OAAO,EAAEH,KADmB;AAE5BC,QAAAA,QAAQ,EAAEA,QAFkB;AAG5BG,QAAAA,MAAM,EAAEC,oBAAOC,KAAP,CAAaD,oBAAOE,IAApB,CAHoB;AAI5BC,QAAAA,eAAe,EAAE;AAJW,OAA9B,EAKGC,KALH;AAMD,KArBD;;AAAA,2CAuBgB,CAACC,KAAD,EAAgBC,EAAhB,KAA+B;AAC7C,UAAIA,EAAE,KAAKC,kCAAgBC,KAA3B,EAAkC;AAChC,aAAKC,YAAL,CAAkB,KAAKpB,KAAL,CAAWqB,aAA7B,EAA6C,CAA7C;AACD,OAFD,MAEO,IACLJ,EAAE,KAAKC,kCAAgBI,YAAvB,IACAL,EAAE,KAAKC,kCAAgBK,aAFlB,EAGL;AACA,aAAKH,YAAL,CAAkB,KAAKf,+BAAL,EAAlB,EAA0D,GAA1D;AACD;AACF,KAhCD;AAAA;;AAkCAmB,EAAAA,MAAM,GAAG;AACP,UAAM;AAAEvB,MAAAA,KAAK,GAAG,EAAV;AAAc,SAAGwB;AAAjB,QAA0B,KAAKzB,KAArC;AACA,wBACE,oBAAC,yBAAD,eACMyB,IADN;AAEE,MAAA,KAAK,EAAE,CACLxB,KADK,EAEL;AACEC,QAAAA,OAAO,EAAG,KAAKA,OADjB,CACgD;;AADhD,OAFK,CAFT;AAQE,MAAA,aAAa,EAAE,KAAKwB;AARtB,QASG,KAAK1B,KAAL,CAAW2B,QAAX,GAAsB,KAAK3B,KAAL,CAAW2B,QAAjC,gBAA4C,oBAAC,iBAAD,OAT/C,CADF;AAaD;;AAjDD;;;;gBAFmBhC,gB,kBAGG,EACpB,GAAGiC,0BAAiBC,YADA;AAEpBR,EAAAA,aAAa,EAAE;AAFK,C","sourcesContent":["import {\n Animated,\n Easing,\n StyleSheet,\n View,\n TouchableOpacityProps,\n} from 'react-native';\nimport GenericTouchable, {\n TOUCHABLE_STATE,\n GenericTouchableProps,\n} from './GenericTouchable';\nimport * as React from 'react';\nimport { Component } from 'react';\n\n/**\n * TouchableOpacity bases on timing animation which has been used in RN's core\n */\nexport default class TouchableOpacity extends Component<\n TouchableOpacityProps & GenericTouchableProps\n> {\n static defaultProps = {\n ...GenericTouchable.defaultProps,\n activeOpacity: 0.2,\n };\n\n // opacity is 1 one by default but could be overwritten\n getChildStyleOpacityWithDefault = () => {\n const childStyle = StyleSheet.flatten(this.props.style) || {};\n return childStyle.opacity == null ? 1 : childStyle.opacity;\n };\n\n opacity = new Animated.Value(this.getChildStyleOpacityWithDefault());\n\n setOpacityTo = (value: number, duration: number) => {\n Animated.timing(this.opacity, {\n toValue: value,\n duration: duration,\n easing: Easing.inOut(Easing.quad),\n useNativeDriver: false,\n }).start();\n };\n\n onStateChange = (_from: number, to: number) => {\n if (to === TOUCHABLE_STATE.BEGAN) {\n this.setOpacityTo(this.props.activeOpacity!, 0);\n } else if (\n to === TOUCHABLE_STATE.UNDETERMINED ||\n to === TOUCHABLE_STATE.MOVED_OUTSIDE\n ) {\n this.setOpacityTo(this.getChildStyleOpacityWithDefault(), 150);\n }\n };\n\n render() {\n const { style = {}, ...rest } = this.props;\n return (\n \n {this.props.children ? this.props.children : }\n \n );\n }\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/touchables/TouchableWithoutFeedback.js b/lib/commonjs/components/touchables/TouchableWithoutFeedback.js new file mode 100644 index 0000000000..f81a088681 --- /dev/null +++ b/lib/commonjs/components/touchables/TouchableWithoutFeedback.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var React = _interopRequireWildcard(require("react")); + +var _GenericTouchable = _interopRequireDefault(require("./GenericTouchable")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +const TouchableWithoutFeedback = /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/React.createElement(_GenericTouchable.default, _extends({ + ref: ref +}, props))); +TouchableWithoutFeedback.defaultProps = _GenericTouchable.default.defaultProps; +var _default = TouchableWithoutFeedback; +exports.default = _default; +//# sourceMappingURL=TouchableWithoutFeedback.js.map \ No newline at end of file diff --git a/lib/commonjs/components/touchables/TouchableWithoutFeedback.js.map b/lib/commonjs/components/touchables/TouchableWithoutFeedback.js.map new file mode 100644 index 0000000000..bc21870ff1 --- /dev/null +++ b/lib/commonjs/components/touchables/TouchableWithoutFeedback.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TouchableWithoutFeedback.tsx"],"names":["TouchableWithoutFeedback","React","forwardRef","props","ref","defaultProps","GenericTouchable"],"mappings":";;;;;;;AAAA;;AAEA;;;;;;;;;;AAEA,MAAMA,wBAAwB,gBAAGC,KAAK,CAACC,UAAN,CAG/B,CAACC,KAAD,EAAQC,GAAR,kBAAgB,oBAAC,yBAAD;AAAkB,EAAA,GAAG,EAAEA;AAAvB,GAAgCD,KAAhC,EAHe,CAAjC;AAKAH,wBAAwB,CAACK,YAAzB,GAAwCC,0BAAiBD,YAAzD;eAEeL,wB","sourcesContent":["import * as React from 'react';\nimport { PropsWithChildren } from 'react';\nimport GenericTouchable, { GenericTouchableProps } from './GenericTouchable';\n\nconst TouchableWithoutFeedback = React.forwardRef<\n GenericTouchable,\n PropsWithChildren\n>((props, ref) => );\n\nTouchableWithoutFeedback.defaultProps = GenericTouchable.defaultProps;\n\nexport default TouchableWithoutFeedback;\n"]} \ No newline at end of file diff --git a/lib/commonjs/components/touchables/index.js b/lib/commonjs/components/touchables/index.js new file mode 100644 index 0000000000..7ea96ef6a6 --- /dev/null +++ b/lib/commonjs/components/touchables/index.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "TouchableNativeFeedback", { + enumerable: true, + get: function () { + return _TouchableNativeFeedback.default; + } +}); +Object.defineProperty(exports, "TouchableWithoutFeedback", { + enumerable: true, + get: function () { + return _TouchableWithoutFeedback.default; + } +}); +Object.defineProperty(exports, "TouchableOpacity", { + enumerable: true, + get: function () { + return _TouchableOpacity.default; + } +}); +Object.defineProperty(exports, "TouchableHighlight", { + enumerable: true, + get: function () { + return _TouchableHighlight.default; + } +}); + +var _TouchableNativeFeedback = _interopRequireDefault(require("./TouchableNativeFeedback")); + +var _TouchableWithoutFeedback = _interopRequireDefault(require("./TouchableWithoutFeedback")); + +var _TouchableOpacity = _interopRequireDefault(require("./TouchableOpacity")); + +var _TouchableHighlight = _interopRequireDefault(require("./TouchableHighlight")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/commonjs/components/touchables/index.js.map b/lib/commonjs/components/touchables/index.js.map new file mode 100644 index 0000000000..215407f317 --- /dev/null +++ b/lib/commonjs/components/touchables/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;AACA;;AACA;;AACA","sourcesContent":["export { default as TouchableNativeFeedback } from './TouchableNativeFeedback';\nexport { default as TouchableWithoutFeedback } from './TouchableWithoutFeedback';\nexport { default as TouchableOpacity } from './TouchableOpacity';\nexport { default as TouchableHighlight } from './TouchableHighlight';\n"]} \ No newline at end of file diff --git a/lib/commonjs/gestureHandlerRootHOC.js b/lib/commonjs/gestureHandlerRootHOC.js new file mode 100644 index 0000000000..3eb329111c --- /dev/null +++ b/lib/commonjs/gestureHandlerRootHOC.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = gestureHandlerRootHOC; + +var React = _interopRequireWildcard(require("react")); + +var _reactNative = require("react-native"); + +var _hoistNonReactStatics = _interopRequireDefault(require("hoist-non-react-statics")); + +var _GestureHandlerRootView = _interopRequireDefault(require("./GestureHandlerRootView")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function gestureHandlerRootHOC(Component, containerStyles) { + function Wrapper(props) { + return /*#__PURE__*/React.createElement(_GestureHandlerRootView.default, { + style: [styles.container, containerStyles] + }, /*#__PURE__*/React.createElement(Component, props)); + } + + Wrapper.displayName = `gestureHandlerRootHOC(${Component.displayName || Component.name})`; + (0, _hoistNonReactStatics.default)(Wrapper, Component); + return Wrapper; +} + +const styles = _reactNative.StyleSheet.create({ + container: { + flex: 1 + } +}); +//# sourceMappingURL=gestureHandlerRootHOC.js.map \ No newline at end of file diff --git a/lib/commonjs/gestureHandlerRootHOC.js.map b/lib/commonjs/gestureHandlerRootHOC.js.map new file mode 100644 index 0000000000..0a1e22c6c4 --- /dev/null +++ b/lib/commonjs/gestureHandlerRootHOC.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["gestureHandlerRootHOC.tsx"],"names":["gestureHandlerRootHOC","Component","containerStyles","Wrapper","props","styles","container","displayName","name","StyleSheet","create","flex"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AACA;;;;;;;;AAEe,SAASA,qBAAT,CACbC,SADa,EAEbC,eAFa,EAGW;AACxB,WAASC,OAAT,CAAiBC,KAAjB,EAA2B;AACzB,wBACE,oBAAC,+BAAD;AAAwB,MAAA,KAAK,EAAE,CAACC,MAAM,CAACC,SAAR,EAAmBJ,eAAnB;AAA/B,oBACE,oBAAC,SAAD,EAAeE,KAAf,CADF,CADF;AAKD;;AAEDD,EAAAA,OAAO,CAACI,WAAR,GAAuB,yBACrBN,SAAS,CAACM,WAAV,IAAyBN,SAAS,CAACO,IACpC,GAFD;AAIA,qCAAqBL,OAArB,EAA8BF,SAA9B;AAEA,SAAOE,OAAP;AACD;;AAED,MAAME,MAAM,GAAGI,wBAAWC,MAAX,CAAkB;AAC/BJ,EAAAA,SAAS,EAAE;AAAEK,IAAAA,IAAI,EAAE;AAAR;AADoB,CAAlB,CAAf","sourcesContent":["import * as React from 'react';\nimport { StyleSheet, StyleProp, ViewStyle } from 'react-native';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport GestureHandlerRootView from './GestureHandlerRootView';\n\nexport default function gestureHandlerRootHOC

(\n Component: React.ComponentType

,\n containerStyles?: StyleProp\n): React.ComponentType

{\n function Wrapper(props: P) {\n return (\n \n \n \n );\n }\n\n Wrapper.displayName = `gestureHandlerRootHOC(${\n Component.displayName || Component.name\n })`;\n\n hoistNonReactStatics(Wrapper, Component);\n\n return Wrapper;\n}\n\nconst styles = StyleSheet.create({\n container: { flex: 1 },\n});\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/FlingGestureHandler.js b/lib/commonjs/handlers/FlingGestureHandler.js new file mode 100644 index 0000000000..1c9d9db9c4 --- /dev/null +++ b/lib/commonjs/handlers/FlingGestureHandler.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FlingGestureHandler = exports.flingGestureHandlerProps = void 0; + +var _createHandler = _interopRequireDefault(require("./createHandler")); + +var _gestureHandlerCommon = require("./gestureHandlerCommon"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const flingGestureHandlerProps = ['numberOfPointers', 'direction']; +exports.flingGestureHandlerProps = flingGestureHandlerProps; +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +const FlingGestureHandler = (0, _createHandler.default)({ + name: 'FlingGestureHandler', + allowedProps: [..._gestureHandlerCommon.baseGestureHandlerProps, ...flingGestureHandlerProps], + config: {} +}); +exports.FlingGestureHandler = FlingGestureHandler; +//# sourceMappingURL=FlingGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/FlingGestureHandler.js.map b/lib/commonjs/handlers/FlingGestureHandler.js.map new file mode 100644 index 0000000000..e242d8f029 --- /dev/null +++ b/lib/commonjs/handlers/FlingGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["FlingGestureHandler.ts"],"names":["flingGestureHandlerProps","FlingGestureHandler","name","allowedProps","baseGestureHandlerProps","config"],"mappings":";;;;;;;AAAA;;AACA;;;;AAKO,MAAMA,wBAAwB,GAAG,CACtC,kBADsC,EAEtC,WAFsC,CAAjC;;AAuCP;AACO,MAAMC,mBAAmB,GAAG,4BAGjC;AACAC,EAAAA,IAAI,EAAE,qBADN;AAEAC,EAAAA,YAAY,EAAE,CACZ,GAAGC,6CADS,EAEZ,GAAGJ,wBAFS,CAFd;AAMAK,EAAAA,MAAM,EAAE;AANR,CAHiC,CAA5B","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport const flingGestureHandlerProps = [\n 'numberOfPointers',\n 'direction',\n] as const;\n\nexport type FlingGestureHandlerEventPayload = {\n x: number;\n y: number;\n absoluteX: number;\n absoluteY: number;\n};\nexport interface FlingGestureConfig {\n /**\n * Expressed allowed direction of movement. It's possible to pass one or many\n * directions in one parameter:\n *\n * ```js\n * direction={Directions.RIGHT | Directions.LEFT}\n * ```\n *\n * or\n *\n * ```js\n * direction={Directions.DOWN}\n * ```\n */\n direction?: number;\n\n /**\n * Determine exact number of points required to handle the fling gesture.\n */\n numberOfPointers?: number;\n}\n\nexport interface FlingGestureHandlerProps\n extends BaseGestureHandlerProps,\n FlingGestureConfig {}\n\nexport type FlingGestureHandler = typeof FlingGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const FlingGestureHandler = createHandler<\n FlingGestureHandlerProps,\n FlingGestureHandlerEventPayload\n>({\n name: 'FlingGestureHandler',\n allowedProps: [\n ...baseGestureHandlerProps,\n ...flingGestureHandlerProps,\n ] as const,\n config: {},\n});\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/ForceTouchGestureHandler.js b/lib/commonjs/handlers/ForceTouchGestureHandler.js new file mode 100644 index 0000000000..220034cae2 --- /dev/null +++ b/lib/commonjs/handlers/ForceTouchGestureHandler.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ForceTouchGestureHandler = exports.forceTouchGestureHandlerProps = void 0; + +var _react = _interopRequireDefault(require("react")); + +var _PlatformConstants = _interopRequireDefault(require("../PlatformConstants")); + +var _createHandler = _interopRequireDefault(require("./createHandler")); + +var _gestureHandlerCommon = require("./gestureHandlerCommon"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +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; } + +const forceTouchGestureHandlerProps = ['minForce', 'maxForce', 'feedbackOnActivation']; +exports.forceTouchGestureHandlerProps = forceTouchGestureHandlerProps; + +class ForceTouchFallback extends _react.default.Component { + componentDidMount() { + console.warn('ForceTouchGestureHandler is not available on this platform. Please use ForceTouchGestureHandler.forceTouchAvailable to conditionally render other components that would provide a fallback behavior specific to your usecase'); + } + + render() { + return this.props.children; + } + +} + +_defineProperty(ForceTouchFallback, "forceTouchAvailable", false); + +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +const ForceTouchGestureHandler = _PlatformConstants.default !== null && _PlatformConstants.default !== void 0 && _PlatformConstants.default.forceTouchAvailable ? (0, _createHandler.default)({ + name: 'ForceTouchGestureHandler', + allowedProps: [..._gestureHandlerCommon.baseGestureHandlerProps, ...forceTouchGestureHandlerProps], + config: {} +}) : ForceTouchFallback; +exports.ForceTouchGestureHandler = ForceTouchGestureHandler; +ForceTouchGestureHandler.forceTouchAvailable = (_PlatformConstants.default === null || _PlatformConstants.default === void 0 ? void 0 : _PlatformConstants.default.forceTouchAvailable) || false; +//# sourceMappingURL=ForceTouchGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/ForceTouchGestureHandler.js.map b/lib/commonjs/handlers/ForceTouchGestureHandler.js.map new file mode 100644 index 0000000000..01f096530e --- /dev/null +++ b/lib/commonjs/handlers/ForceTouchGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["ForceTouchGestureHandler.ts"],"names":["forceTouchGestureHandlerProps","ForceTouchFallback","React","Component","componentDidMount","console","warn","render","props","children","ForceTouchGestureHandler","PlatformConstants","forceTouchAvailable","name","allowedProps","baseGestureHandlerProps","config"],"mappings":";;;;;;;AAAA;;AACA;;AACA;;AACA;;;;;;AAKO,MAAMA,6BAA6B,GAAG,CAC3C,UAD2C,EAE3C,UAF2C,EAG3C,sBAH2C,CAAtC;;;AAMP,MAAMC,kBAAN,SAAiCC,eAAMC,SAAvC,CAAiD;AAE/CC,EAAAA,iBAAiB,GAAG;AAClBC,IAAAA,OAAO,CAACC,IAAR,CACE,8NADF;AAGD;;AACDC,EAAAA,MAAM,GAAG;AACP,WAAO,KAAKC,KAAL,CAAWC,QAAlB;AACD;;AAT8C;;gBAA3CR,kB,yBACyB,K;;AAmD/B;AACO,MAAMS,wBAAwB,GAAGC,2GAAmBC,mBAAnB,GACpC,4BAGE;AACAC,EAAAA,IAAI,EAAE,0BADN;AAEAC,EAAAA,YAAY,EAAE,CACZ,GAAGC,6CADS,EAEZ,GAAGf,6BAFS,CAFd;AAMAgB,EAAAA,MAAM,EAAE;AANR,CAHF,CADoC,GAYpCf,kBAZG;;AAcNS,wBAAD,CAAuDE,mBAAvD,GACE,oHAAmBA,mBAAnB,KAA0C,KAD5C","sourcesContent":["import React from 'react';\nimport PlatformConstants from '../PlatformConstants';\nimport createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport const forceTouchGestureHandlerProps = [\n 'minForce',\n 'maxForce',\n 'feedbackOnActivation',\n] as const;\n\nclass ForceTouchFallback extends React.Component {\n static forceTouchAvailable = false;\n componentDidMount() {\n console.warn(\n 'ForceTouchGestureHandler is not available on this platform. Please use ForceTouchGestureHandler.forceTouchAvailable to conditionally render other components that would provide a fallback behavior specific to your usecase'\n );\n }\n render() {\n return this.props.children;\n }\n}\n\nexport type ForceTouchGestureHandlerEventPayload = {\n x: number;\n y: number;\n absoluteX: number;\n absoluteY: number;\n\n /**\n * The pressure of a touch.\n */\n force: number;\n};\n\nexport interface ForceTouchGestureConfig {\n /**\n *\n * A minimal pressure that is required before handler can activate. Should be a\n * value from range `[0.0, 1.0]`. Default is `0.2`.\n */\n minForce?: number;\n\n /**\n * A maximal pressure that could be applied for handler. If the pressure is\n * greater, handler fails. Should be a value from range `[0.0, 1.0]`.\n */\n maxForce?: number;\n\n /**\n * Boolean value defining if haptic feedback has to be performed on\n * activation.\n */\n feedbackOnActivation?: boolean;\n}\n\nexport interface ForceTouchGestureHandlerProps\n extends BaseGestureHandlerProps,\n ForceTouchGestureConfig {}\n\nexport type ForceTouchGestureHandler = typeof ForceTouchGestureHandler & {\n forceTouchAvailable: boolean;\n};\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const ForceTouchGestureHandler = PlatformConstants?.forceTouchAvailable\n ? createHandler<\n ForceTouchGestureHandlerProps,\n ForceTouchGestureHandlerEventPayload\n >({\n name: 'ForceTouchGestureHandler',\n allowedProps: [\n ...baseGestureHandlerProps,\n ...forceTouchGestureHandlerProps,\n ] as const,\n config: {},\n })\n : ForceTouchFallback;\n\n(ForceTouchGestureHandler as ForceTouchGestureHandler).forceTouchAvailable =\n PlatformConstants?.forceTouchAvailable || false;\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/LongPressGestureHandler.js b/lib/commonjs/handlers/LongPressGestureHandler.js new file mode 100644 index 0000000000..01747a02f1 --- /dev/null +++ b/lib/commonjs/handlers/LongPressGestureHandler.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LongPressGestureHandler = exports.longPressGestureHandlerProps = void 0; + +var _createHandler = _interopRequireDefault(require("./createHandler")); + +var _gestureHandlerCommon = require("./gestureHandlerCommon"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const longPressGestureHandlerProps = ['minDurationMs', 'maxDist']; +exports.longPressGestureHandlerProps = longPressGestureHandlerProps; +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +const LongPressGestureHandler = (0, _createHandler.default)({ + name: 'LongPressGestureHandler', + allowedProps: [..._gestureHandlerCommon.baseGestureHandlerProps, ...longPressGestureHandlerProps], + config: {} +}); +exports.LongPressGestureHandler = LongPressGestureHandler; +//# sourceMappingURL=LongPressGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/LongPressGestureHandler.js.map b/lib/commonjs/handlers/LongPressGestureHandler.js.map new file mode 100644 index 0000000000..96f65bbbbf --- /dev/null +++ b/lib/commonjs/handlers/LongPressGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["LongPressGestureHandler.ts"],"names":["longPressGestureHandlerProps","LongPressGestureHandler","name","allowedProps","baseGestureHandlerProps","config"],"mappings":";;;;;;;AAAA;;AACA;;;;AAKO,MAAMA,4BAA4B,GAAG,CAC1C,eAD0C,EAE1C,SAF0C,CAArC;;AAkEP;AACO,MAAMC,uBAAuB,GAAG,4BAGrC;AACAC,EAAAA,IAAI,EAAE,yBADN;AAEAC,EAAAA,YAAY,EAAE,CACZ,GAAGC,6CADS,EAEZ,GAAGJ,4BAFS,CAFd;AAMAK,EAAAA,MAAM,EAAE;AANR,CAHqC,CAAhC","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport const longPressGestureHandlerProps = [\n 'minDurationMs',\n 'maxDist',\n] as const;\n\nexport type LongPressGestureHandlerEventPayload = {\n /**\n * X coordinate, expressed in points, of the current position of the pointer\n * (finger or a leading pointer when there are multiple fingers placed)\n * relative to the view attached to the handler.\n */\n x: number;\n\n /**\n * Y coordinate, expressed in points, of the current position of the pointer\n * (finger or a leading pointer when there are multiple fingers placed)\n * relative to the view attached to the handler.\n */\n y: number;\n\n /**\n * X coordinate, expressed in points, of the current position of the pointer\n * (finger or a leading pointer when there are multiple fingers placed)\n * relative to the window. It is recommended to use `absoluteX` instead of\n * `x` in cases when the view attached to the handler can be transformed as an\n * effect of the gesture.\n */\n absoluteX: number;\n\n /**\n * Y coordinate, expressed in points, of the current position of the pointer\n * (finger or a leading pointer when there are multiple fingers placed)\n * relative to the window. It is recommended to use `absoluteY` instead of\n * `y` in cases when the view attached to the handler can be transformed as an\n * effect of the gesture.\n */\n absoluteY: number;\n\n /**\n * Duration of the long press (time since the start of the event), expressed\n * in milliseconds.\n */\n duration: number;\n};\n\nexport interface LongPressGestureConfig {\n /**\n * Minimum time, expressed in milliseconds, that a finger must remain pressed on\n * the corresponding view. The default value is 500.\n */\n minDurationMs?: number;\n\n /**\n * Maximum distance, expressed in points, that defines how far the finger is\n * allowed to travel during a long press gesture. If the finger travels\n * further than the defined distance and the handler hasn't yet activated, it\n * will fail to recognize the gesture. The default value is 10.\n */\n maxDist?: number;\n}\n\nexport interface LongPressGestureHandlerProps\n extends BaseGestureHandlerProps,\n LongPressGestureConfig {}\n\nexport type LongPressGestureHandler = typeof LongPressGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const LongPressGestureHandler = createHandler<\n LongPressGestureHandlerProps,\n LongPressGestureHandlerEventPayload\n>({\n name: 'LongPressGestureHandler',\n allowedProps: [\n ...baseGestureHandlerProps,\n ...longPressGestureHandlerProps,\n ] as const,\n config: {},\n});\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/NativeViewGestureHandler.js b/lib/commonjs/handlers/NativeViewGestureHandler.js new file mode 100644 index 0000000000..f3a30de5d9 --- /dev/null +++ b/lib/commonjs/handlers/NativeViewGestureHandler.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NativeViewGestureHandler = exports.nativeViewProps = exports.nativeViewGestureHandlerProps = void 0; + +var _createHandler = _interopRequireDefault(require("./createHandler")); + +var _gestureHandlerCommon = require("./gestureHandlerCommon"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const nativeViewGestureHandlerProps = ['shouldActivateOnStart', 'disallowInterruption']; +exports.nativeViewGestureHandlerProps = nativeViewGestureHandlerProps; +const nativeViewProps = [..._gestureHandlerCommon.baseGestureHandlerProps, ...nativeViewGestureHandlerProps]; +exports.nativeViewProps = nativeViewProps; +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +const NativeViewGestureHandler = (0, _createHandler.default)({ + name: 'NativeViewGestureHandler', + allowedProps: nativeViewProps, + config: {} +}); +exports.NativeViewGestureHandler = NativeViewGestureHandler; +//# sourceMappingURL=NativeViewGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/NativeViewGestureHandler.js.map b/lib/commonjs/handlers/NativeViewGestureHandler.js.map new file mode 100644 index 0000000000..b2eea1ee0f --- /dev/null +++ b/lib/commonjs/handlers/NativeViewGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["NativeViewGestureHandler.ts"],"names":["nativeViewGestureHandlerProps","nativeViewProps","baseGestureHandlerProps","NativeViewGestureHandler","name","allowedProps","config"],"mappings":";;;;;;;AAAA;;AACA;;;;AAKO,MAAMA,6BAA6B,GAAG,CAC3C,uBAD2C,EAE3C,sBAF2C,CAAtC;;AAgCA,MAAMC,eAAe,GAAG,CAC7B,GAAGC,6CAD0B,EAE7B,GAAGF,6BAF0B,CAAxB;;AAMP;AACO,MAAMG,wBAAwB,GAAG,4BAGtC;AACAC,EAAAA,IAAI,EAAE,0BADN;AAEAC,EAAAA,YAAY,EAAEJ,eAFd;AAGAK,EAAAA,MAAM,EAAE;AAHR,CAHsC,CAAjC","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport const nativeViewGestureHandlerProps = [\n 'shouldActivateOnStart',\n 'disallowInterruption',\n] as const;\n\nexport interface NativeViewGestureConfig {\n /**\n * Android only.\n *\n * Determines whether the handler should check for an existing touch event on\n * instantiation.\n */\n shouldActivateOnStart?: boolean;\n\n /**\n * When `true`, cancels all other gesture handlers when this\n * `NativeViewGestureHandler` receives an `ACTIVE` state event.\n */\n disallowInterruption?: boolean;\n}\n\nexport interface NativeViewGestureHandlerProps\n extends BaseGestureHandlerProps,\n NativeViewGestureConfig {}\n\nexport type NativeViewGestureHandlerPayload = {\n /**\n * True if gesture was performed inside of containing view, false otherwise.\n */\n pointerInside: boolean;\n};\n\nexport const nativeViewProps = [\n ...baseGestureHandlerProps,\n ...nativeViewGestureHandlerProps,\n] as const;\n\nexport type NativeViewGestureHandler = typeof NativeViewGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const NativeViewGestureHandler = createHandler<\n NativeViewGestureHandlerProps,\n NativeViewGestureHandlerPayload\n>({\n name: 'NativeViewGestureHandler',\n allowedProps: nativeViewProps,\n config: {},\n});\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/PanGestureHandler.js b/lib/commonjs/handlers/PanGestureHandler.js new file mode 100644 index 0000000000..b4bb5fbe80 --- /dev/null +++ b/lib/commonjs/handlers/PanGestureHandler.js @@ -0,0 +1,121 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.managePanProps = managePanProps; +exports.PanGestureHandler = exports.panGestureHandlerCustomNativeProps = exports.panGestureHandlerProps = void 0; + +var _createHandler = _interopRequireDefault(require("./createHandler")); + +var _gestureHandlerCommon = require("./gestureHandlerCommon"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const panGestureHandlerProps = ['activeOffsetY', 'activeOffsetX', 'failOffsetY', 'failOffsetX', 'minDist', 'minVelocity', 'minVelocityX', 'minVelocityY', 'minPointers', 'maxPointers', 'avgTouches', 'enableTrackpadTwoFingerGesture']; +exports.panGestureHandlerProps = panGestureHandlerProps; +const panGestureHandlerCustomNativeProps = ['activeOffsetYStart', 'activeOffsetYEnd', 'activeOffsetXStart', 'activeOffsetXEnd', 'failOffsetYStart', 'failOffsetYEnd', 'failOffsetXStart', 'failOffsetXEnd']; +exports.panGestureHandlerCustomNativeProps = panGestureHandlerCustomNativeProps; +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +const PanGestureHandler = (0, _createHandler.default)({ + name: 'PanGestureHandler', + allowedProps: [..._gestureHandlerCommon.baseGestureHandlerProps, ...panGestureHandlerProps], + config: {}, + transformProps: managePanProps, + customNativeProps: panGestureHandlerCustomNativeProps +}); +exports.PanGestureHandler = PanGestureHandler; + +function validatePanGestureHandlerProps(props) { + if (Array.isArray(props.activeOffsetX) && (props.activeOffsetX[0] > 0 || props.activeOffsetX[1] < 0)) { + throw new Error(`First element of activeOffsetX should be negative, a the second one should be positive`); + } + + if (Array.isArray(props.activeOffsetY) && (props.activeOffsetY[0] > 0 || props.activeOffsetY[1] < 0)) { + throw new Error(`First element of activeOffsetY should be negative, a the second one should be positive`); + } + + if (Array.isArray(props.failOffsetX) && (props.failOffsetX[0] > 0 || props.failOffsetX[1] < 0)) { + throw new Error(`First element of failOffsetX should be negative, a the second one should be positive`); + } + + if (Array.isArray(props.failOffsetY) && (props.failOffsetY[0] > 0 || props.failOffsetY[1] < 0)) { + throw new Error(`First element of failOffsetY should be negative, a the second one should be positive`); + } + + if (props.minDist && (props.failOffsetX || props.failOffsetY)) { + throw new Error(`It is not supported to use minDist with failOffsetX or failOffsetY, use activeOffsetX and activeOffsetY instead`); + } + + if (props.minDist && (props.activeOffsetX || props.activeOffsetY)) { + throw new Error(`It is not supported to use minDist with activeOffsetX or activeOffsetY`); + } +} + +function transformPanGestureHandlerProps(props) { + const res = { ...props + }; + + if (props.activeOffsetX !== undefined) { + delete res.activeOffsetX; + + if (Array.isArray(props.activeOffsetX)) { + res.activeOffsetXStart = props.activeOffsetX[0]; + res.activeOffsetXEnd = props.activeOffsetX[1]; + } else if (props.activeOffsetX < 0) { + res.activeOffsetXStart = props.activeOffsetX; + } else { + res.activeOffsetXEnd = props.activeOffsetX; + } + } + + if (props.activeOffsetY !== undefined) { + delete res.activeOffsetY; + + if (Array.isArray(props.activeOffsetY)) { + res.activeOffsetYStart = props.activeOffsetY[0]; + res.activeOffsetYEnd = props.activeOffsetY[1]; + } else if (props.activeOffsetY < 0) { + res.activeOffsetYStart = props.activeOffsetY; + } else { + res.activeOffsetYEnd = props.activeOffsetY; + } + } + + if (props.failOffsetX !== undefined) { + delete res.failOffsetX; + + if (Array.isArray(props.failOffsetX)) { + res.failOffsetXStart = props.failOffsetX[0]; + res.failOffsetXEnd = props.failOffsetX[1]; + } else if (props.failOffsetX < 0) { + res.failOffsetXStart = props.failOffsetX; + } else { + res.failOffsetXEnd = props.failOffsetX; + } + } + + if (props.failOffsetY !== undefined) { + delete res.failOffsetY; + + if (Array.isArray(props.failOffsetY)) { + res.failOffsetYStart = props.failOffsetY[0]; + res.failOffsetYEnd = props.failOffsetY[1]; + } else if (props.failOffsetY < 0) { + res.failOffsetYStart = props.failOffsetY; + } else { + res.failOffsetYEnd = props.failOffsetY; + } + } + + return res; +} + +function managePanProps(props) { + if (__DEV__) { + validatePanGestureHandlerProps(props); + } + + return transformPanGestureHandlerProps(props); +} +//# sourceMappingURL=PanGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/PanGestureHandler.js.map b/lib/commonjs/handlers/PanGestureHandler.js.map new file mode 100644 index 0000000000..c6bf45736e --- /dev/null +++ b/lib/commonjs/handlers/PanGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PanGestureHandler.ts"],"names":["panGestureHandlerProps","panGestureHandlerCustomNativeProps","PanGestureHandler","name","allowedProps","baseGestureHandlerProps","config","transformProps","managePanProps","customNativeProps","validatePanGestureHandlerProps","props","Array","isArray","activeOffsetX","Error","activeOffsetY","failOffsetX","failOffsetY","minDist","transformPanGestureHandlerProps","res","undefined","activeOffsetXStart","activeOffsetXEnd","activeOffsetYStart","activeOffsetYEnd","failOffsetXStart","failOffsetXEnd","failOffsetYStart","failOffsetYEnd","__DEV__"],"mappings":";;;;;;;;AAAA;;AACA;;;;AAKO,MAAMA,sBAAsB,GAAG,CACpC,eADoC,EAEpC,eAFoC,EAGpC,aAHoC,EAIpC,aAJoC,EAKpC,SALoC,E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AvB;AACAG,MAAAA,GAAG,CAACS,cAAJ,GAAqBnB,KAAK,CAACO,WAAN,CAAkB,CAAlB,CAArB;AACD,KAHD,MAGO,IAAIP,KAAK,CAACO,WAAN,GAAoB,CAAxB,EAA2B;AAChCG,MAAAA,GAAG,CAACQ,gBAAJ,GAAuBlB,KAAK,CAACO,WAA7B;AACD,KAFM,MAEA;AACLG,MAAAA,GAAG,CAACS,cAAJ,GAAqBnB,KAAK,CAACO,WAA3B;AACD;AACF;;AAED,SAAOG,GAAP;AACD;;AAEM,SAASb,cAAT,CAAwBG,KAAxB,EAAuD;AAC5D,MAAIoB,OAAJ,EAAa;AACXrB,IAAAA,8BAA8B,CAACC,KAAD,CAA9B;AACD;;AACD,SAAOS,+BAA+B,CAACT,KAAD,CAAtC;AACD","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport const panGestureHandlerProps = [\n 'activeOffsetY',\n 'activeOffsetX',\n 'failOffsetY',\n 'failOffsetX',\n 'minDist',\n 'minVelocity',\n 'minVelocityX',\n 'minVelocityY',\n 'minPointers',\n 'maxPointers',\n 'avgTouches',\n 'enableTrackpadTwoFingerGesture',\n] as const;\n\nexport const panGestureHandlerCustomNativeProps = [\n 'activeOffsetYStart',\n 'activeOffsetYEnd',\n 'activeOffsetXStart',\n 'activeOffsetXEnd',\n 'failOffsetYStart',\n 'failOffsetYEnd',\n 'failOffsetXStart',\n 'failOffsetXEnd',\n] as const;\n\nexport type PanGestureHandlerEventPayload = {\n /**\n * X coordinate of the current position of the pointer (finger or a leading\n * pointer when there are multiple fingers placed) relative to the view\n * attached to the handler. Expressed in point units.\n */\n x: number;\n\n /**\n * Y coordinate of the current position of the pointer (finger or a leading\n * pointer when there are multiple fingers placed) relative to the view\n * attached to the handler. Expressed in point units.\n */\n y: number;\n\n /**\n * X coordinate of the current position of the pointer (finger or a leading\n * pointer when there are multiple fingers placed) relative to the window.\n * The value is expressed in point units. It is recommended to use it instead\n * of `x` in cases when the original view can be transformed as an effect of\n * the gesture.\n */\n absoluteX: number;\n\n /**\n * Y coordinate of the current position of the pointer (finger or a leading\n * pointer when there are multiple fingers placed) relative to the window.\n * The value is expressed in point units. It is recommended to use it instead\n * of `y` in cases when the original view can be transformed as an\n * effect of the gesture.\n */\n absoluteY: number;\n\n /**\n * Translation of the pan gesture along X axis accumulated over the time of\n * the gesture. The value is expressed in the point units.\n */\n translationX: number;\n\n /**\n * Translation of the pan gesture along Y axis accumulated over the time of\n * the gesture. The value is expressed in the point units.\n */\n translationY: number;\n\n /**\n * Velocity of the pan gesture along the X axis in the current moment. The\n * value is expressed in point units per second.\n */\n velocityX: number;\n\n /**\n * Velocity of the pan gesture along the Y axis in the current moment. The\n * value is expressed in point units per second.\n */\n velocityY: number;\n};\n\ninterface CommonPanProperties {\n /**\n * Minimum distance the finger (or multiple finger) need to travel before the\n * handler activates. Expressed in points.\n */\n minDist?: number;\n\n /**\n * Android only.\n */\n avgTouches?: boolean;\n\n /**\n * Enables two-finger gestures on supported devices, for example iPads with\n * trackpads. If not enabled the gesture will require click + drag, with\n * enableTrackpadTwoFingerGesture swiping with two fingers will also trigger\n * the gesture.\n */\n enableTrackpadTwoFingerGesture?: boolean;\n\n /**\n * A number of fingers that is required to be placed before handler can\n * activate. Should be a higher or equal to 0 integer.\n */\n minPointers?: number;\n\n /**\n * When the given number of fingers is placed on the screen and handler hasn't\n * yet activated it will fail recognizing the gesture. Should be a higher or\n * equal to 0 integer.\n */\n maxPointers?: number;\n\n minVelocity?: number;\n minVelocityX?: number;\n minVelocityY?: number;\n}\n\nexport interface PanGestureConfig extends CommonPanProperties {\n activeOffsetYStart?: number;\n activeOffsetYEnd?: number;\n activeOffsetXStart?: number;\n activeOffsetXEnd?: number;\n failOffsetYStart?: number;\n failOffsetYEnd?: number;\n failOffsetXStart?: number;\n failOffsetXEnd?: number;\n}\n\nexport interface PanGestureHandlerProps\n extends BaseGestureHandlerProps,\n CommonPanProperties {\n /**\n * Range along X axis (in points) where fingers travels without activation of\n * handler. Moving outside of this range implies activation of handler. Range\n * can be given as an array or a single number. If range is set as an array,\n * first value must be lower or equal to 0, a the second one higher or equal\n * to 0. If only one number `p` is given a range of `(-inf, p)` will be used\n * if `p` is higher or equal to 0 and `(-p, inf)` otherwise.\n */\n activeOffsetY?: number | number[];\n\n /**\n * Range along X axis (in points) where fingers travels without activation of\n * handler. Moving outside of this range implies activation of handler. Range\n * can be given as an array or a single number. If range is set as an array,\n * first value must be lower or equal to 0, a the second one higher or equal\n * to 0. If only one number `p` is given a range of `(-inf, p)` will be used\n * if `p` is higher or equal to 0 and `(-p, inf)` otherwise.\n */\n activeOffsetX?: number | number[];\n\n /**\n * When the finger moves outside this range (in points) along Y axis and\n * handler hasn't yet activated it will fail recognizing the gesture. Range\n * can be given as an array or a single number. If range is set as an array,\n * first value must be lower or equal to 0, a the second one higher or equal\n * to 0. If only one number `p` is given a range of `(-inf, p)` will be used\n * if `p` is higher or equal to 0 and `(-p, inf)` otherwise.\n */\n failOffsetY?: number | number[];\n\n /**\n * When the finger moves outside this range (in points) along X axis and\n * handler hasn't yet activated it will fail recognizing the gesture. Range\n * can be given as an array or a single number. If range is set as an array,\n * first value must be lower or equal to 0, a the second one higher or equal\n * to 0. If only one number `p` is given a range of `(-inf, p)` will be used\n * if `p` is higher or equal to 0 and `(-p, inf)` otherwise.\n */\n failOffsetX?: number | number[];\n}\n\nexport type PanGestureHandler = typeof PanGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const PanGestureHandler = createHandler<\n PanGestureHandlerProps,\n PanGestureHandlerEventPayload\n>({\n name: 'PanGestureHandler',\n allowedProps: [\n ...baseGestureHandlerProps,\n ...panGestureHandlerProps,\n ] as const,\n config: {},\n transformProps: managePanProps,\n customNativeProps: panGestureHandlerCustomNativeProps,\n});\n\nfunction validatePanGestureHandlerProps(props: PanGestureHandlerProps) {\n if (\n Array.isArray(props.activeOffsetX) &&\n (props.activeOffsetX[0] > 0 || props.activeOffsetX[1] < 0)\n ) {\n throw new Error(\n `First element of activeOffsetX should be negative, a the second one should be positive`\n );\n }\n\n if (\n Array.isArray(props.activeOffsetY) &&\n (props.activeOffsetY[0] > 0 || props.activeOffsetY[1] < 0)\n ) {\n throw new Error(\n `First element of activeOffsetY should be negative, a the second one should be positive`\n );\n }\n\n if (\n Array.isArray(props.failOffsetX) &&\n (props.failOffsetX[0] > 0 || props.failOffsetX[1] < 0)\n ) {\n throw new Error(\n `First element of failOffsetX should be negative, a the second one should be positive`\n );\n }\n\n if (\n Array.isArray(props.failOffsetY) &&\n (props.failOffsetY[0] > 0 || props.failOffsetY[1] < 0)\n ) {\n throw new Error(\n `First element of failOffsetY should be negative, a the second one should be positive`\n );\n }\n\n if (props.minDist && (props.failOffsetX || props.failOffsetY)) {\n throw new Error(\n `It is not supported to use minDist with failOffsetX or failOffsetY, use activeOffsetX and activeOffsetY instead`\n );\n }\n\n if (props.minDist && (props.activeOffsetX || props.activeOffsetY)) {\n throw new Error(\n `It is not supported to use minDist with activeOffsetX or activeOffsetY`\n );\n }\n}\n\nfunction transformPanGestureHandlerProps(props: PanGestureHandlerProps) {\n type InternalPanGHKeys =\n | 'activeOffsetXStart'\n | 'activeOffsetXEnd'\n | 'failOffsetXStart'\n | 'failOffsetXEnd'\n | 'activeOffsetYStart'\n | 'activeOffsetYEnd'\n | 'failOffsetYStart'\n | 'failOffsetYEnd';\n type PanGestureHandlerInternalProps = PanGestureHandlerProps &\n Partial>;\n\n const res: PanGestureHandlerInternalProps = { ...props };\n\n if (props.activeOffsetX !== undefined) {\n delete res.activeOffsetX;\n if (Array.isArray(props.activeOffsetX)) {\n res.activeOffsetXStart = props.activeOffsetX[0];\n res.activeOffsetXEnd = props.activeOffsetX[1];\n } else if (props.activeOffsetX < 0) {\n res.activeOffsetXStart = props.activeOffsetX;\n } else {\n res.activeOffsetXEnd = props.activeOffsetX;\n }\n }\n\n if (props.activeOffsetY !== undefined) {\n delete res.activeOffsetY;\n if (Array.isArray(props.activeOffsetY)) {\n res.activeOffsetYStart = props.activeOffsetY[0];\n res.activeOffsetYEnd = props.activeOffsetY[1];\n } else if (props.activeOffsetY < 0) {\n res.activeOffsetYStart = props.activeOffsetY;\n } else {\n res.activeOffsetYEnd = props.activeOffsetY;\n }\n }\n\n if (props.failOffsetX !== undefined) {\n delete res.failOffsetX;\n if (Array.isArray(props.failOffsetX)) {\n res.failOffsetXStart = props.failOffsetX[0];\n res.failOffsetXEnd = props.failOffsetX[1];\n } else if (props.failOffsetX < 0) {\n res.failOffsetXStart = props.failOffsetX;\n } else {\n res.failOffsetXEnd = props.failOffsetX;\n }\n }\n\n if (props.failOffsetY !== undefined) {\n delete res.failOffsetY;\n if (Array.isArray(props.failOffsetY)) {\n res.failOffsetYStart = props.failOffsetY[0];\n res.failOffsetYEnd = props.failOffsetY[1];\n } else if (props.failOffsetY < 0) {\n res.failOffsetYStart = props.failOffsetY;\n } else {\n res.failOffsetYEnd = props.failOffsetY;\n }\n }\n\n return res;\n}\n\nexport function managePanProps(props: PanGestureHandlerProps) {\n if (__DEV__) {\n validatePanGestureHandlerProps(props);\n }\n return transformPanGestureHandlerProps(props);\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/PinchGestureHandler.js b/lib/commonjs/handlers/PinchGestureHandler.js new file mode 100644 index 0000000000..d11d596f7a --- /dev/null +++ b/lib/commonjs/handlers/PinchGestureHandler.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PinchGestureHandler = void 0; + +var _createHandler = _interopRequireDefault(require("./createHandler")); + +var _gestureHandlerCommon = require("./gestureHandlerCommon"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +const PinchGestureHandler = (0, _createHandler.default)({ + name: 'PinchGestureHandler', + allowedProps: _gestureHandlerCommon.baseGestureHandlerProps, + config: {} +}); +exports.PinchGestureHandler = PinchGestureHandler; +//# sourceMappingURL=PinchGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/PinchGestureHandler.js.map b/lib/commonjs/handlers/PinchGestureHandler.js.map new file mode 100644 index 0000000000..c0390e5f41 --- /dev/null +++ b/lib/commonjs/handlers/PinchGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PinchGestureHandler.ts"],"names":["PinchGestureHandler","name","allowedProps","baseGestureHandlerProps","config"],"mappings":";;;;;;;AAAA;;AACA;;;;AAoCA;AACO,MAAMA,mBAAmB,GAAG,4BAGjC;AACAC,EAAAA,IAAI,EAAE,qBADN;AAEAC,EAAAA,YAAY,EAAEC,6CAFd;AAGAC,EAAAA,MAAM,EAAE;AAHR,CAHiC,CAA5B","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport type PinchGestureHandlerEventPayload = {\n /**\n * The scale factor relative to the points of the two touches in screen\n * coordinates.\n */\n scale: number;\n\n /**\n * Position expressed in points along X axis of center anchor point of\n * gesture.\n */\n focalX: number;\n\n /**\n * Position expressed in points along Y axis of center anchor point of\n * gesture.\n */\n focalY: number;\n\n /**\n *\n * Velocity of the pan gesture the current moment. The value is expressed in\n * point units per second.\n */\n velocity: number;\n};\n\nexport interface PinchGestureHandlerProps\n extends BaseGestureHandlerProps {}\n\nexport type PinchGestureHandler = typeof PinchGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const PinchGestureHandler = createHandler<\n PinchGestureHandlerProps,\n PinchGestureHandlerEventPayload\n>({\n name: 'PinchGestureHandler',\n allowedProps: baseGestureHandlerProps,\n config: {},\n});\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/RotationGestureHandler.js b/lib/commonjs/handlers/RotationGestureHandler.js new file mode 100644 index 0000000000..60f8e35ebd --- /dev/null +++ b/lib/commonjs/handlers/RotationGestureHandler.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RotationGestureHandler = void 0; + +var _createHandler = _interopRequireDefault(require("./createHandler")); + +var _gestureHandlerCommon = require("./gestureHandlerCommon"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +const RotationGestureHandler = (0, _createHandler.default)({ + name: 'RotationGestureHandler', + allowedProps: _gestureHandlerCommon.baseGestureHandlerProps, + config: {} +}); +exports.RotationGestureHandler = RotationGestureHandler; +//# sourceMappingURL=RotationGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/RotationGestureHandler.js.map b/lib/commonjs/handlers/RotationGestureHandler.js.map new file mode 100644 index 0000000000..5e76ef56b1 --- /dev/null +++ b/lib/commonjs/handlers/RotationGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["RotationGestureHandler.ts"],"names":["RotationGestureHandler","name","allowedProps","baseGestureHandlerProps","config"],"mappings":";;;;;;;AAAA;;AACA;;;;AAoCA;AACO,MAAMA,sBAAsB,GAAG,4BAGpC;AACAC,EAAAA,IAAI,EAAE,wBADN;AAEAC,EAAAA,YAAY,EAAEC,6CAFd;AAGAC,EAAAA,MAAM,EAAE;AAHR,CAHoC,CAA/B","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport type RotationGestureHandlerEventPayload = {\n /**\n * Amount rotated, expressed in radians, from the gesture's focal point\n * (anchor).\n */\n rotation: number;\n\n /**\n * X coordinate, expressed in points, of the gesture's central focal point\n * (anchor).\n */\n anchorX: number;\n\n /**\n * Y coordinate, expressed in points, of the gesture's central focal point\n * (anchor).\n */\n anchorY: number;\n\n /**\n *\n * Instantaneous velocity, expressed in point units per second, of the\n * gesture.\n */\n velocity: number;\n};\n\nexport interface RotationGestureHandlerProps\n extends BaseGestureHandlerProps {}\n\nexport type RotationGestureHandler = typeof RotationGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const RotationGestureHandler = createHandler<\n RotationGestureHandlerProps,\n RotationGestureHandlerEventPayload\n>({\n name: 'RotationGestureHandler',\n allowedProps: baseGestureHandlerProps,\n config: {},\n});\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/TapGestureHandler.js b/lib/commonjs/handlers/TapGestureHandler.js new file mode 100644 index 0000000000..2695e85cd3 --- /dev/null +++ b/lib/commonjs/handlers/TapGestureHandler.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TapGestureHandler = exports.tapGestureHandlerProps = void 0; + +var _createHandler = _interopRequireDefault(require("./createHandler")); + +var _gestureHandlerCommon = require("./gestureHandlerCommon"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const tapGestureHandlerProps = ['maxDurationMs', 'maxDelayMs', 'numberOfTaps', 'maxDeltaX', 'maxDeltaY', 'maxDist', 'minPointers']; +exports.tapGestureHandlerProps = tapGestureHandlerProps; +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +const TapGestureHandler = (0, _createHandler.default)({ + name: 'TapGestureHandler', + allowedProps: [..._gestureHandlerCommon.baseGestureHandlerProps, ...tapGestureHandlerProps], + config: {} +}); +exports.TapGestureHandler = TapGestureHandler; +//# sourceMappingURL=TapGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/TapGestureHandler.js.map b/lib/commonjs/handlers/TapGestureHandler.js.map new file mode 100644 index 0000000000..5b05052ab5 --- /dev/null +++ b/lib/commonjs/handlers/TapGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TapGestureHandler.ts"],"names":["tapGestureHandlerProps","TapGestureHandler","name","allowedProps","baseGestureHandlerProps","config"],"mappings":";;;;;;;AAAA;;AACA;;;;AAKO,MAAMA,sBAAsB,GAAG,CACpC,eADoC,EAEpC,YAFoC,EAGpC,cAHoC,EAIpC,WAJoC,EAKpC,WALoC,EAMpC,SANoC,EAOpC,aAPoC,CAA/B;;AAwEP;AACO,MAAMC,iBAAiB,GAAG,4BAG/B;AACAC,EAAAA,IAAI,EAAE,mBADN;AAEAC,EAAAA,YAAY,EAAE,CACZ,GAAGC,6CADS,EAEZ,GAAGJ,sBAFS,CAFd;AAMAK,EAAAA,MAAM,EAAE;AANR,CAH+B,CAA1B","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport const tapGestureHandlerProps = [\n 'maxDurationMs',\n 'maxDelayMs',\n 'numberOfTaps',\n 'maxDeltaX',\n 'maxDeltaY',\n 'maxDist',\n 'minPointers',\n] as const;\n\nexport type TapGestureHandlerEventPayload = {\n x: number;\n y: number;\n absoluteX: number;\n absoluteY: number;\n};\nexport interface TapGestureConfig {\n /**\n * Minimum number of pointers (fingers) required to be placed before the\n * handler activates. Should be a positive integer.\n * The default value is 1.\n */\n minPointers?: number;\n\n /**\n * Maximum time, expressed in milliseconds, that defines how fast a finger\n * must be released after a touch. The default value is 500.\n */\n maxDurationMs?: number;\n\n /**\n * Maximum time, expressed in milliseconds, that can pass before the next tap\n * if many taps are required. The default value is 500.\n */\n maxDelayMs?: number;\n\n /**\n * Number of tap gestures required to activate the handler. The default value\n * is 1.\n */\n numberOfTaps?: number;\n\n /**\n * Maximum distance, expressed in points, that defines how far the finger is\n * allowed to travel along the X axis during a tap gesture. If the finger\n * travels further than the defined distance along the X axis and the handler\n * hasn't yet activated, it will fail to recognize the gesture.\n */\n maxDeltaX?: number;\n\n /**\n * Maximum distance, expressed in points, that defines how far the finger is\n * allowed to travel along the Y axis during a tap gesture. If the finger\n * travels further than the defined distance along the Y axis and the handler\n * hasn't yet activated, it will fail to recognize the gesture.\n */\n maxDeltaY?: number;\n\n /**\n * Maximum distance, expressed in points, that defines how far the finger is\n * allowed to travel during a tap gesture. If the finger travels further than\n * the defined distance and the handler hasn't yet\n * activated, it will fail to recognize the gesture.\n */\n maxDist?: number;\n}\n\nexport interface TapGestureHandlerProps\n extends BaseGestureHandlerProps,\n TapGestureConfig {}\n\nexport type TapGestureHandler = typeof TapGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const TapGestureHandler = createHandler<\n TapGestureHandlerProps,\n TapGestureHandlerEventPayload\n>({\n name: 'TapGestureHandler',\n allowedProps: [\n ...baseGestureHandlerProps,\n ...tapGestureHandlerProps,\n ] as const,\n config: {},\n});\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/createHandler.js b/lib/commonjs/handlers/createHandler.js new file mode 100644 index 0000000000..cdcec8975e --- /dev/null +++ b/lib/commonjs/handlers/createHandler.js @@ -0,0 +1,385 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = createHandler; + +var React = _interopRequireWildcard(require("react")); + +var _reactNative = require("react-native"); + +var _isEqual = _interopRequireDefault(require("lodash/isEqual")); + +var _RNGestureHandlerModule = _interopRequireDefault(require("../RNGestureHandlerModule")); + +var _State = require("../State"); + +var _handlersRegistry = require("./handlersRegistry"); + +var _gestureHandlerCommon = require("./gestureHandlerCommon"); + +var _UIManagerAny$getView, _UIManagerAny$getView2, _UIManagerAny$getCons; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +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; } + +const UIManagerAny = _reactNative.UIManager; +const customGHEventsConfig = { + onGestureHandlerEvent: { + registrationName: 'onGestureHandlerEvent' + }, + onGestureHandlerStateChange: { + registrationName: 'onGestureHandlerStateChange' + } +}; // Add gesture specific events to genericDirectEventTypes object exported from UIManager +// native module. +// Once new event types are registered with react it is possible to dispatch these +// events to all kind of native views. + +UIManagerAny.genericDirectEventTypes = { ...UIManagerAny.genericDirectEventTypes, + ...customGHEventsConfig +}; // In newer versions of RN the `genericDirectEventTypes` is located in the object +// returned by UIManager.getViewManagerConfig('getConstants') or in older RN UIManager.getConstants(), we need to add it there as well to make +// it compatible with RN 61+ + +const UIManagerConstants = (_UIManagerAny$getView = (_UIManagerAny$getView2 = UIManagerAny.getViewManagerConfig) === null || _UIManagerAny$getView2 === void 0 ? void 0 : _UIManagerAny$getView2.call(UIManagerAny, 'getConstants')) !== null && _UIManagerAny$getView !== void 0 ? _UIManagerAny$getView : (_UIManagerAny$getCons = UIManagerAny.getConstants) === null || _UIManagerAny$getCons === void 0 ? void 0 : _UIManagerAny$getCons.call(UIManagerAny); + +if (UIManagerConstants) { + UIManagerConstants.genericDirectEventTypes = { ...UIManagerConstants.genericDirectEventTypes, + ...customGHEventsConfig + }; +} // Wrap JS responder calls and notify gesture handler manager + + +const { + setJSResponder: oldSetJSResponder = () => {//no operation + }, + clearJSResponder: oldClearJSResponder = () => {//no operation + } +} = UIManagerAny; + +UIManagerAny.setJSResponder = (tag, blockNativeResponder) => { + _RNGestureHandlerModule.default.handleSetJSResponder(tag, blockNativeResponder); + + oldSetJSResponder(tag, blockNativeResponder); +}; + +UIManagerAny.clearJSResponder = () => { + _RNGestureHandlerModule.default.handleClearJSResponder(); + + oldClearJSResponder(); +}; + +let allowTouches = true; +const DEV_ON_ANDROID = __DEV__ && _reactNative.Platform.OS === 'android'; // Toggled inspector blocks touch events in order to allow inspecting on Android +// This needs to be a global variable in order to set initial state for `allowTouches` property in Handler component + +if (DEV_ON_ANDROID) { + _reactNative.DeviceEventEmitter.addListener('toggleElementInspector', () => { + allowTouches = !allowTouches; + }); +} + +function hasUnresolvedRefs(props) { + // TODO(TS) - add type for extract arg + const extract = refs => { + if (!Array.isArray(refs)) { + return refs && refs.current === null; + } + + return refs.some(r => r && r.current === null); + }; + + return extract(props['simultaneousHandlers']) || extract(props['waitFor']); +} + +const stateToPropMappings = { + [_State.State.UNDETERMINED]: undefined, + [_State.State.BEGAN]: 'onBegan', + [_State.State.FAILED]: 'onFailed', + [_State.State.CANCELLED]: 'onCancelled', + [_State.State.ACTIVE]: 'onActivated', + [_State.State.END]: 'onEnded' +}; +let showedRngh2Notice = false; + +function showRngh2NoticeIfNeeded() { + if (!showedRngh2Notice) { + console.warn("[react-native-gesture-handler] Seems like you're using an old API with gesture components, check out new Gestures system!"); + showedRngh2Notice = true; + } +} // TODO(TS) - make sure that BaseGestureHandlerProps doesn't need other generic parameter to work with custom properties. + + +function createHandler({ + name, + allowedProps = [], + config = {}, + transformProps, + customNativeProps = [] +}) { + class Handler extends React.Component { + constructor(props) { + super(props); + + _defineProperty(this, "handlerTag", void 0); + + _defineProperty(this, "config", void 0); + + _defineProperty(this, "propsRef", void 0); + + _defineProperty(this, "viewNode", void 0); + + _defineProperty(this, "viewTag", void 0); + + _defineProperty(this, "updateEnqueued", null); + + _defineProperty(this, "inspectorToggleListener", void 0); + + _defineProperty(this, "onGestureHandlerEvent", event => { + if (event.nativeEvent.handlerTag === this.handlerTag) { + var _this$props$onGesture, _this$props; + + (_this$props$onGesture = (_this$props = this.props).onGestureEvent) === null || _this$props$onGesture === void 0 ? void 0 : _this$props$onGesture.call(_this$props, event); + } else { + var _this$props$onGesture2, _this$props2; + + (_this$props$onGesture2 = (_this$props2 = this.props).onGestureHandlerEvent) === null || _this$props$onGesture2 === void 0 ? void 0 : _this$props$onGesture2.call(_this$props2, event); + } + }); + + _defineProperty(this, "onGestureHandlerStateChange", event => { + if (event.nativeEvent.handlerTag === this.handlerTag) { + var _this$props$onHandler, _this$props3; + + (_this$props$onHandler = (_this$props3 = this.props).onHandlerStateChange) === null || _this$props$onHandler === void 0 ? void 0 : _this$props$onHandler.call(_this$props3, event); + const state = event.nativeEvent.state; + const stateEventName = stateToPropMappings[state]; + const eventHandler = stateEventName && this.props[stateEventName]; + + if (eventHandler && typeof eventHandler === 'function') { + eventHandler(event); + } + } else { + var _this$props$onGesture3, _this$props4; + + (_this$props$onGesture3 = (_this$props4 = this.props).onGestureHandlerStateChange) === null || _this$props$onGesture3 === void 0 ? void 0 : _this$props$onGesture3.call(_this$props4, event); + } + }); + + _defineProperty(this, "refHandler", node => { + this.viewNode = node; + const child = React.Children.only(this.props.children); // TODO(TS) fix ref type + + const { + ref + } = child; + + if (ref !== null) { + if (typeof ref === 'function') { + ref(node); + } else { + ref.current = node; + } + } + }); + + _defineProperty(this, "createGestureHandler", newConfig => { + this.config = newConfig; + + _RNGestureHandlerModule.default.createGestureHandler(name, this.handlerTag, newConfig); + }); + + _defineProperty(this, "attachGestureHandler", newViewTag => { + this.viewTag = newViewTag; + + if (_reactNative.Platform.OS === 'web') { + // typecast due to dynamic resolution, attachGestureHandler should have web version signature in this branch + _RNGestureHandlerModule.default.attachGestureHandler(this.handlerTag, newViewTag, false, this.propsRef); + } else { + _RNGestureHandlerModule.default.attachGestureHandler(this.handlerTag, newViewTag, false); + } + }); + + _defineProperty(this, "updateGestureHandler", newConfig => { + this.config = newConfig; + + _RNGestureHandlerModule.default.updateGestureHandler(this.handlerTag, newConfig); + }); + + this.handlerTag = (0, _handlersRegistry.getNextHandlerTag)(); + this.config = {}; + this.propsRef = /*#__PURE__*/React.createRef(); + this.state = { + allowTouches + }; + + if (props.id) { + if (_handlersRegistry.handlerIDToTag[props.id] !== undefined) { + throw new Error(`Handler with ID "${props.id}" already registered`); + } + + _handlersRegistry.handlerIDToTag[props.id] = this.handlerTag; + } + + if (__DEV__) { + showRngh2NoticeIfNeeded(); + } + } + + componentDidMount() { + const props = this.props; + + if (DEV_ON_ANDROID) { + this.inspectorToggleListener = _reactNative.DeviceEventEmitter.addListener('toggleElementInspector', () => { + this.setState(_ => ({ + allowTouches + })); + this.update(); + }); + } + + if (hasUnresolvedRefs(props)) { + // If there are unresolved refs (e.g. ".current" has not yet been set) + // passed as `simultaneousHandlers` or `waitFor`, we enqueue a call to + // _update method that will try to update native handler props using + // setImmediate. This makes it so update() function gets called after all + // react components are mounted and we expect the missing ref object to + // be resolved by then. + this.updateEnqueued = setImmediate(() => { + this.updateEnqueued = null; + this.update(); + }); + } + + this.createGestureHandler((0, _gestureHandlerCommon.filterConfig)(transformProps ? transformProps(this.props) : this.props, [...allowedProps, ...customNativeProps], config)); + this.attachGestureHandler((0, _gestureHandlerCommon.findNodeHandle)(this.viewNode)); // TODO(TS) - check if this can be null + } + + componentDidUpdate() { + const viewTag = (0, _gestureHandlerCommon.findNodeHandle)(this.viewNode); + + if (this.viewTag !== viewTag) { + this.attachGestureHandler(viewTag); // TODO(TS) - check interaction between _viewTag & findNodeHandle + } + + this.update(); + } + + componentWillUnmount() { + var _this$inspectorToggle; + + (_this$inspectorToggle = this.inspectorToggleListener) === null || _this$inspectorToggle === void 0 ? void 0 : _this$inspectorToggle.remove(); + + _RNGestureHandlerModule.default.dropGestureHandler(this.handlerTag); + + if (this.updateEnqueued) { + clearImmediate(this.updateEnqueued); + } // We can't use this.props.id directly due to TS generic type narrowing bug, see https://github.com/microsoft/TypeScript/issues/13995 for more context + + + const handlerID = this.props.id; + + if (handlerID) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete _handlersRegistry.handlerIDToTag[handlerID]; + } + } + + update() { + const newConfig = (0, _gestureHandlerCommon.filterConfig)(transformProps ? transformProps(this.props) : this.props, [...allowedProps, ...customNativeProps], config); + + if (!(0, _isEqual.default)(this.config, newConfig)) { + this.updateGestureHandler(newConfig); + } + } + + setNativeProps(updates) { + const mergedProps = { ...this.props, + ...updates + }; + const newConfig = (0, _gestureHandlerCommon.filterConfig)(transformProps ? transformProps(mergedProps) : mergedProps, [...allowedProps, ...customNativeProps], config); + this.updateGestureHandler(newConfig); + } + + render() { + let gestureEventHandler = this.onGestureHandlerEvent; // Another instance of https://github.com/microsoft/TypeScript/issues/13995 + + const { + onGestureEvent, + onGestureHandlerEvent + } = this.props; + + if (onGestureEvent && typeof onGestureEvent !== 'function') { + // If it's not a method it should be an native Animated.event + // object. We set it directly as the handler for the view + // In this case nested handlers are not going to be supported + if (onGestureHandlerEvent) { + throw new Error('Nesting touch handlers with native animated driver is not supported yet'); + } + + gestureEventHandler = onGestureEvent; + } else { + if (onGestureHandlerEvent && typeof onGestureHandlerEvent !== 'function') { + throw new Error('Nesting touch handlers with native animated driver is not supported yet'); + } + } + + let gestureStateEventHandler = this.onGestureHandlerStateChange; // Another instance of https://github.com/microsoft/TypeScript/issues/13995 + + const { + onHandlerStateChange, + onGestureHandlerStateChange + } = this.props; + + if (onHandlerStateChange && typeof onHandlerStateChange !== 'function') { + // If it's not a method it should be an native Animated.event + // object. We set it directly as the handler for the view + // In this case nested handlers are not going to be supported + if (onGestureHandlerStateChange) { + throw new Error('Nesting touch handlers with native animated driver is not supported yet'); + } + + gestureStateEventHandler = onHandlerStateChange; + } else { + if (onGestureHandlerStateChange && typeof onGestureHandlerStateChange !== 'function') { + throw new Error('Nesting touch handlers with native animated driver is not supported yet'); + } + } + + const events = { + onGestureHandlerEvent: this.state.allowTouches ? gestureEventHandler : undefined, + onGestureHandlerStateChange: this.state.allowTouches ? gestureStateEventHandler : undefined + }; + this.propsRef.current = events; + const child = React.Children.only(this.props.children); + let grandChildren = child.props.children; + + if (_reactNative.Touchable.TOUCH_TARGET_DEBUG && child.type && (child.type === 'RNGestureHandlerButton' || child.type.name === 'View' || child.type.displayName === 'View')) { + grandChildren = React.Children.toArray(grandChildren); + grandChildren.push(_reactNative.Touchable.renderDebugView({ + color: 'mediumspringgreen', + hitSlop: child.props.hitSlop + })); + } + + return /*#__PURE__*/React.cloneElement(child, { + ref: this.refHandler, + collapsable: false, + ...events + }, grandChildren); + } + + } + + _defineProperty(Handler, "displayName", name); + + return Handler; +} +//# sourceMappingURL=createHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/createHandler.js.map b/lib/commonjs/handlers/createHandler.js.map new file mode 100644 index 0000000000..25437e2a1e --- /dev/null +++ b/lib/commonjs/handlers/createHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["createHandler.ts"],"names":["UIManagerAny","UIManager","customGHEventsConfig","onGestureHandlerEvent","registrationName","onGestureHandlerStateChange","genericDirectEventTypes","UIManagerConstants","getViewManagerConfig","getConstants","setJSResponder","oldSetJSResponder","clearJSResponder","oldClearJSResponder","tag","blockNativeResponder","RNGestureHandlerModule","handleSetJSResponder","handleClearJSResponder","allowTouches","DEV_ON_ANDROID","__DEV__","Platform","OS","DeviceEventEmitter","addListener","hasUnresolvedRefs","props","extract","refs","Array","isArray","current","some","r","stateToPropMappings","State","UNDETERMINED","undefined","BEGAN","FAILED","CANCELLED","ACTIVE","END","showedRngh2Notice","showRngh2NoticeIfNeeded","console","warn","createHandler","name","allowedProps","config","transformProps","customNativeProps","Handler","React","Component","constructor","event","nativeEvent","handlerTag","onGestureEvent","onHandlerStateChange","state","stateEventName","eventHandler","node","viewNode","child","Children","only","children","ref","newConfig","createGestureHandler","newViewTag","viewTag","attachGestureHandler","propsRef","updateGestureHandler","createRef","id","handlerIDToTag","Error","componentDidMount","inspectorToggleListener","setState","_","update","updateEnqueued","setImmediate","componentDidUpdate","componentWillUnmount","remove","dropGestureHandler","clearImmediate","handlerID","setNativeProps","updates","mergedProps","render","gestureEventHandler","gestureStateEventHandler","events","grandChildren","Touchable","TOUCH_TARGET_DEBUG","type","displayName","toArray","push","renderDebugView","color","hitSlop","cloneElement","refHandler","collapsable"],"mappings":";;;;;;;AAAA;;AACA;;AAQA;;AACA;;AAEA;;AACA;;AAEA;;;;;;;;;;;;AASA,MAAMA,YAAY,GAAGC,sBAArB;AAEA,MAAMC,oBAAoB,GAAG;AAC3BC,EAAAA,qBAAqB,EAAE;AAAEC,IAAAA,gBAAgB,EAAE;AAApB,GADI;AAE3BC,EAAAA,2BAA2B,EAAE;AAC3BD,IAAAA,gBAAgB,EAAE;AADS;AAFF,CAA7B,C,CAOA;AACA;AACA;AACA;;AACAJ,YAAY,CAACM,uBAAb,GAAuC,EACrC,GAAGN,YAAY,CAACM,uBADqB;AAErC,KAAGJ;AAFkC,CAAvC,C,CAIA;AACA;AACA;;AACA,MAAMK,kBAAkB,sDACtBP,YAAY,CAACQ,oBADS,2DACtB,4BAAAR,YAAY,EAAwB,cAAxB,CADU,kGAEtBA,YAAY,CAACS,YAFS,0DAEtB,2BAAAT,YAAY,CAFd;;AAIA,IAAIO,kBAAJ,EAAwB;AACtBA,EAAAA,kBAAkB,CAACD,uBAAnB,GAA6C,EAC3C,GAAGC,kBAAkB,CAACD,uBADqB;AAE3C,OAAGJ;AAFwC,GAA7C;AAID,C,CAED;;;AACA,MAAM;AACJQ,EAAAA,cAAc,EAAEC,iBAAiB,GAAG,MAAM,CACxC;AACD,GAHG;AAIJC,EAAAA,gBAAgB,EAAEC,mBAAmB,GAAG,MAAM,CAC5C;AACD;AANG,IAOFb,YAPJ;;AAQAA,YAAY,CAACU,cAAb,GAA8B,CAACI,GAAD,EAAcC,oBAAd,KAAgD;AAC5EC,kCA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W4C,QAA/B,CAAnB;AACA,UAAIiC,aAAa,GAAGpC,KAAK,CAACzC,KAAN,CAAY4C,QAAhC;;AACA,UACEkC,uBAAUC,kBAAV,IACAtC,KAAK,CAACuC,IADN,KAECvC,KAAK,CAACuC,IAAN,KAAe,wBAAf,IACCvC,KAAK,CAACuC,IAAN,CAAW1D,IAAX,KAAoB,MADrB,IAECmB,KAAK,CAACuC,IAAN,CAAWC,WAAX,KAA2B,MAJ7B,CADF,EAME;AACAJ,QAAAA,aAAa,GAAGjD,KAAK,CAACc,QAAN,CAAewC,OAAf,CAAuBL,aAAvB,CAAhB;AACAA,QAAAA,aAAa,CAACM,IAAd,CACEL,uBAAUM,eAAV,CAA0B;AACxBC,UAAAA,KAAK,EAAE,mBADiB;AAExBC,UAAAA,OAAO,EAAE7C,KAAK,CAACzC,KAAN,CAAYsF;AAFG,SAA1B,CADF;AAMD;;AAED,0BAAO1D,KAAK,CAAC2D,YAAN,CACL9C,KADK,EAEL;AACEI,QAAAA,GAAG,EAAE,KAAK2C,UADZ;AAEEC,QAAAA,WAAW,EAAE,KAFf;AAGE,WAAGb;AAHL,OAFK,EAOLC,aAPK,CAAP;AASD;;AAhSD;;AAPwE,kBAIpElD,OAJoE,iBAQnDL,IARmD;;AAyS1E,SAAOK,OAAP;AACD","sourcesContent":["import * as React from 'react';\nimport {\n Platform,\n Touchable,\n UIManager,\n DeviceEventEmitter,\n EmitterSubscription,\n} from 'react-native';\n// @ts-ignore - it isn't typed by TS & don't have definitelyTyped types\nimport deepEqual from 'lodash/isEqual';\nimport RNGestureHandlerModule from '../RNGestureHandlerModule';\nimport type RNGestureHandlerModuleWeb from '../RNGestureHandlerModule.web';\nimport { State } from '../State';\nimport { handlerIDToTag, getNextHandlerTag } from './handlersRegistry';\n\nimport {\n BaseGestureHandlerProps,\n filterConfig,\n GestureEvent,\n HandlerStateChangeEvent,\n findNodeHandle,\n} from './gestureHandlerCommon';\nimport { ValueOf } from '../typeUtils';\n\nconst UIManagerAny = UIManager as any;\n\nconst customGHEventsConfig = {\n onGestureHandlerEvent: { registrationName: 'onGestureHandlerEvent' },\n onGestureHandlerStateChange: {\n registrationName: 'onGestureHandlerStateChange',\n },\n};\n\n// Add gesture specific events to genericDirectEventTypes object exported from UIManager\n// native module.\n// Once new event types are registered with react it is possible to dispatch these\n// events to all kind of native views.\nUIManagerAny.genericDirectEventTypes = {\n ...UIManagerAny.genericDirectEventTypes,\n ...customGHEventsConfig,\n};\n// In newer versions of RN the `genericDirectEventTypes` is located in the object\n// returned by UIManager.getViewManagerConfig('getConstants') or in older RN UIManager.getConstants(), we need to add it there as well to make\n// it compatible with RN 61+\nconst UIManagerConstants =\n UIManagerAny.getViewManagerConfig?.('getConstants') ??\n UIManagerAny.getConstants?.();\n\nif (UIManagerConstants) {\n UIManagerConstants.genericDirectEventTypes = {\n ...UIManagerConstants.genericDirectEventTypes,\n ...customGHEventsConfig,\n };\n}\n\n// Wrap JS responder calls and notify gesture handler manager\nconst {\n setJSResponder: oldSetJSResponder = () => {\n //no operation\n },\n clearJSResponder: oldClearJSResponder = () => {\n //no operation\n },\n} = UIManagerAny;\nUIManagerAny.setJSResponder = (tag: number, blockNativeResponder: boolean) => {\n RNGestureHandlerModule.handleSetJSResponder(tag, blockNativeResponder);\n oldSetJSResponder(tag, blockNativeResponder);\n};\nUIManagerAny.clearJSResponder = () => {\n RNGestureHandlerModule.handleClearJSResponder();\n oldClearJSResponder();\n};\n\nlet allowTouches = true;\nconst DEV_ON_ANDROID = __DEV__ && Platform.OS === 'android';\n// Toggled inspector blocks touch events in order to allow inspecting on Android\n// This needs to be a global variable in order to set initial state for `allowTouches` property in Handler component\nif (DEV_ON_ANDROID) {\n DeviceEventEmitter.addListener('toggleElementInspector', () => {\n allowTouches = !allowTouches;\n });\n}\n\ntype HandlerProps> = Readonly<\n React.PropsWithChildren>\n>;\nfunction hasUnresolvedRefs>(\n props: HandlerProps\n) {\n // TODO(TS) - add type for extract arg\n const extract = (refs: any | any[]) => {\n if (!Array.isArray(refs)) {\n return refs && refs.current === null;\n }\n return refs.some((r) => r && r.current === null);\n };\n return extract(props['simultaneousHandlers']) || extract(props['waitFor']);\n}\n\nconst stateToPropMappings = {\n [State.UNDETERMINED]: undefined,\n [State.BEGAN]: 'onBegan',\n [State.FAILED]: 'onFailed',\n [State.CANCELLED]: 'onCancelled',\n [State.ACTIVE]: 'onActivated',\n [State.END]: 'onEnded',\n} as const;\n\ntype CreateHandlerArgs<\n HandlerPropsT extends Record\n> = Readonly<{\n name: string;\n allowedProps: Readonly[]>;\n config: Readonly>;\n transformProps?: (props: HandlerPropsT) => HandlerPropsT;\n customNativeProps?: Readonly;\n}>;\n\n// TODO(TS) fix event types\ntype InternalEventHandlers = {\n onGestureHandlerEvent?: (event: any) => void;\n onGestureHandlerStateChange?: (event: any) => void;\n};\n\nlet showedRngh2Notice = false;\nfunction showRngh2NoticeIfNeeded() {\n if (!showedRngh2Notice) {\n console.warn(\n \"[react-native-gesture-handler] Seems like you're using an old API with gesture components, check out new Gestures system!\"\n );\n showedRngh2Notice = true;\n }\n}\n\n// TODO(TS) - make sure that BaseGestureHandlerProps doesn't need other generic parameter to work with custom properties.\nexport default function createHandler<\n T extends BaseGestureHandlerProps,\n U extends Record\n>({\n name,\n allowedProps = [],\n config = {},\n transformProps,\n customNativeProps = [],\n}: CreateHandlerArgs): React.ComponentType> {\n interface HandlerState {\n allowTouches: boolean;\n }\n class Handler extends React.Component<\n T & InternalEventHandlers,\n HandlerState\n > {\n static displayName = name;\n\n private handlerTag: number;\n private config: Record;\n private propsRef: React.MutableRefObject;\n private viewNode: any;\n private viewTag?: number;\n private updateEnqueued: ReturnType | null = null;\n private inspectorToggleListener?: EmitterSubscription;\n\n constructor(props: T & InternalEventHandlers) {\n super(props);\n this.handlerTag = getNextHandlerTag();\n this.config = {};\n this.propsRef = React.createRef();\n this.state = { allowTouches };\n if (props.id) {\n if (handlerIDToTag[props.id] !== undefined) {\n throw new Error(`Handler with ID \"${props.id}\" already registered`);\n }\n handlerIDToTag[props.id] = this.handlerTag;\n }\n if (__DEV__) {\n showRngh2NoticeIfNeeded();\n }\n }\n\n componentDidMount() {\n const props: HandlerProps = this.props;\n\n if (DEV_ON_ANDROID) {\n this.inspectorToggleListener = DeviceEventEmitter.addListener(\n 'toggleElementInspector',\n () => {\n this.setState((_) => ({ allowTouches }));\n this.update();\n }\n );\n }\n if (hasUnresolvedRefs(props)) {\n // If there are unresolved refs (e.g. \".current\" has not yet been set)\n // passed as `simultaneousHandlers` or `waitFor`, we enqueue a call to\n // _update method that will try to update native handler props using\n // setImmediate. This makes it so update() function gets called after all\n // react components are mounted and we expect the missing ref object to\n // be resolved by then.\n this.updateEnqueued = setImmediate(() => {\n this.updateEnqueued = null;\n this.update();\n });\n }\n\n this.createGestureHandler(\n filterConfig(\n transformProps ? transformProps(this.props) : this.props,\n [...allowedProps, ...customNativeProps],\n config\n )\n );\n\n this.attachGestureHandler(findNodeHandle(this.viewNode) as number); // TODO(TS) - check if this can be null\n }\n\n componentDidUpdate() {\n const viewTag = findNodeHandle(this.viewNode);\n if (this.viewTag !== viewTag) {\n this.attachGestureHandler(viewTag as number); // TODO(TS) - check interaction between _viewTag & findNodeHandle\n }\n this.update();\n }\n\n componentWillUnmount() {\n this.inspectorToggleListener?.remove();\n RNGestureHandlerModule.dropGestureHandler(this.handlerTag);\n if (this.updateEnqueued) {\n clearImmediate(this.updateEnqueued);\n }\n // We can't use this.props.id directly due to TS generic type narrowing bug, see https://github.com/microsoft/TypeScript/issues/13995 for more context\n const handlerID: string | undefined = this.props.id;\n if (handlerID) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete handlerIDToTag[handlerID];\n }\n }\n\n private onGestureHandlerEvent = (event: GestureEvent) => {\n if (event.nativeEvent.handlerTag === this.handlerTag) {\n this.props.onGestureEvent?.(event);\n } else {\n this.props.onGestureHandlerEvent?.(event);\n }\n };\n\n // TODO(TS) - make sure this is right type for event\n private onGestureHandlerStateChange = (\n event: HandlerStateChangeEvent\n ) => {\n if (event.nativeEvent.handlerTag === this.handlerTag) {\n this.props.onHandlerStateChange?.(event);\n\n const state: ValueOf = event.nativeEvent.state;\n const stateEventName = stateToPropMappings[state];\n const eventHandler = stateEventName && this.props[stateEventName];\n if (eventHandler && typeof eventHandler === 'function') {\n eventHandler(event);\n }\n } else {\n this.props.onGestureHandlerStateChange?.(event);\n }\n };\n\n private refHandler = (node: any) => {\n this.viewNode = node;\n\n const child = React.Children.only(this.props.children);\n // TODO(TS) fix ref type\n const { ref }: any = child;\n if (ref !== null) {\n if (typeof ref === 'function') {\n ref(node);\n } else {\n ref.current = node;\n }\n }\n };\n\n private createGestureHandler = (\n newConfig: Readonly>\n ) => {\n this.config = newConfig;\n\n RNGestureHandlerModule.createGestureHandler(\n name,\n this.handlerTag,\n newConfig\n );\n };\n\n private attachGestureHandler = (newViewTag: number) => {\n this.viewTag = newViewTag;\n\n if (Platform.OS === 'web') {\n // typecast due to dynamic resolution, attachGestureHandler should have web version signature in this branch\n (RNGestureHandlerModule.attachGestureHandler as typeof RNGestureHandlerModuleWeb.attachGestureHandler)(\n this.handlerTag,\n newViewTag,\n false,\n this.propsRef\n );\n } else {\n RNGestureHandlerModule.attachGestureHandler(\n this.handlerTag,\n newViewTag,\n false\n );\n }\n };\n\n private updateGestureHandler = (\n newConfig: Readonly>\n ) => {\n this.config = newConfig;\n\n RNGestureHandlerModule.updateGestureHandler(this.handlerTag, newConfig);\n };\n\n private update() {\n const newConfig = filterConfig(\n transformProps ? transformProps(this.props) : this.props,\n [...allowedProps, ...customNativeProps],\n config\n );\n if (!deepEqual(this.config, newConfig)) {\n this.updateGestureHandler(newConfig);\n }\n }\n\n setNativeProps(updates: any) {\n const mergedProps = { ...this.props, ...updates };\n const newConfig = filterConfig(\n transformProps ? transformProps(mergedProps) : mergedProps,\n [...allowedProps, ...customNativeProps],\n config\n );\n this.updateGestureHandler(newConfig);\n }\n\n render() {\n let gestureEventHandler = this.onGestureHandlerEvent;\n // Another instance of https://github.com/microsoft/TypeScript/issues/13995\n type OnGestureEventHandlers = {\n onGestureEvent?: BaseGestureHandlerProps['onGestureEvent'];\n onGestureHandlerEvent?: InternalEventHandlers['onGestureHandlerEvent'];\n };\n const {\n onGestureEvent,\n onGestureHandlerEvent,\n }: OnGestureEventHandlers = this.props;\n if (onGestureEvent && typeof onGestureEvent !== 'function') {\n // If it's not a method it should be an native Animated.event\n // object. We set it directly as the handler for the view\n // In this case nested handlers are not going to be supported\n if (onGestureHandlerEvent) {\n throw new Error(\n 'Nesting touch handlers with native animated driver is not supported yet'\n );\n }\n gestureEventHandler = onGestureEvent;\n } else {\n if (\n onGestureHandlerEvent &&\n typeof onGestureHandlerEvent !== 'function'\n ) {\n throw new Error(\n 'Nesting touch handlers with native animated driver is not supported yet'\n );\n }\n }\n\n let gestureStateEventHandler = this.onGestureHandlerStateChange;\n // Another instance of https://github.com/microsoft/TypeScript/issues/13995\n type OnGestureStateChangeHandlers = {\n onHandlerStateChange?: BaseGestureHandlerProps['onHandlerStateChange'];\n onGestureHandlerStateChange?: InternalEventHandlers['onGestureHandlerStateChange'];\n };\n const {\n onHandlerStateChange,\n onGestureHandlerStateChange,\n }: OnGestureStateChangeHandlers = this.props;\n if (onHandlerStateChange && typeof onHandlerStateChange !== 'function') {\n // If it's not a method it should be an native Animated.event\n // object. We set it directly as the handler for the view\n // In this case nested handlers are not going to be supported\n if (onGestureHandlerStateChange) {\n throw new Error(\n 'Nesting touch handlers with native animated driver is not supported yet'\n );\n }\n gestureStateEventHandler = onHandlerStateChange;\n } else {\n if (\n onGestureHandlerStateChange &&\n typeof onGestureHandlerStateChange !== 'function'\n ) {\n throw new Error(\n 'Nesting touch handlers with native animated driver is not supported yet'\n );\n }\n }\n const events = {\n onGestureHandlerEvent: this.state.allowTouches\n ? gestureEventHandler\n : undefined,\n onGestureHandlerStateChange: this.state.allowTouches\n ? gestureStateEventHandler\n : undefined,\n };\n\n this.propsRef.current = events;\n\n const child: any = React.Children.only(this.props.children);\n let grandChildren = child.props.children;\n if (\n Touchable.TOUCH_TARGET_DEBUG &&\n child.type &&\n (child.type === 'RNGestureHandlerButton' ||\n child.type.name === 'View' ||\n child.type.displayName === 'View')\n ) {\n grandChildren = React.Children.toArray(grandChildren);\n grandChildren.push(\n Touchable.renderDebugView({\n color: 'mediumspringgreen',\n hitSlop: child.props.hitSlop,\n })\n );\n }\n\n return React.cloneElement(\n child,\n {\n ref: this.refHandler,\n collapsable: false,\n ...events,\n },\n grandChildren\n );\n }\n }\n return Handler;\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/createNativeWrapper.js b/lib/commonjs/handlers/createNativeWrapper.js new file mode 100644 index 0000000000..29fd09f7b6 --- /dev/null +++ b/lib/commonjs/handlers/createNativeWrapper.js @@ -0,0 +1,70 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = createNativeWrapper; + +var React = _interopRequireWildcard(require("react")); + +var _NativeViewGestureHandler = require("./NativeViewGestureHandler"); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +/* + * This array should consist of: + * - All keys in propTypes from NativeGestureHandler + * (and all keys in GestureHandlerPropTypes) + * - 'onGestureHandlerEvent' + * - 'onGestureHandlerStateChange' + */ +const NATIVE_WRAPPER_PROPS_FILTER = [..._NativeViewGestureHandler.nativeViewProps, 'onGestureHandlerEvent', 'onGestureHandlerStateChange']; + +function createNativeWrapper(Component, config = {}) { + const ComponentWrapper = /*#__PURE__*/React.forwardRef((props, ref) => { + // filter out props that should be passed to gesture handler wrapper + const gestureHandlerProps = Object.keys(props).reduce((res, key) => { + // TS being overly protective with it's types, see https://github.com/microsoft/TypeScript/issues/26255#issuecomment-458013731 for more info + const allowedKeys = NATIVE_WRAPPER_PROPS_FILTER; + + if (allowedKeys.includes(key)) { + // @ts-ignore FIXME(TS) + res[key] = props[key]; + } + + return res; + }, { ...config + } // watch out not to modify config + ); + + const _ref = (0, React.useRef)(); + + const _gestureHandlerRef = (0, React.useRef)(); + + (0, React.useImperativeHandle)(ref, // @ts-ignore TODO(TS) decide how nulls work in this context + () => { + const node = _gestureHandlerRef.current; // add handlerTag for relations config + + if (_ref.current && node) { + // @ts-ignore FIXME(TS) think about createHandler return type + _ref.current.handlerTag = node.handlerTag; + return _ref.current; + } + + return null; + }, [_ref, _gestureHandlerRef]); + return /*#__PURE__*/React.createElement(_NativeViewGestureHandler.NativeViewGestureHandler, _extends({}, gestureHandlerProps, { + // @ts-ignore TODO(TS) + ref: _gestureHandlerRef + }), /*#__PURE__*/React.createElement(Component, _extends({}, props, { + ref: _ref + }))); + }); + ComponentWrapper.displayName = Component.displayName || 'ComponentWrapper'; + return ComponentWrapper; +} +//# sourceMappingURL=createNativeWrapper.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/createNativeWrapper.js.map b/lib/commonjs/handlers/createNativeWrapper.js.map new file mode 100644 index 0000000000..79a2effeba --- /dev/null +++ b/lib/commonjs/handlers/createNativeWrapper.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["createNativeWrapper.tsx"],"names":["NATIVE_WRAPPER_PROPS_FILTER","nativeViewProps","createNativeWrapper","Component","config","ComponentWrapper","React","forwardRef","props","ref","gestureHandlerProps","Object","keys","reduce","res","key","allowedKeys","includes","_ref","_gestureHandlerRef","node","current","handlerTag","displayName"],"mappings":";;;;;;;AAAA;;AAGA;;;;;;;;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMA,2BAA2B,GAAG,CAClC,GAAGC,yCAD+B,EAElC,uBAFkC,EAGlC,6BAHkC,CAApC;;AAMe,SAASC,mBAAT,CACbC,SADa,EAEbC,MAA+C,GAAG,EAFrC,EAGb;AACA,QAAMC,gBAAgB,gBAAGC,KAAK,CAACC,UAAN,CAGvB,CAACC,KAAD,EAAQC,GAAR,KAAgB;AAChB;AACA,UAAMC,mBAAmB,GAAGC,MAAM,CAACC,IAAP,CAAYJ,KAAZ,EAAmBK,MAAnB,CAC1B,CAACC,GAAD,EAAMC,GAAN,KAAc;AACZ;AACA,YAAMC,WAA8B,GAAGhB,2BAAvC;;AACA,UAAIgB,WAAW,CAACC,QAAZ,CAAqBF,GAArB,CAAJ,EAA+B;AAC7B;AACAD,QAAAA,GAAG,CAACC,GAAD,CAAH,GAAWP,KAAK,CAACO,GAAD,CAAhB;AACD;;AACD,aAAOD,GAAP;AACD,KATyB,EAU1B,EAAE,GAAGV;AAAL,KAV0B,CAUZ;AAVY,KAA5B;;AAYA,UAAMc,IAAI,GAAG,mBAAb;;AACA,UAAMC,kBAAkB,GAAG,mBAA3B;;AACA,mCACEV,GADF,EAEE;AACA,UAAM;AACJ,YAAMW,IAAI,GAAGD,kBAAkB,CAACE,OAAhC,CADI,CAEJ;;AACA,UAAIH,IAAI,CAACG,OAAL,IAAgBD,IAApB,EAA0B;AACxB;AACAF,QAAAA,IAAI,CAACG,OAAL,CAAaC,UAAb,GAA0BF,IAAI,CAACE,UAA/B;AACA,eAAOJ,IAAI,CAACG,OAAZ;AACD;;AACD,aAAO,IAAP;AACD,KAZH,EAaE,CAACH,IAAD,EAAOC,kBAAP,CAbF;AAeA,wBACE,oBAAC,kDAAD,eACMT,mBADN;AAEE;AACA,MAAA,GAAG,EAAES;AAHP,qBAIE,oBAAC,SAAD,eAAeX,KAAf;AAAsB,MAAA,GAAG,EAAEU;AAA3B,OAJF,CADF;AAQD,GA1CwB,CAAzB;AA4CAb,EAAAA,gBAAgB,CAACkB,WAAjB,GAA+BpB,SAAS,CAACoB,WAAV,IAAyB,kBAAxD;AAEA,SAAOlB,gBAAP;AACD","sourcesContent":["import * as React from 'react';\nimport { useImperativeHandle, useRef } from 'react';\n\nimport {\n NativeViewGestureHandler,\n NativeViewGestureHandlerProps,\n nativeViewProps,\n} from './NativeViewGestureHandler';\n\n/*\n * This array should consist of:\n * - All keys in propTypes from NativeGestureHandler\n * (and all keys in GestureHandlerPropTypes)\n * - 'onGestureHandlerEvent'\n * - 'onGestureHandlerStateChange'\n */\nconst NATIVE_WRAPPER_PROPS_FILTER = [\n ...nativeViewProps,\n 'onGestureHandlerEvent',\n 'onGestureHandlerStateChange',\n] as const;\n\nexport default function createNativeWrapper

(\n Component: React.ComponentType

,\n config: Readonly = {}\n) {\n const ComponentWrapper = React.forwardRef<\n React.ComponentType,\n P & NativeViewGestureHandlerProps\n >((props, ref) => {\n // filter out props that should be passed to gesture handler wrapper\n const gestureHandlerProps = Object.keys(props).reduce(\n (res, key) => {\n // TS being overly protective with it's types, see https://github.com/microsoft/TypeScript/issues/26255#issuecomment-458013731 for more info\n const allowedKeys: readonly string[] = NATIVE_WRAPPER_PROPS_FILTER;\n if (allowedKeys.includes(key)) {\n // @ts-ignore FIXME(TS)\n res[key] = props[key];\n }\n return res;\n },\n { ...config } // watch out not to modify config\n );\n const _ref = useRef>();\n const _gestureHandlerRef = useRef>();\n useImperativeHandle(\n ref,\n // @ts-ignore TODO(TS) decide how nulls work in this context\n () => {\n const node = _gestureHandlerRef.current;\n // add handlerTag for relations config\n if (_ref.current && node) {\n // @ts-ignore FIXME(TS) think about createHandler return type\n _ref.current.handlerTag = node.handlerTag;\n return _ref.current;\n }\n return null;\n },\n [_ref, _gestureHandlerRef]\n );\n return (\n \n \n \n );\n });\n\n ComponentWrapper.displayName = Component.displayName || 'ComponentWrapper';\n\n return ComponentWrapper;\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestureHandlerCommon.js b/lib/commonjs/handlers/gestureHandlerCommon.js new file mode 100644 index 0000000000..855a80eca1 --- /dev/null +++ b/lib/commonjs/handlers/gestureHandlerCommon.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.filterConfig = filterConfig; +exports.findNodeHandle = findNodeHandle; +exports.baseGestureHandlerWithMonitorProps = exports.baseGestureHandlerProps = void 0; + +var _reactNative = require("react-native"); + +var _handlersRegistry = require("./handlersRegistry"); + +var _utils = require("../utils"); + +// Previous types exported gesture handlers as classes which creates an interface and variable, both named the same as class. +// Without those types, we'd introduce breaking change, forcing users to prefix every handler type specification with typeof +// e.g. React.createRef -> React.createRef. +// See https://www.typescriptlang.org/docs/handbook/classes.html#constructor-functions for reference. +const commonProps = ['id', 'enabled', 'shouldCancelWhenOutside', 'hitSlop']; +const componentInteractionProps = ['waitFor', 'simultaneousHandlers']; +const baseGestureHandlerProps = [...commonProps, ...componentInteractionProps, 'onBegan', 'onFailed', 'onCancelled', 'onActivated', 'onEnded', 'onGestureEvent', 'onHandlerStateChange']; +exports.baseGestureHandlerProps = baseGestureHandlerProps; +const baseGestureHandlerWithMonitorProps = [...commonProps, 'needsPointerData', 'manualActivation']; +exports.baseGestureHandlerWithMonitorProps = baseGestureHandlerWithMonitorProps; + +function isConfigParam(param, name) { + // param !== Object(param) returns false if `param` is a function + // or an object and returns true if `param` is null + return param !== undefined && (param !== Object(param) || !('__isNative' in param)) && name !== 'onHandlerStateChange' && name !== 'onGestureEvent'; +} + +function filterConfig(props, validProps, defaults = {}) { + const filteredConfig = { ...defaults + }; + + for (const key of validProps) { + let value = props[key]; + + if (isConfigParam(value, key)) { + if (key === 'simultaneousHandlers' || key === 'waitFor') { + value = transformIntoHandlerTags(props[key]); + } else if (key === 'hitSlop' && typeof value !== 'object') { + value = { + top: value, + left: value, + bottom: value, + right: value + }; + } + + filteredConfig[key] = value; + } + } + + return filteredConfig; +} + +function transformIntoHandlerTags(handlerIDs) { + handlerIDs = (0, _utils.toArray)(handlerIDs); + + if (_reactNative.Platform.OS === 'web') { + return handlerIDs.map(({ + current + }) => current).filter(handle => handle); + } // converts handler string IDs into their numeric tags + + + return handlerIDs.map(handlerID => { + var _handlerID$current; + + return _handlersRegistry.handlerIDToTag[handlerID] || ((_handlerID$current = handlerID.current) === null || _handlerID$current === void 0 ? void 0 : _handlerID$current.handlerTag) || -1; + }).filter(handlerTag => handlerTag > 0); +} + +function findNodeHandle(node) { + if (_reactNative.Platform.OS === 'web') return node; + return (0, _reactNative.findNodeHandle)(node); +} +//# sourceMappingURL=gestureHandlerCommon.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestureHandlerCommon.js.map b/lib/commonjs/handlers/gestureHandlerCommon.js.map new file mode 100644 index 0000000000..e86a1afb2c --- /dev/null +++ b/lib/commonjs/handlers/gestureHandlerCommon.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["gestureHandlerCommon.ts"],"names":["commonProps","componentInteractionProps","baseGestureHandlerProps","baseGestureHandlerWithMonitorProps","isConfigParam","param","name","undefined","Object","filterConfig","props","validProps","defaults","filteredConfig","key","value","transformIntoHandlerTags","top","left","bottom","right","handlerIDs","Platform","OS","map","current","filter","handle","handlerID","handlerIDToTag","handlerTag","findNodeHandle","node"],"mappings":";;;;;;;;;AAKA;;AAKA;;AACA;;AAXA;AACA;AACA;AACA;AAUA,MAAMA,WAAW,GAAG,CAClB,IADkB,EAElB,SAFkB,EAGlB,yBAHkB,EAIlB,SAJkB,CAApB;AAOA,MAAMC,yBAAyB,GAAG,CAAC,SAAD,EAAY,sBAAZ,CAAlC;AAEO,MAA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;AACF;;AACD,SAAOF,cAAP;AACD;;AAED,SAASG,wBAAT,CAAkCK,UAAlC,EAAmD;AACjDA,EAAAA,UAAU,GAAG,oBAAQA,UAAR,CAAb;;AAEA,MAAIC,sBAASC,EAAT,KAAgB,KAApB,EAA2B;AACzB,WAAOF,UAAU,CACdG,GADI,CACA,CAAC;AAAEC,MAAAA;AAAF,KAAD,KAAmCA,OADnC,EAEJC,MAFI,CAEIC,MAAD,IAAiBA,MAFpB,CAAP;AAGD,GAPgD,CAQjD;;;AACA,SAAON,UAAU,CACdG,GADI,CAEFI,SAAD;AAAA;;AAAA,WACEC,iCAAeD,SAAf,4BAA6BA,SAAS,CAACH,OAAvC,uDAA6B,mBAAmBK,UAAhD,KAA8D,CAAC,CADjE;AAAA,GAFG,EAKJJ,MALI,CAKII,UAAD,IAAwBA,UAAU,GAAG,CALxC,CAAP;AAMD;;AAEM,SAASC,cAAT,CACLC,IADK,EAEkE;AACvE,MAAIV,sBAASC,EAAT,KAAgB,KAApB,EAA2B,OAAOS,IAAP;AAC3B,SAAO,iCAAiBA,IAAjB,CAAP;AACD","sourcesContent":["// Previous types exported gesture handlers as classes which creates an interface and variable, both named the same as class.\n// Without those types, we'd introduce breaking change, forcing users to prefix every handler type specification with typeof\n// e.g. React.createRef -> React.createRef.\n// See https://www.typescriptlang.org/docs/handbook/classes.html#constructor-functions for reference.\nimport * as React from 'react';\nimport { Platform, findNodeHandle as findNodeHandleRN } from 'react-native';\n\nimport { State } from '../State';\nimport { EventType } from '../EventType';\nimport { ValueOf } from '../typeUtils';\nimport { handlerIDToTag } from './handlersRegistry';\nimport { toArray } from '../utils';\n\nconst commonProps = [\n 'id',\n 'enabled',\n 'shouldCancelWhenOutside',\n 'hitSlop',\n] as const;\n\nconst componentInteractionProps = ['waitFor', 'simultaneousHandlers'] as const;\n\nexport const baseGestureHandlerProps = [\n ...commonProps,\n ...componentInteractionProps,\n 'onBegan',\n 'onFailed',\n 'onCancelled',\n 'onActivated',\n 'onEnded',\n 'onGestureEvent',\n 'onHandlerStateChange',\n] as const;\n\nexport const baseGestureHandlerWithMonitorProps = [\n ...commonProps,\n 'needsPointerData',\n 'manualActivation',\n];\n\nexport interface GestureEventPayload {\n handlerTag: number;\n numberOfPointers: number;\n state: ValueOf;\n}\n\nexport interface HandlerStateChangeEventPayload {\n handlerTag: number;\n numberOfPointers: number;\n state: ValueOf;\n oldState: ValueOf;\n}\n\nexport type HitSlop =\n | number\n | Partial<\n Record<\n 'left' | 'right' | 'top' | 'bottom' | 'vertical' | 'horizontal',\n number\n >\n >\n | Record<'width' | 'left', number>\n | Record<'width' | 'right', number>\n | Record<'height' | 'top', number>\n | Record<'height' | 'bottom', number>;\n\n//TODO(TS) events in handlers\n\nexport interface GestureEvent> {\n nativeEvent: Readonly;\n}\nexport interface HandlerStateChangeEvent<\n ExtraEventPayloadT = Record\n> {\n nativeEvent: Readonly;\n}\n\nexport type TouchData = {\n id: number;\n x: number;\n y: number;\n absoluteX: number;\n absoluteY: number;\n};\n\nexport type GestureTouchEvent = {\n handlerTag: number;\n numberOfTouches: number;\n state: ValueOf;\n eventType: EventType;\n allTouches: TouchData[];\n changedTouches: TouchData[];\n};\n\nexport type GestureUpdateEvent<\n GestureEventPayloadT = Record\n> = GestureEventPayload & GestureEventPayloadT;\n\nexport type GestureStateChangeEvent<\n GestureStateChangeEventPayloadT = Record\n> = HandlerStateChangeEventPayload & GestureStateChangeEventPayloadT;\n\nexport type CommonGestureConfig = {\n enabled?: boolean;\n shouldCancelWhenOutside?: boolean;\n hitSlop?: HitSlop;\n};\n\n// Events payloads are types instead of interfaces due to TS limitation.\n// See https://github.com/microsoft/TypeScript/issues/15300 for more info.\nexport type BaseGestureHandlerProps<\n ExtraEventPayloadT extends Record = Record\n> = CommonGestureConfig & {\n id?: string;\n waitFor?: React.Ref | React.Ref[];\n simultaneousHandlers?: React.Ref | React.Ref[];\n // TODO(TS) - fix event types\n onBegan?: (event: HandlerStateChangeEvent) => void;\n onFailed?: (event: HandlerStateChangeEvent) => void;\n onCancelled?: (event: HandlerStateChangeEvent) => void;\n onActivated?: (event: HandlerStateChangeEvent) => void;\n onEnded?: (event: HandlerStateChangeEvent) => void;\n\n //TODO(TS) consider using NativeSyntheticEvent\n onGestureEvent?: (event: GestureEvent) => void;\n onHandlerStateChange?: (\n event: HandlerStateChangeEvent\n ) => void;\n};\n\nfunction isConfigParam(param: unknown, name: string) {\n // param !== Object(param) returns false if `param` is a function\n // or an object and returns true if `param` is null\n return (\n param !== undefined &&\n (param !== Object(param) ||\n !('__isNative' in (param as Record))) &&\n name !== 'onHandlerStateChange' &&\n name !== 'onGestureEvent'\n );\n}\n\nexport function filterConfig(\n props: Record,\n validProps: string[],\n defaults: Record = {}\n) {\n const filteredConfig = { ...defaults };\n for (const key of validProps) {\n let value = props[key];\n if (isConfigParam(value, key)) {\n if (key === 'simultaneousHandlers' || key === 'waitFor') {\n value = transformIntoHandlerTags(props[key]);\n } else if (key === 'hitSlop' && typeof value !== 'object') {\n value = { top: value, left: value, bottom: value, right: value };\n }\n filteredConfig[key] = value;\n }\n }\n return filteredConfig;\n}\n\nfunction transformIntoHandlerTags(handlerIDs: any) {\n handlerIDs = toArray(handlerIDs);\n\n if (Platform.OS === 'web') {\n return handlerIDs\n .map(({ current }: { current: any }) => current)\n .filter((handle: any) => handle);\n }\n // converts handler string IDs into their numeric tags\n return handlerIDs\n .map(\n (handlerID: any) =>\n handlerIDToTag[handlerID] || handlerID.current?.handlerTag || -1\n )\n .filter((handlerTag: number) => handlerTag > 0);\n}\n\nexport function findNodeHandle(\n node: null | number | React.Component | React.ComponentClass\n): null | number | React.Component | React.ComponentClass {\n if (Platform.OS === 'web') return node;\n return findNodeHandleRN(node);\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestureHandlerTypesCompat.js b/lib/commonjs/handlers/gestureHandlerTypesCompat.js new file mode 100644 index 0000000000..a82c6d8e6e --- /dev/null +++ b/lib/commonjs/handlers/gestureHandlerTypesCompat.js @@ -0,0 +1,2 @@ +"use strict"; +//# sourceMappingURL=gestureHandlerTypesCompat.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestureHandlerTypesCompat.js.map b/lib/commonjs/handlers/gestureHandlerTypesCompat.js.map new file mode 100644 index 0000000000..9ffd4b22fc --- /dev/null +++ b/lib/commonjs/handlers/gestureHandlerTypesCompat.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","sourcesContent":[]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/GestureDetector.js b/lib/commonjs/handlers/gestures/GestureDetector.js new file mode 100644 index 0000000000..50da038043 --- /dev/null +++ b/lib/commonjs/handlers/gestures/GestureDetector.js @@ -0,0 +1,440 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GestureDetector = void 0; + +var _react = _interopRequireWildcard(require("react")); + +var _gesture = require("./gesture"); + +var _reanimatedWrapper = require("./reanimatedWrapper"); + +var _handlersRegistry = require("../handlersRegistry"); + +var _RNGestureHandlerModule = _interopRequireDefault(require("../../RNGestureHandlerModule")); + +var _gestureHandlerCommon = require("../gestureHandlerCommon"); + +var _gestureStateManager = require("./gestureStateManager"); + +var _FlingGestureHandler = require("../FlingGestureHandler"); + +var _ForceTouchGestureHandler = require("../ForceTouchGestureHandler"); + +var _LongPressGestureHandler = require("../LongPressGestureHandler"); + +var _PanGestureHandler = require("../PanGestureHandler"); + +var _TapGestureHandler = require("../TapGestureHandler"); + +var _State = require("../../State"); + +var _EventType = require("../../EventType"); + +var _Reanimated$default$c, _Reanimated$default; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +const ALLOWED_PROPS = [..._gestureHandlerCommon.baseGestureHandlerWithMonitorProps, ..._TapGestureHandler.tapGestureHandlerProps, ..._PanGestureHandler.panGestureHandlerProps, ..._PanGestureHandler.panGestureHandlerCustomNativeProps, ..._LongPressGestureHandler.longPressGestureHandlerProps, ..._ForceTouchGestureHandler.forceTouchGestureHandlerProps, ..._FlingGestureHandler.flingGestureHandlerProps]; + +function convertToHandlerTag(ref) { + if (typeof ref === 'number') { + return ref; + } else if (ref instanceof _gesture.BaseGesture) { + return ref.handlerTag; + } else { + var _ref$current$handlerT, _ref$current; + + // @ts-ignore in this case it should be a ref either to gesture object or + // a gesture handler component, in both cases handlerTag property exists + return (_ref$current$handlerT = (_ref$current = ref.current) === null || _ref$current === void 0 ? void 0 : _ref$current.handlerTag) !== null && _ref$current$handlerT !== void 0 ? _ref$current$handlerT : -1; + } +} + +function extractValidHandlerTags(interactionGroup) { + var _interactionGroup$map, _interactionGroup$map2; + + return (_interactionGroup$map = interactionGroup === null || interactionGroup === void 0 ? void 0 : (_interactionGroup$map2 = interactionGroup.map(convertToHandlerTag)) === null || _interactionGroup$map2 === void 0 ? void 0 : _interactionGroup$map2.filter(tag => tag > 0)) !== null && _interactionGroup$map !== void 0 ? _interactionGroup$map : []; +} + +function dropHandlers(preparedGesture) { + for (const handler of preparedGesture.config) { + _RNGestureHandlerModule.default.dropGestureHandler(handler.handlerTag); + + (0, _handlersRegistry.unregisterHandler)(handler.handlerTag); + } +} + +function attachHandlers({ + preparedGesture, + gestureConfig, + gesture, + viewTag, + useAnimated +}) { + if (!preparedGesture.firstExecution) { + gestureConfig === null || gestureConfig === void 0 ? void 0 : gestureConfig.initialize(); + } else { + preparedGesture.firstExecution = false; + } // use setImmediate to extract handlerTags, because all refs should be initialized + // when it's ran + + + setImmediate(() => { + gestureConfig === null || gestureConfig === void 0 ? void 0 : gestureConfig.prepare(); + }); + + for (const handler of gesture) { + _RNGestureHandlerModule.default.createGestureHandler(handler.handlerName, handler.handlerTag, (0, _gestureHandlerCommon.filterConfig)(handler.config, ALLOWED_PROPS)); + + (0, _handlersRegistry.registerHandler)(handler.handlerTag, handler); // use setImmediate to extract handlerTags, because all refs should be initialized + // when it's ran + + setImmediate(() => { + let requireToFail = []; + + if (handler.config.requireToFail) { + requireToFail = extractValidHandlerTags(handler.config.requireToFail); + } + + let simultaneousWith = []; + + if (handler.config.simultaneousWith) { + simultaneousWith = extractValidHandlerTags(handler.config.simultaneousWith); + } + + _RNGestureHandlerModule.default.updateGestureHandler(handler.handlerTag, (0, _gestureHandlerCommon.filterConfig)(handler.config, ALLOWED_PROPS, { + simultaneousHandlers: simultaneousWith, + waitFor: requireToFail + })); + }); + } + + preparedGesture.config = gesture; + + for (const gesture of preparedGesture.config) { + _RNGestureHandlerModule.default.attachGestureHandler(gesture.handlerTag, viewTag, !useAnimated // send direct events when using animatedGesture, device events otherwise + ); + } + + if (preparedGesture.animatedHandlers) { + preparedGesture.animatedHandlers.value = gesture.map(g => g.handlers); + } +} + +function updateHandlers(preparedGesture, gestureConfig, gesture) { + gestureConfig === null || gestureConfig === void 0 ? void 0 : gestureConfig.prepare(); + + for (let i = 0; i < gesture.length; i++) { + const handler = preparedGesture.config[i]; + gesture[i].handlerTag = handler.handlerTag; + gesture[i].handlers.handlerTag = handler.handlerTag; + } // use setImmediate to extract handlerTags, because when it's ran, all refs should be updated + // and handlerTags in BaseGesture references should be updated in the loop above (we need to wait + // in case of external relations) + + + setImmediate(() => { + for (let i = 0; i < gesture.length; i++) { + const handler = preparedGesture.config[i]; + handler.config = gesture[i].config; + handler.handlers = gesture[i].handlers; + handler.handlers.handlerTag = handler.handlerTag; + const requireToFail = extractValidHandlerTags(handler.config.requireToFail); + const simultaneousWith = extractValidHandlerTags(handler.config.simultaneousWith); + + _RNGestureHandlerModule.default.updateGestureHandler(handler.handlerTag, (0, _gestureHandlerCommon.filterConfig)(handler.config, ALLOWED_PROPS, { + simultaneousHandlers: simultaneousWith, + waitFor: requireToFail + })); + + (0, _handlersRegistry.registerHandler)(handler.handlerTag, handler); + } + + if (preparedGesture.animatedHandlers) { + preparedGesture.animatedHandlers.value = preparedGesture.config.map(g => g.handlers); + } + }); +} + +function needsToReattach(preparedGesture, gesture) { + if (gesture.length !== preparedGesture.config.length) { + return true; + } + + for (let i = 0; i < gesture.length; i++) { + if (gesture[i].handlerName !== preparedGesture.config[i].handlerName) { + return true; + } + } + + return false; +} + +function useAnimatedGesture(preparedGesture) { + if (!_reanimatedWrapper.Reanimated) { + return; + } + + function isStateChangeEvent(event) { + 'worklet'; // @ts-ignore Yes, the oldState prop is missing on GestureTouchEvent, that's the point + + return event.oldState != null; + } + + function isTouchEvent(event) { + 'worklet'; + + return event.eventType != null; + } + + function getHandler(type, gesture) { + 'worklet'; + + switch (type) { + case _gesture.CALLBACK_TYPE.BEGAN: + return gesture.onBegin; + + case _gesture.CALLBACK_TYPE.START: + return gesture.onStart; + + case _gesture.CALLBACK_TYPE.UPDATE: + return gesture.onUpdate; + + case _gesture.CALLBACK_TYPE.CHANGE: + return gesture.onChange; + + case _gesture.CALLBACK_TYPE.END: + return gesture.onEnd; + + case _gesture.CALLBACK_TYPE.FINALIZE: + return gesture.onFinalize; + + case _gesture.CALLBACK_TYPE.TOUCHES_DOWN: + return gesture.onTouchesDown; + + case _gesture.CALLBACK_TYPE.TOUCHES_MOVE: + return gesture.onTouchesMove; + + case _gesture.CALLBACK_TYPE.TOUCHES_UP: + return gesture.onTouchesUp; + + case _gesture.CALLBACK_TYPE.TOUCHES_CANCELLED: + return gesture.onTouchesCancelled; + } + } + + function touchEventTypeToCallbackType(eventType) { + 'worklet'; + + switch (eventType) { + case _EventType.EventType.TOUCHES_DOWN: + return _gesture.CALLBACK_TYPE.TOUCHES_DOWN; + + case _EventType.EventType.TOUCHES_MOVE: + return _gesture.CALLBACK_TYPE.TOUCHES_MOVE; + + case _EventType.EventType.TOUCHES_UP: + return _gesture.CALLBACK_TYPE.TOUCHES_UP; + + case _EventType.EventType.TOUCHES_CANCELLED: + return _gesture.CALLBACK_TYPE.TOUCHES_CANCELLED; + } + + return _gesture.CALLBACK_TYPE.UNDEFINED; + } + + function runWorklet(type, gesture, event, ...args) { + 'worklet'; + + const handler = getHandler(type, gesture); + + if (gesture.isWorklet[type]) { + // @ts-ignore Logic below makes sure the correct event is send to the + // correct handler. + handler === null || handler === void 0 ? void 0 : handler(event, ...args); + } else if (handler) { + console.warn('Animated gesture callback must be a worklet'); + } + } // Hooks are called conditionally, but the condition is whether the + // react-native-reanimated is installed, which shouldn't change while running + // eslint-disable-next-line react-hooks/rules-of-hooks + + + const sharedHandlersCallbacks = _reanimatedWrapper.Reanimated.useSharedValue(null); // eslint-disable-next-line react-hooks/rules-of-hooks + + + const lastUpdateEvent = _reanimatedWrapper.Reanimated.useSharedValue([]); // not every gesture needs a state controller, init them lazily + + + const stateControllers = []; + + const callback = event => { + 'worklet'; + + const currentCallback = sharedHandlersCallbacks.value; + + if (!currentCallback) { + return; + } + + for (let i = 0; i < currentCallback.length; i++) { + const gesture = currentCallback[i]; + + if (event.handlerTag === gesture.handlerTag) { + if (isStateChangeEvent(event)) { + if (event.oldState === _State.State.UNDETERMINED && event.state === _State.State.BEGAN) { + runWorklet(_gesture.CALLBACK_TYPE.BEGAN, gesture, event); + } else if ((event.oldState === _State.State.BEGAN || event.oldState === _State.State.UNDETERMINED) && event.state === _State.State.ACTIVE) { + runWorklet(_gesture.CALLBACK_TYPE.START, gesture, event); + lastUpdateEvent.value[gesture.handlerTag] = undefined; + } else if (event.oldState !== event.state && event.state === _State.State.END) { + if (event.oldState === _State.State.ACTIVE) { + runWorklet(_gesture.CALLBACK_TYPE.END, gesture, event, true); + } + + runWorklet(_gesture.CALLBACK_TYPE.FINALIZE, gesture, event, true); + } else if ((event.state === _State.State.FAILED || event.state === _State.State.CANCELLED) && event.state !== event.oldState) { + if (event.oldState === _State.State.ACTIVE) { + runWorklet(_gesture.CALLBACK_TYPE.END, gesture, event, false); + } + + runWorklet(_gesture.CALLBACK_TYPE.FINALIZE, gesture, event, false); + } + } else if (isTouchEvent(event)) { + if (!stateControllers[i]) { + stateControllers[i] = _gestureStateManager.GestureStateManager.create(event.handlerTag); + } + + if (event.eventType !== _EventType.EventType.UNDETERMINED) { + runWorklet(touchEventTypeToCallbackType(event.eventType), gesture, event, stateControllers[i]); + } + } else { + runWorklet(_gesture.CALLBACK_TYPE.UPDATE, gesture, event); + + if (gesture.onChange && gesture.changeEventCalculator) { + var _gesture$changeEventC; + + runWorklet(_gesture.CALLBACK_TYPE.CHANGE, gesture, (_gesture$changeEventC = gesture.changeEventCalculator) === null || _gesture$changeEventC === void 0 ? void 0 : _gesture$changeEventC.call(gesture, event, lastUpdateEvent.value[gesture.handlerTag])); + lastUpdateEvent.value[gesture.handlerTag] = event; + } + } + } + } + }; // eslint-disable-next-line react-hooks/rules-of-hooks + + + const event = _reanimatedWrapper.Reanimated.useEvent(callback, ['onGestureHandlerStateChange', 'onGestureHandlerEvent'], true); + + preparedGesture.animatedEventHandler = event; + preparedGesture.animatedHandlers = sharedHandlersCallbacks; +} + +const GestureDetector = props => { + var _gestureConfig$toGest, _gestureConfig$toGest2; + + const gestureConfig = props.gesture; + const gesture = (_gestureConfig$toGest = gestureConfig === null || gestureConfig === void 0 ? void 0 : (_gestureConfig$toGest2 = gestureConfig.toGestureArray) === null || _gestureConfig$toGest2 === void 0 ? void 0 : _gestureConfig$toGest2.call(gestureConfig)) !== null && _gestureConfig$toGest !== void 0 ? _gestureConfig$toGest : []; + const useAnimated = gesture.find(gesture => gesture.handlers.isWorklet.reduce((prev, current) => prev || current)) != null; + const viewRef = (0, _react.useRef)(null); + const firstRenderRef = (0, _react.useRef)(true); + + const preparedGesture = _react.default.useRef({ + config: gesture, + animatedEventHandler: null, + animatedHandlers: null, + firstExecution: true, + useAnimated: useAnimated + }).current; + + if (useAnimated !== preparedGesture.useAnimated) { + throw new Error('You cannot change whether you are using gesture or animatedGesture while the app is running'); + } + + if (preparedGesture.firstExecution) { + var _gestureConfig$initia; + + gestureConfig === null || gestureConfig === void 0 ? void 0 : (_gestureConfig$initia = gestureConfig.initialize) === null || _gestureConfig$initia === void 0 ? void 0 : _gestureConfig$initia.call(gestureConfig); + } + + if (useAnimated) { + // Whether animatedGesture or gesture is used shouldn't change + // during while an app is running + // eslint-disable-next-line react-hooks/rules-of-hooks + useAnimatedGesture(preparedGesture); + } + + (0, _react.useEffect)(() => { + firstRenderRef.current = true; + const viewTag = (0, _gestureHandlerCommon.findNodeHandle)(viewRef.current); + attachHandlers({ + preparedGesture, + gestureConfig, + gesture, + viewTag, + useAnimated + }); + return () => { + dropHandlers(preparedGesture); + }; + }, []); + (0, _react.useEffect)(() => { + if (!firstRenderRef.current) { + const viewTag = (0, _gestureHandlerCommon.findNodeHandle)(viewRef.current); + + if (needsToReattach(preparedGesture, gesture)) { + dropHandlers(preparedGesture); + attachHandlers({ + preparedGesture, + gestureConfig, + gesture, + viewTag, + useAnimated + }); + } else { + updateHandlers(preparedGesture, gestureConfig, gesture); + } + } else { + firstRenderRef.current = false; + } + }, [props]); + + if (useAnimated) { + return /*#__PURE__*/_react.default.createElement(AnimatedWrap, { + ref: viewRef, + onGestureHandlerEvent: preparedGesture.animatedEventHandler + }, props.children); + } else { + return /*#__PURE__*/_react.default.createElement(Wrap, { + ref: viewRef + }, props.children); + } +}; + +exports.GestureDetector = GestureDetector; + +class Wrap extends _react.default.Component { + render() { + // I don't think that fighting with types over such a simple function is worth it + // The only thing it does is add 'collapsable: false' to the child component + // to make sure it is in the native view hierarchy so the detector can find + // correct viewTag to attach to. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const child = _react.default.Children.only(this.props.children); + + return /*#__PURE__*/_react.default.cloneElement(child, { + collapsable: false + }, // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + child.props.children); + } + +} + +const AnimatedWrap = (_Reanimated$default$c = _reanimatedWrapper.Reanimated === null || _reanimatedWrapper.Reanimated === void 0 ? void 0 : (_Reanimated$default = _reanimatedWrapper.Reanimated.default) === null || _Reanimated$default === void 0 ? void 0 : _Reanimated$default.createAnimatedComponent(Wrap)) !== null && _Reanimated$default$c !== void 0 ? _Reanimated$default$c : Wrap; +//# sourceMappingURL=GestureDetector.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/GestureDetector.js.map b/lib/commonjs/handlers/gestures/GestureDetector.js.map new file mode 100644 index 0000000000..523dfcf312 --- /dev/null +++ b/lib/commonjs/handlers/gestures/GestureDetector.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureDetector.tsx"],"names":["ALLOWED_PROPS","baseGestureHandlerWithMonitorProps","tapGestureHandlerProps","panGestureHandlerProps","panGestureHandlerCustomNativeProps","longPressGestureHandlerProps","forceTouchGestureHandlerProps","flingGestureHandlerProps","convertToHandlerTag","ref","BaseGesture","handlerTag","current","extractValidHandlerTags","interactionGroup","map","filter","tag","dropHandlers","preparedGesture","handler","config","RNGestureHandlerModule","dropGestureHandler","attachHandlers","gestureConfig","gesture","viewTag","useAnimated","firstExecution","initialize","setImmediate","prepare","createGestureHandler","handlerName","requireToFail","simultaneousWith","updateGestureHandler","simultaneousHandlers","waitFor","attachGestureHandler","animatedHandlers","value","g","handlers","updateHandlers","i","length","needsToReattach","useAnimatedGesture","Reanimated","isStateChangeEvent","event","oldState","isTouchEvent","eventType","getHandler","type","CALLBACK_TYPE","BEGAN","onBegin","START","onStart","UPDATE","onUpdate","CHANGE","onChange","END","onEnd","FINALIZE","onFinalize","TOUCHES_DOWN","onTouchesDown","TOUCHES_MOVE","onTouchesMove","TOUCHES_UP","onTouchesUp","TOUCHES_CANCELLED","onTouchesCancelled","touchEventTypeToCallbackType","EventType","UNDEFINED","runWorklet","args","isWorklet","console","warn","sharedHandlersCallbacks","useSharedValue","lastUpdateEvent","stateControllers","callback","currentCallback","State","UNDETERMINED","state","ACTIVE","undefined","FAILED","CANCELLED","GestureStateManager","create","changeEventCalculator","useEvent","animatedEventHandler","GestureDetector","props","toGestureArray","find","reduce","prev","viewRef","firstRenderRef","React","useRef","Error","children","Wrap","Component","render","child","Children","only","cloneElement","collapsable","AnimatedWrap","default","createAnimatedComponent"],"mappings":";;;;;;;AAAA;;AACA;;AAOA;;AACA;;AACA;;AACA;;AAQA;;AAIA;;AACA;;AACA;;AACA;;AAIA;;AACA;;AACA;;;;;;;;;;AAGA,MAAMA,aAAa,GAAG,CACpB,GAAGC,wDADiB,EAEpB,GAAGC,yCAFiB,EAGpB,GAAGC,yCAHiB,EAIpB,GAAGC,qDAJiB,EAKpB,GAAGC,qDALiB,EAMpB,GAAGC,uDANiB,EAOpB,GAAGC,6CAPiB,CAAtB;;AAoBA,SAASC,mBAAT,CAA6BC,GAA7B,EAAsD;AACpD,MAAI,OAAOA,GAAP,KAAe,QAAnB,EAA6B;AAC3B,WAAOA,GAAP;AACD,GAFD,MAEO,IAAIA,GAAG,YAAYC,oBAAnB,EAAgC;AACrC,WAAOD,GAAG,CAACE,UAAX;AACD,GAFM,MAEA;AAAA;;AACL;AACA;AACA,oDAAOF,GAAG,CAACG,OAAX,iDAAO,aAAaD,UAApB,yEAAkC,CAAC,CAAnC;AACD;AACF;;AAED,SAASE,uBAAT,CAAiCC,gBAAjC,EAA6E;AAAA;;AAC3E,kCACEA,gBADF,aACEA,gBADF,iDACEA,gBAAgB,CAAEC,GAAlB,CAAsBP,mBAAtB,CADF,2DACE,uBAA4CQ,MAA5C,CAAoDC,GAAD,IAASA,GAAG,GAAG,CAAlE,CADF,yEAC0E,EAD1E;AAGD;;AAED,SAASC,YAAT,CAAsBC,eAAtB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,OAGGE,KAAK,CAACU,QAHT,CADF;AAOD,GARD,MAQO;AACL,wBAAO,6BAAC,IAAD;AAAM,MAAA,GAAG,EAAEL;AAAX,OAAqBL,KAAK,CAACU,QAA3B,CAAP;AACD;AACF,CArFM;;;;AAuFP,MAAMC,IAAN,SAAmBJ,eAAMK,SAAzB,CAAwE;AACtEC,EAAAA,MAAM,GAAG;AACP;AACA;AACA;AACA;AACA;AACA,UAAMC,KAAU,GAAGP,eAAMQ,QAAN,CAAeC,IAAf,CAAoB,KAAKhB,KAAL,CAAWU,QAA/B,CAAnB;;AAEA,wBAAOH,eAAMU,YAAN,CACLH,KADK,EAEL;AAAEI,MAAAA,WAAW,EAAE;AAAf,KAFK,EAGL;AACAJ,IAAAA,KAAK,CAACd,KAAN,CAAYU,QAJP,CAAP;AAMD;;AAfqE;;AAkBxE,MAAMS,YAAY,4BAAG3E,6BAAH,aAAGA,6BAAH,8CAAGA,8BAAY4E,OAAf,wDAAG,oBAAqBC,uBAArB,CAA6CV,IAA7C,CAAH,yEAAyDA,IAA3E","sourcesContent":["import React, { useEffect, useRef } from 'react';\nimport {\n GestureType,\n HandlerCallbacks,\n BaseGesture,\n GestureRef,\n CALLBACK_TYPE,\n} from './gesture';\nimport { Reanimated, SharedValue } from './reanimatedWrapper';\nimport { registerHandler, unregisterHandler } from '../handlersRegistry';\nimport RNGestureHandlerModule from '../../RNGestureHandlerModule';\nimport {\n baseGestureHandlerWithMonitorProps,\n filterConfig,\n findNodeHandle,\n GestureTouchEvent,\n GestureUpdateEvent,\n GestureStateChangeEvent,\n} from '../gestureHandlerCommon';\nimport {\n GestureStateManager,\n GestureStateManagerType,\n} from './gestureStateManager';\nimport { flingGestureHandlerProps } from '../FlingGestureHandler';\nimport { forceTouchGestureHandlerProps } from '../ForceTouchGestureHandler';\nimport { longPressGestureHandlerProps } from '../LongPressGestureHandler';\nimport {\n panGestureHandlerProps,\n panGestureHandlerCustomNativeProps,\n} from '../PanGestureHandler';\nimport { tapGestureHandlerProps } from '../TapGestureHandler';\nimport { State } from '../../State';\nimport { EventType } from '../../EventType';\nimport { ComposedGesture } from './gestureComposition';\n\nconst ALLOWED_PROPS = [\n ...baseGestureHandlerWithMonitorProps,\n ...tapGestureHandlerProps,\n ...panGestureHandlerProps,\n ...panGestureHandlerCustomNativeProps,\n ...longPressGestureHandlerProps,\n ...forceTouchGestureHandlerProps,\n ...flingGestureHandlerProps,\n];\n\nexport type GestureConfigReference = {\n config: GestureType[];\n animatedEventHandler: unknown;\n animatedHandlers: SharedValue<\n HandlerCallbacks>[] | null\n > | null;\n firstExecution: boolean;\n useAnimated: boolean;\n};\n\nfunction convertToHandlerTag(ref: GestureRef): number {\n if (typeof ref === 'number') {\n return ref;\n } else if (ref instanceof BaseGesture) {\n return ref.handlerTag;\n } else {\n // @ts-ignore in this case it should be a ref either to gesture object or\n // a gesture handler component, in both cases handlerTag property exists\n return ref.current?.handlerTag ?? -1;\n }\n}\n\nfunction extractValidHandlerTags(interactionGroup: GestureRef[] | undefined) {\n return (\n interactionGroup?.map(convertToHandlerTag)?.filter((tag) => tag > 0) ?? []\n );\n}\n\nfunction dropHandlers(preparedGesture: GestureConfigReference) {\n for (const handler of preparedGesture.config) {\n RNGestureHandlerModule.dropGestureHandler(handler.handlerTag);\n\n unregisterHandler(handler.handlerTag);\n }\n}\n\ninterface AttachHandlersConfig {\n preparedGesture: GestureConfigReference;\n gestureConfig: ComposedGesture | GestureType | undefined;\n gesture: GestureType[];\n viewTag: number;\n useAnimated: boolean;\n}\n\nfunction attachHandlers({\n preparedGesture,\n gestureConfig,\n gesture,\n viewTag,\n useAnimated,\n}: AttachHandlersConfig) {\n if (!preparedGesture.firstExecution) {\n gestureConfig?.initialize();\n } else {\n preparedGesture.firstExecution = false;\n }\n\n // use setImmediate to extract handlerTags, because all refs should be initialized\n // when it's ran\n setImmediate(() => {\n gestureConfig?.prepare();\n });\n\n for (const handler of gesture) {\n RNGestureHandlerModule.createGestureHandler(\n handler.handlerName,\n handler.handlerTag,\n filterConfig(handler.config, ALLOWED_PROPS)\n );\n\n registerHandler(handler.handlerTag, handler);\n\n // use setImmediate to extract handlerTags, because all refs should be initialized\n // when it's ran\n setImmediate(() => {\n let requireToFail: number[] = [];\n if (handler.config.requireToFail) {\n requireToFail = extractValidHandlerTags(handler.config.requireToFail);\n }\n\n let simultaneousWith: number[] = [];\n if (handler.config.simultaneousWith) {\n simultaneousWith = extractValidHandlerTags(\n handler.config.simultaneousWith\n );\n }\n\n RNGestureHandlerModule.updateGestureHandler(\n handler.handlerTag,\n filterConfig(handler.config, ALLOWED_PROPS, {\n simultaneousHandlers: simultaneousWith,\n waitFor: requireToFail,\n })\n );\n });\n }\n preparedGesture.config = gesture;\n\n for (const gesture of preparedGesture.config) {\n RNGestureHandlerModule.attachGestureHandler(\n gesture.handlerTag,\n viewTag,\n !useAnimated // send direct events when using animatedGesture, device events otherwise\n );\n }\n\n if (preparedGesture.animatedHandlers) {\n preparedGesture.animatedHandlers.value = (gesture.map(\n (g) => g.handlers\n ) as unknown) as HandlerCallbacks>[];\n }\n}\n\nfunction updateHandlers(\n preparedGesture: GestureConfigReference,\n gestureConfig: ComposedGesture | GestureType | undefined,\n gesture: GestureType[]\n) {\n gestureConfig?.prepare();\n\n for (let i = 0; i < gesture.length; i++) {\n const handler = preparedGesture.config[i];\n\n gesture[i].handlerTag = handler.handlerTag;\n gesture[i].handlers.handlerTag = handler.handlerTag;\n }\n\n // use setImmediate to extract handlerTags, because when it's ran, all refs should be updated\n // and handlerTags in BaseGesture references should be updated in the loop above (we need to wait\n // in case of external relations)\n setImmediate(() => {\n for (let i = 0; i < gesture.length; i++) {\n const handler = preparedGesture.config[i];\n\n handler.config = gesture[i].config;\n handler.handlers = gesture[i].handlers;\n handler.handlers.handlerTag = handler.handlerTag;\n\n const requireToFail = extractValidHandlerTags(\n handler.config.requireToFail\n );\n\n const simultaneousWith = extractValidHandlerTags(\n handler.config.simultaneousWith\n );\n\n RNGestureHandlerModule.updateGestureHandler(\n handler.handlerTag,\n filterConfig(handler.config, ALLOWED_PROPS, {\n simultaneousHandlers: simultaneousWith,\n waitFor: requireToFail,\n })\n );\n\n registerHandler(handler.handlerTag, handler);\n }\n\n if (preparedGesture.animatedHandlers) {\n preparedGesture.animatedHandlers.value = (preparedGesture.config.map(\n (g) => g.handlers\n ) as unknown) as HandlerCallbacks>[];\n }\n });\n}\n\nfunction needsToReattach(\n preparedGesture: GestureConfigReference,\n gesture: GestureType[]\n) {\n if (gesture.length !== preparedGesture.config.length) {\n return true;\n }\n for (let i = 0; i < gesture.length; i++) {\n if (gesture[i].handlerName !== preparedGesture.config[i].handlerName) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction useAnimatedGesture(preparedGesture: GestureConfigReference) {\n if (!Reanimated) {\n return;\n }\n\n function isStateChangeEvent(\n event: GestureUpdateEvent | GestureStateChangeEvent | GestureTouchEvent\n ): event is GestureStateChangeEvent {\n 'worklet';\n // @ts-ignore Yes, the oldState prop is missing on GestureTouchEvent, that's the point\n return event.oldState != null;\n }\n\n function isTouchEvent(\n event: GestureUpdateEvent | GestureStateChangeEvent | GestureTouchEvent\n ): event is GestureTouchEvent {\n 'worklet';\n return event.eventType != null;\n }\n\n function getHandler(\n type: CALLBACK_TYPE,\n gesture: HandlerCallbacks>\n ) {\n 'worklet';\n switch (type) {\n case CALLBACK_TYPE.BEGAN:\n return gesture.onBegin;\n case CALLBACK_TYPE.START:\n return gesture.onStart;\n case CALLBACK_TYPE.UPDATE:\n return gesture.onUpdate;\n case CALLBACK_TYPE.CHANGE:\n return gesture.onChange;\n case CALLBACK_TYPE.END:\n return gesture.onEnd;\n case CALLBACK_TYPE.FINALIZE:\n return gesture.onFinalize;\n case CALLBACK_TYPE.TOUCHES_DOWN:\n return gesture.onTouchesDown;\n case CALLBACK_TYPE.TOUCHES_MOVE:\n return gesture.onTouchesMove;\n case CALLBACK_TYPE.TOUCHES_UP:\n return gesture.onTouchesUp;\n case CALLBACK_TYPE.TOUCHES_CANCELLED:\n return gesture.onTouchesCancelled;\n }\n }\n\n function touchEventTypeToCallbackType(eventType: EventType): CALLBACK_TYPE {\n 'worklet';\n switch (eventType) {\n case EventType.TOUCHES_DOWN:\n return CALLBACK_TYPE.TOUCHES_DOWN;\n case EventType.TOUCHES_MOVE:\n return CALLBACK_TYPE.TOUCHES_MOVE;\n case EventType.TOUCHES_UP:\n return CALLBACK_TYPE.TOUCHES_UP;\n case EventType.TOUCHES_CANCELLED:\n return CALLBACK_TYPE.TOUCHES_CANCELLED;\n }\n return CALLBACK_TYPE.UNDEFINED;\n }\n\n function runWorklet(\n type: CALLBACK_TYPE,\n gesture: HandlerCallbacks>,\n event: GestureStateChangeEvent | GestureUpdateEvent | GestureTouchEvent,\n ...args: any[]\n ) {\n 'worklet';\n const handler = getHandler(type, gesture);\n if (gesture.isWorklet[type]) {\n // @ts-ignore Logic below makes sure the correct event is send to the\n // correct handler.\n handler?.(event, ...args);\n } else if (handler) {\n console.warn('Animated gesture callback must be a worklet');\n }\n }\n\n // Hooks are called conditionally, but the condition is whether the\n // react-native-reanimated is installed, which shouldn't change while running\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const sharedHandlersCallbacks = Reanimated.useSharedValue<\n HandlerCallbacks>[] | null\n >(null);\n\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const lastUpdateEvent = Reanimated.useSharedValue<\n (GestureUpdateEvent | undefined)[]\n >([]);\n\n // not every gesture needs a state controller, init them lazily\n const stateControllers: GestureStateManagerType[] = [];\n\n const callback = (\n event: GestureStateChangeEvent | GestureUpdateEvent | GestureTouchEvent\n ) => {\n 'worklet';\n\n const currentCallback = sharedHandlersCallbacks.value;\n if (!currentCallback) {\n return;\n }\n\n for (let i = 0; i < currentCallback.length; i++) {\n const gesture = currentCallback[i];\n\n if (event.handlerTag === gesture.handlerTag) {\n if (isStateChangeEvent(event)) {\n if (\n event.oldState === State.UNDETERMINED &&\n event.state === State.BEGAN\n ) {\n runWorklet(CALLBACK_TYPE.BEGAN, gesture, event);\n } else if (\n (event.oldState === State.BEGAN ||\n event.oldState === State.UNDETERMINED) &&\n event.state === State.ACTIVE\n ) {\n runWorklet(CALLBACK_TYPE.START, gesture, event);\n lastUpdateEvent.value[gesture.handlerTag] = undefined;\n } else if (\n event.oldState !== event.state &&\n event.state === State.END\n ) {\n if (event.oldState === State.ACTIVE) {\n runWorklet(CALLBACK_TYPE.END, gesture, event, true);\n }\n runWorklet(CALLBACK_TYPE.FINALIZE, gesture, event, true);\n } else if (\n (event.state === State.FAILED || event.state === State.CANCELLED) &&\n event.state !== event.oldState\n ) {\n if (event.oldState === State.ACTIVE) {\n runWorklet(CALLBACK_TYPE.END, gesture, event, false);\n }\n runWorklet(CALLBACK_TYPE.FINALIZE, gesture, event, false);\n }\n } else if (isTouchEvent(event)) {\n if (!stateControllers[i]) {\n stateControllers[i] = GestureStateManager.create(event.handlerTag);\n }\n\n if (event.eventType !== EventType.UNDETERMINED) {\n runWorklet(\n touchEventTypeToCallbackType(event.eventType),\n gesture,\n event,\n stateControllers[i]\n );\n }\n } else {\n runWorklet(CALLBACK_TYPE.UPDATE, gesture, event);\n\n if (gesture.onChange && gesture.changeEventCalculator) {\n runWorklet(\n CALLBACK_TYPE.CHANGE,\n gesture,\n gesture.changeEventCalculator?.(\n event,\n lastUpdateEvent.value[gesture.handlerTag]\n )\n );\n\n lastUpdateEvent.value[gesture.handlerTag] = event;\n }\n }\n }\n }\n };\n\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const event = Reanimated.useEvent(\n callback,\n ['onGestureHandlerStateChange', 'onGestureHandlerEvent'],\n true\n );\n\n preparedGesture.animatedEventHandler = event;\n preparedGesture.animatedHandlers = sharedHandlersCallbacks;\n}\n\ninterface GestureDetectorProps {\n gesture?: ComposedGesture | GestureType;\n}\nexport const GestureDetector: React.FunctionComponent = (\n props\n) => {\n const gestureConfig = props.gesture;\n const gesture = gestureConfig?.toGestureArray?.() ?? [];\n const useAnimated =\n gesture.find((gesture) =>\n gesture.handlers.isWorklet.reduce((prev, current) => prev || current)\n ) != null;\n const viewRef = useRef(null);\n const firstRenderRef = useRef(true);\n\n const preparedGesture = React.useRef({\n config: gesture,\n animatedEventHandler: null,\n animatedHandlers: null,\n firstExecution: true,\n useAnimated: useAnimated,\n }).current;\n\n if (useAnimated !== preparedGesture.useAnimated) {\n throw new Error(\n 'You cannot change whether you are using gesture or animatedGesture while the app is running'\n );\n }\n\n if (preparedGesture.firstExecution) {\n gestureConfig?.initialize?.();\n }\n\n if (useAnimated) {\n // Whether animatedGesture or gesture is used shouldn't change\n // during while an app is running\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useAnimatedGesture(preparedGesture);\n }\n\n useEffect(() => {\n firstRenderRef.current = true;\n const viewTag = findNodeHandle(viewRef.current) as number;\n attachHandlers({\n preparedGesture,\n gestureConfig,\n gesture,\n viewTag,\n useAnimated,\n });\n\n return () => {\n dropHandlers(preparedGesture);\n };\n }, []);\n\n useEffect(() => {\n if (!firstRenderRef.current) {\n const viewTag = findNodeHandle(viewRef.current) as number;\n\n if (needsToReattach(preparedGesture, gesture)) {\n dropHandlers(preparedGesture);\n attachHandlers({\n preparedGesture,\n gestureConfig,\n gesture,\n viewTag,\n useAnimated,\n });\n } else {\n updateHandlers(preparedGesture, gestureConfig, gesture);\n }\n } else {\n firstRenderRef.current = false;\n }\n }, [props]);\n\n if (useAnimated) {\n return (\n \n {props.children}\n \n );\n } else {\n return {props.children};\n }\n};\n\nclass Wrap extends React.Component<{ onGestureHandlerEvent?: unknown }> {\n render() {\n // I don't think that fighting with types over such a simple function is worth it\n // The only thing it does is add 'collapsable: false' to the child component\n // to make sure it is in the native view hierarchy so the detector can find\n // correct viewTag to attach to.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const child: any = React.Children.only(this.props.children);\n\n return React.cloneElement(\n child,\n { collapsable: false },\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n child.props.children\n );\n }\n}\n\nconst AnimatedWrap = Reanimated?.default?.createAnimatedComponent(Wrap) ?? Wrap;\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/eventReceiver.js b/lib/commonjs/handlers/gestures/eventReceiver.js new file mode 100644 index 0000000000..a51d62ce8a --- /dev/null +++ b/lib/commonjs/handlers/gestures/eventReceiver.js @@ -0,0 +1,135 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.startListening = startListening; +exports.stopListening = stopListening; + +var _reactNative = require("react-native"); + +var _State = require("../../State"); + +var _EventType = require("../../EventType"); + +var _handlersRegistry = require("../handlersRegistry"); + +let gestureHandlerEventSubscription = null; +let gestureHandlerStateChangeEventSubscription = null; +const dummyStateManager = { + begin: () => { + console.warn('You have to use react-native-reanimated in order to control the state of the gesture.'); + }, + activate: () => { + console.warn('You have to use react-native-reanimated in order to control the state of the gesture.'); + }, + end: () => { + console.warn('You have to use react-native-reanimated in order to control the state of the gesture.'); + }, + fail: () => { + console.warn('You have to use react-native-reanimated in order to control the state of the gesture.'); + } +}; +const lastUpdateEvent = []; + +function isStateChangeEvent(event) { + // @ts-ignore oldState doesn't exist on GestureTouchEvent and that's the point + return event.oldState != null; +} + +function isTouchEvent(event) { + return event.eventType != null; +} + +function onGestureHandlerEvent(event) { + var _handler$handlers7, _handler$handlers7$on, _handler$handlers8, _handler$handlers8$on, _handler$handlers9, _handler$handlers9$on, _handler$handlers10, _handler$handlers10$o; + + const handler = (0, _handlersRegistry.findHandler)(event.handlerTag); + + if (handler) { + if (isStateChangeEvent(event)) { + if (event.oldState === _State.State.UNDETERMINED && event.state === _State.State.BEGAN) { + var _handler$handlers$onB, _handler$handlers; + + (_handler$handlers$onB = (_handler$handlers = handler.handlers).onBegin) === null || _handler$handlers$onB === void 0 ? void 0 : _handler$handlers$onB.call(_handler$handlers, event); + } else if ((event.oldState === _State.State.BEGAN || event.oldState === _State.State.UNDETERMINED) && event.state === _State.State.ACTIVE) { + var _handler$handlers$onS, _handler$handlers2; + + (_handler$handlers$onS = (_handler$handlers2 = handler.handlers).onStart) === null || _handler$handlers$onS === void 0 ? void 0 : _handler$handlers$onS.call(_handler$handlers2, event); + lastUpdateEvent[handler.handlers.handlerTag] = event; + } else if (event.oldState !== event.state && event.state === _State.State.END) { + var _handler$handlers$onF, _handler$handlers4; + + if (event.oldState === _State.State.ACTIVE) { + var _handler$handlers$onE, _handler$handlers3; + + (_handler$handlers$onE = (_handler$handlers3 = handler.handlers).onEnd) === null || _handler$handlers$onE === void 0 ? void 0 : _handler$handlers$onE.call(_handler$handlers3, event, true); + } + + (_handler$handlers$onF = (_handler$handlers4 = handler.handlers).onFinalize) === null || _handler$handlers$onF === void 0 ? void 0 : _handler$handlers$onF.call(_handler$handlers4, event, true); + lastUpdateEvent[handler.handlers.handlerTag] = undefined; + } else if ((event.state === _State.State.FAILED || event.state === _State.State.CANCELLED) && event.oldState !== event.state) { + var _handler$handlers$onF2, _handler$handlers6; + + if (event.oldState === _State.State.ACTIVE) { + var _handler$handlers$onE2, _handler$handlers5; + + (_handler$handlers$onE2 = (_handler$handlers5 = handler.handlers).onEnd) === null || _handler$handlers$onE2 === void 0 ? void 0 : _handler$handlers$onE2.call(_handler$handlers5, event, false); + } + + (_handler$handlers$onF2 = (_handler$handlers6 = handler.handlers).onFinalize) === null || _handler$handlers$onF2 === void 0 ? void 0 : _handler$handlers$onF2.call(_handler$handlers6, event, false); + lastUpdateEvent[handler.handlers.handlerTag] = undefined; + } + } else if (isTouchEvent(event)) { + switch (event.eventType) { + case _EventType.EventType.TOUCHES_DOWN: + (_handler$handlers7 = handler.handlers) === null || _handler$handlers7 === void 0 ? void 0 : (_handler$handlers7$on = _handler$handlers7.onTouchesDown) === null || _handler$handlers7$on === void 0 ? void 0 : _handler$handlers7$on.call(_handler$handlers7, event, dummyStateManager); + break; + + case _EventType.EventType.TOUCHES_MOVE: + (_handler$handlers8 = handler.handlers) === null || _handler$handlers8 === void 0 ? void 0 : (_handler$handlers8$on = _handler$handlers8.onTouchesMove) === null || _handler$handlers8$on === void 0 ? void 0 : _handler$handlers8$on.call(_handler$handlers8, event, dummyStateManager); + break; + + case _EventType.EventType.TOUCHES_UP: + (_handler$handlers9 = handler.handlers) === null || _handler$handlers9 === void 0 ? void 0 : (_handler$handlers9$on = _handler$handlers9.onTouchesUp) === null || _handler$handlers9$on === void 0 ? void 0 : _handler$handlers9$on.call(_handler$handlers9, event, dummyStateManager); + break; + + case _EventType.EventType.TOUCHES_CANCELLED: + (_handler$handlers10 = handler.handlers) === null || _handler$handlers10 === void 0 ? void 0 : (_handler$handlers10$o = _handler$handlers10.onTouchesCancelled) === null || _handler$handlers10$o === void 0 ? void 0 : _handler$handlers10$o.call(_handler$handlers10, event, dummyStateManager); + break; + } + } else { + var _handler$handlers$onU, _handler$handlers11; + + (_handler$handlers$onU = (_handler$handlers11 = handler.handlers).onUpdate) === null || _handler$handlers$onU === void 0 ? void 0 : _handler$handlers$onU.call(_handler$handlers11, event); + + if (handler.handlers.onChange && handler.handlers.changeEventCalculator) { + var _handler$handlers$onC, _handler$handlers12, _handler$handlers$cha, _handler$handlers13; + + (_handler$handlers$onC = (_handler$handlers12 = handler.handlers).onChange) === null || _handler$handlers$onC === void 0 ? void 0 : _handler$handlers$onC.call(_handler$handlers12, (_handler$handlers$cha = (_handler$handlers13 = handler.handlers).changeEventCalculator) === null || _handler$handlers$cha === void 0 ? void 0 : _handler$handlers$cha.call(_handler$handlers13, event, lastUpdateEvent[handler.handlers.handlerTag])); + lastUpdateEvent[handler.handlers.handlerTag] = event; + } + } + } +} + +function startListening() { + stopListening(); + gestureHandlerEventSubscription = _reactNative.DeviceEventEmitter.addListener('onGestureHandlerEvent', onGestureHandlerEvent); + gestureHandlerStateChangeEventSubscription = _reactNative.DeviceEventEmitter.addListener('onGestureHandlerStateChange', onGestureHandlerEvent); +} + +function stopListening() { + if (gestureHandlerEventSubscription) { + _reactNative.DeviceEventEmitter.removeSubscription(gestureHandlerEventSubscription); + + gestureHandlerEventSubscription = null; + } + + if (gestureHandlerStateChangeEventSubscription) { + _reactNative.DeviceEventEmitter.removeSubscription(gestureHandlerStateChangeEventSubscription); + + gestureHandlerStateChangeEventSubscription = null; + } +} +//# sourceMappingURL=eventReceiver.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/eventReceiver.js.map b/lib/commonjs/handlers/gestures/eventReceiver.js.map new file mode 100644 index 0000000000..f1fe7812a8 --- /dev/null +++ b/lib/commonjs/handlers/gestures/eventReceiver.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["eventReceiver.ts"],"names":["gestureHandlerEventSubscription","gestureHandlerStateChangeEventSubscription","dummyStateManager","begin","console","warn","activate","end","fail","lastUpdateEvent","isStateChangeEvent","event","oldState","isTouchEvent","eventType","onGestureHandlerEvent","handler","handlerTag","State","UNDETERMINED","state","BEGAN","handlers","onBegin","ACTIVE","onStart","END","onEnd","onFinalize","undefined","FAILED","CANCELLED","EventType","TOUCHES_DOWN","onTouchesDown","TOUCHES_MOVE","onTouchesMove","TOUCHES_UP","onTouchesUp","TOUCHES_CANCELLED","onTouchesCancelled","onUpdate","onChange","changeEventCalculator","startListening","stopListening","DeviceEventEmitter","addListener","removeSubscription"],"mappings":";;;;;;;;AAAA;;AACA;;AACA;;AAOA;;AAGA,IAAIA,+BAA2D,GAAG,IAAlE;AACA,IAAIC,0CAAsE,GAAG,IAA7E;AAEA,MAAMC,iBAA0C,GAAG;AACjDC,EAAAA,KAAK,EAAE,MAAM;AACXC,IAAAA,OAAO,CAACC,IAAR,CACE,uFADF;AAGD,GALgD;AAMjDC,EAAAA,QAAQ,EAAE,MAAM;AACdF,IAAAA,OAAO,CAACC,IAAR,CACE,uFADF;AAGD,GAVgD;AAWjDE,EAAAA,GAAG,EAAE,MAAM;AACTH,IAAAA,OAAO,CAACC,IAAR,CACE,uFADF;AAGD,GAfgD;AAgBjDG,EAAAA,IAAI,EAAE,MAAM;AACVJ,IAAAA,OAAO,CAACC,IAAR,CACE,uFADF;AAGD;AApBgD,CAAnD;AAuBA,M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R,EAAiBmB,QAAjB,0GAA4B9B,KAA5B;;AAEA,UAAIK,OAAO,CAACM,QAAR,CAAiBoB,QAAjB,IAA6B1B,OAAO,CAACM,QAAR,CAAiBqB,qBAAlD,EAAyE;AAAA;;AACvE,wDAAA3B,OAAO,CAACM,QAAR,EAAiBoB,QAAjB,mIACE,uBAAA1B,OAAO,CAACM,QAAR,EAAiBqB,qBADnB,0DACE,gDACEhC,KADF,EAEEF,eAAe,CAACO,OAAO,CAACM,QAAR,CAAiBL,UAAlB,CAFjB,CADF;AAOAR,QAAAA,eAAe,CAACO,OAAO,CAACM,QAAR,CAAiBL,UAAlB,CAAf,GAA+CN,KAA/C;AACD;AACF;AACF;AACF;;AAEM,SAASiC,cAAT,GAA0B;AAC/BC,EAAAA,aAAa;AAEb7C,EAAAA,+BAA+B,GAAG8C,gCAAmBC,WAAnB,CAChC,uBADgC,EAEhChC,qBAFgC,CAAlC;AAKAd,EAAAA,0CAA0C,GAAG6C,gCAAmBC,WAAnB,CAC3C,6BAD2C,EAE3ChC,qBAF2C,CAA7C;AAID;;AAEM,SAAS8B,aAAT,GAAyB;AAC9B,MAAI7C,+BAAJ,EAAqC;AACnC8C,oCAAmBE,kBAAnB,CAAsChD,+BAAtC;;AAEAA,IAAAA,+BAA+B,GAAG,IAAlC;AACD;;AAED,MAAIC,0CAAJ,EAAgD;AAC9C6C,oCAAmBE,kBAAnB,CACE/C,0CADF;;AAIAA,IAAAA,0CAA0C,GAAG,IAA7C;AACD;AACF","sourcesContent":["import { DeviceEventEmitter, EmitterSubscription } from 'react-native';\nimport { State } from '../../State';\nimport { EventType } from '../../EventType';\nimport {\n GestureTouchEvent,\n GestureUpdateEvent,\n GestureStateChangeEvent,\n} from '../gestureHandlerCommon';\nimport { GestureStateManagerType } from './gestureStateManager';\nimport { findHandler } from '../handlersRegistry';\nimport { BaseGesture } from './gesture';\n\nlet gestureHandlerEventSubscription: EmitterSubscription | null = null;\nlet gestureHandlerStateChangeEventSubscription: EmitterSubscription | null = null;\n\nconst dummyStateManager: GestureStateManagerType = {\n begin: () => {\n console.warn(\n 'You have to use react-native-reanimated in order to control the state of the gesture.'\n );\n },\n activate: () => {\n console.warn(\n 'You have to use react-native-reanimated in order to control the state of the gesture.'\n );\n },\n end: () => {\n console.warn(\n 'You have to use react-native-reanimated in order to control the state of the gesture.'\n );\n },\n fail: () => {\n console.warn(\n 'You have to use react-native-reanimated in order to control the state of the gesture.'\n );\n },\n};\n\nconst lastUpdateEvent: (GestureUpdateEvent | undefined)[] = [];\n\nfunction isStateChangeEvent(\n event: GestureUpdateEvent | GestureStateChangeEvent | GestureTouchEvent\n): event is GestureStateChangeEvent {\n // @ts-ignore oldState doesn't exist on GestureTouchEvent and that's the point\n return event.oldState != null;\n}\n\nfunction isTouchEvent(\n event: GestureUpdateEvent | GestureStateChangeEvent | GestureTouchEvent\n): event is GestureTouchEvent {\n return event.eventType != null;\n}\n\nfunction onGestureHandlerEvent(\n event: GestureUpdateEvent | GestureStateChangeEvent | GestureTouchEvent\n) {\n const handler = findHandler(event.handlerTag) as BaseGesture<\n Record\n >;\n\n if (handler) {\n if (isStateChangeEvent(event)) {\n if (\n event.oldState === State.UNDETERMINED &&\n event.state === State.BEGAN\n ) {\n handler.handlers.onBegin?.(event);\n } else if (\n (event.oldState === State.BEGAN ||\n event.oldState === State.UNDETERMINED) &&\n event.state === State.ACTIVE\n ) {\n handler.handlers.onStart?.(event);\n lastUpdateEvent[handler.handlers.handlerTag] = event;\n } else if (event.oldState !== event.state && event.state === State.END) {\n if (event.oldState === State.ACTIVE) {\n handler.handlers.onEnd?.(event, true);\n }\n handler.handlers.onFinalize?.(event, true);\n lastUpdateEvent[handler.handlers.handlerTag] = undefined;\n } else if (\n (event.state === State.FAILED || event.state === State.CANCELLED) &&\n event.oldState !== event.state\n ) {\n if (event.oldState === State.ACTIVE) {\n handler.handlers.onEnd?.(event, false);\n }\n handler.handlers.onFinalize?.(event, false);\n lastUpdateEvent[handler.handlers.handlerTag] = undefined;\n }\n } else if (isTouchEvent(event)) {\n switch (event.eventType) {\n case EventType.TOUCHES_DOWN:\n handler.handlers?.onTouchesDown?.(event, dummyStateManager);\n break;\n case EventType.TOUCHES_MOVE:\n handler.handlers?.onTouchesMove?.(event, dummyStateManager);\n break;\n case EventType.TOUCHES_UP:\n handler.handlers?.onTouchesUp?.(event, dummyStateManager);\n break;\n case EventType.TOUCHES_CANCELLED:\n handler.handlers?.onTouchesCancelled?.(event, dummyStateManager);\n break;\n }\n } else {\n handler.handlers.onUpdate?.(event);\n\n if (handler.handlers.onChange && handler.handlers.changeEventCalculator) {\n handler.handlers.onChange?.(\n handler.handlers.changeEventCalculator?.(\n event,\n lastUpdateEvent[handler.handlers.handlerTag]\n )\n );\n\n lastUpdateEvent[handler.handlers.handlerTag] = event;\n }\n }\n }\n}\n\nexport function startListening() {\n stopListening();\n\n gestureHandlerEventSubscription = DeviceEventEmitter.addListener(\n 'onGestureHandlerEvent',\n onGestureHandlerEvent\n );\n\n gestureHandlerStateChangeEventSubscription = DeviceEventEmitter.addListener(\n 'onGestureHandlerStateChange',\n onGestureHandlerEvent\n );\n}\n\nexport function stopListening() {\n if (gestureHandlerEventSubscription) {\n DeviceEventEmitter.removeSubscription(gestureHandlerEventSubscription);\n\n gestureHandlerEventSubscription = null;\n }\n\n if (gestureHandlerStateChangeEventSubscription) {\n DeviceEventEmitter.removeSubscription(\n gestureHandlerStateChangeEventSubscription\n );\n\n gestureHandlerStateChangeEventSubscription = null;\n }\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/flingGesture.js b/lib/commonjs/handlers/gestures/flingGesture.js new file mode 100644 index 0000000000..4deac4cf39 --- /dev/null +++ b/lib/commonjs/handlers/gestures/flingGesture.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FlingGesture = void 0; + +var _gesture = require("./gesture"); + +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; } + +class FlingGesture extends _gesture.BaseGesture { + constructor() { + super(); + + _defineProperty(this, "config", {}); + + this.handlerName = 'FlingGestureHandler'; + } + + numberOfPointers(pointers) { + this.config.numberOfPointers = pointers; + return this; + } + + direction(direction) { + this.config.direction = direction; + return this; + } + +} + +exports.FlingGesture = FlingGesture; +//# sourceMappingURL=flingGesture.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/flingGesture.js.map b/lib/commonjs/handlers/gestures/flingGesture.js.map new file mode 100644 index 0000000000..074539a670 --- /dev/null +++ b/lib/commonjs/handlers/gestures/flingGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["flingGesture.ts"],"names":["FlingGesture","BaseGesture","constructor","handlerName","numberOfPointers","pointers","config","direction"],"mappings":";;;;;;;AAAA;;;;AAMO,MAAMA,YAAN,SAA2BC,oBAA3B,CAAwE;AAG7EC,EAAAA,WAAW,GAAG;AACZ;;AADY,oCAF0C,EAE1C;;AAGZ,SAAKC,WAAL,GAAmB,qBAAnB;AACD;;AAEDC,EAAAA,gBAAgB,CAACC,QAAD,EAAmB;AACjC,SAAKC,MAAL,CAAYF,gBAAZ,GAA+BC,QAA/B;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,SAAS,CAACA,SAAD,EAAoB;AAC3B,SAAKD,MAAL,CAAYC,SAAZ,GAAwBA,SAAxB;AACA,WAAO,IAAP;AACD;;AAjB4E","sourcesContent":["import { BaseGesture, BaseGestureConfig } from './gesture';\nimport {\n FlingGestureConfig,\n FlingGestureHandlerEventPayload,\n} from '../FlingGestureHandler';\n\nexport class FlingGesture extends BaseGesture {\n public config: BaseGestureConfig & FlingGestureConfig = {};\n\n constructor() {\n super();\n\n this.handlerName = 'FlingGestureHandler';\n }\n\n numberOfPointers(pointers: number) {\n this.config.numberOfPointers = pointers;\n return this;\n }\n\n direction(direction: number) {\n this.config.direction = direction;\n return this;\n }\n}\n\nexport type FlingGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/forceTouchGesture.js b/lib/commonjs/handlers/gestures/forceTouchGesture.js new file mode 100644 index 0000000000..5dbd1c5d15 --- /dev/null +++ b/lib/commonjs/handlers/gestures/forceTouchGesture.js @@ -0,0 +1,65 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ForceTouchGesture = void 0; + +var _gesture = require("./gesture"); + +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; } + +function changeEventCalculator(current, previous) { + 'worklet'; + + let changePayload; + + if (previous === undefined) { + changePayload = { + forceChange: current.force + }; + } else { + changePayload = { + forceChange: current.force - previous.force + }; + } + + return { ...current, + ...changePayload + }; +} + +class ForceTouchGesture extends _gesture.ContinousBaseGesture { + constructor() { + super(); + + _defineProperty(this, "config", {}); + + this.handlerName = 'ForceTouchGestureHandler'; + } + + minForce(force) { + this.config.minForce = force; + return this; + } + + maxForce(force) { + this.config.maxForce = force; + return this; + } + + feedbackOnActivation(value) { + this.config.feedbackOnActivation = value; + return this; + } + + onChange(callback) { + // @ts-ignore TS being overprotective, ForceTouchGestureHandlerEventPayload is Record + this.handlers.changeEventCalculator = changeEventCalculator; + return super.onChange(callback); + } + +} + +exports.ForceTouchGesture = ForceTouchGesture; +//# sourceMappingURL=forceTouchGesture.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/forceTouchGesture.js.map b/lib/commonjs/handlers/gestures/forceTouchGesture.js.map new file mode 100644 index 0000000000..3655a312db --- /dev/null +++ b/lib/commonjs/handlers/gestures/forceTouchGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["forceTouchGesture.ts"],"names":["changeEventCalculator","current","previous","changePayload","undefined","forceChange","force","ForceTouchGesture","ContinousBaseGesture","constructor","handlerName","minForce","config","maxForce","feedbackOnActivation","value","onChange","callback","handlers"],"mappings":";;;;;;;AAAA;;;;AAWA,SAASA,qBAAT,CACEC,OADF,EAEEC,QAFF,EAGE;AACA;;AACA,MAAIC,aAAJ;;AACA,MAAID,QAAQ,KAAKE,SAAjB,EAA4B;AAC1BD,IAAAA,aAAa,GAAG;AACdE,MAAAA,WAAW,EAAEJ,OAAO,CAACK;AADP,KAAhB;AAGD,GAJD,MAIO;AACLH,IAAAA,aAAa,GAAG;AACdE,MAAAA,WAAW,EAAEJ,OAAO,CAACK,KAAR,GAAgBJ,QAAQ,CAACI;AADxB,KAAhB;AAGD;;AAED,SAAO,EAAE,GAAGL,OAAL;AAAc,OAAGE;AAAjB,GAAP;AACD;;AAEM,MAAMI,iBAAN,SAAgCC,6BAAhC,CAGL;AAGAC,EAAAA,WAAW,GAAG;AACZ;;AADY,oCAF+C,EAE/C;;AAGZ,SAAKC,WAAL,GAAmB,0BAAnB;AACD;;AAEDC,EAAAA,QAAQ,CAACL,KAAD,EAAgB;AACtB,SAAKM,MAAL,CAAYD,QAAZ,GAAuBL,KAAvB;AACA,WAAO,IAAP;AACD;;AAEDO,EAAAA,QAAQ,CAACP,KAAD,EAAgB;AACtB,SAAKM,MAAL,CAAYC,QAAZ,GAAuBP,KAAvB;AACA,WAAO,IAAP;AACD;;AAEDQ,EAAAA,oBAAoB,CAACC,KAAD,EAAiB;AACnC,SAAKH,MAAL,CAAYE,oBAAZ,GAAmCC,KAAnC;AACA,WAAO,IAAP;AACD;;AAEDC,EAAAA,QAAQ,CACNC,QADM,EASN;AACA;AACA,SAAKC,QAAL,CAAclB,qBAAd,GAAsCA,qBAAtC;AACA,WAAO,MAAMgB,QAAN,CAAeC,QAAf,CAAP;AACD;;AArCD","sourcesContent":["import { BaseGestureConfig, ContinousBaseGesture } from './gesture';\nimport {\n ForceTouchGestureConfig,\n ForceTouchGestureHandlerEventPayload,\n} from '../ForceTouchGestureHandler';\nimport { GestureUpdateEvent } from '../gestureHandlerCommon';\n\ntype ForceTouchGestureChangeEventPayload = {\n forceChange: number;\n};\n\nfunction changeEventCalculator(\n current: GestureUpdateEvent,\n previous?: GestureUpdateEvent\n) {\n 'worklet';\n let changePayload: ForceTouchGestureChangeEventPayload;\n if (previous === undefined) {\n changePayload = {\n forceChange: current.force,\n };\n } else {\n changePayload = {\n forceChange: current.force - previous.force,\n };\n }\n\n return { ...current, ...changePayload };\n}\n\nexport class ForceTouchGesture extends ContinousBaseGesture<\n ForceTouchGestureHandlerEventPayload,\n ForceTouchGestureChangeEventPayload\n> {\n public config: BaseGestureConfig & ForceTouchGestureConfig = {};\n\n constructor() {\n super();\n\n this.handlerName = 'ForceTouchGestureHandler';\n }\n\n minForce(force: number) {\n this.config.minForce = force;\n return this;\n }\n\n maxForce(force: number) {\n this.config.maxForce = force;\n return this;\n }\n\n feedbackOnActivation(value: boolean) {\n this.config.feedbackOnActivation = value;\n return this;\n }\n\n onChange(\n callback: (\n event: GestureUpdateEvent<\n GestureUpdateEvent<\n ForceTouchGestureHandlerEventPayload &\n ForceTouchGestureChangeEventPayload\n >\n >\n ) => void\n ) {\n // @ts-ignore TS being overprotective, ForceTouchGestureHandlerEventPayload is Record\n this.handlers.changeEventCalculator = changeEventCalculator;\n return super.onChange(callback);\n }\n}\n\nexport type ForceTouchGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/gesture.js b/lib/commonjs/handlers/gestures/gesture.js new file mode 100644 index 0000000000..2b3e5e42be --- /dev/null +++ b/lib/commonjs/handlers/gestures/gesture.js @@ -0,0 +1,193 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ContinousBaseGesture = exports.BaseGesture = exports.Gesture = exports.CALLBACK_TYPE = void 0; + +var _handlersRegistry = require("../handlersRegistry"); + +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; } + +const CALLBACK_TYPE = { + UNDEFINED: 0, + BEGAN: 1, + START: 2, + UPDATE: 3, + CHANGE: 4, + END: 5, + FINALIZE: 6, + TOUCHES_DOWN: 7, + TOUCHES_MOVE: 8, + TOUCHES_UP: 9, + TOUCHES_CANCELLED: 10 +}; // Allow using CALLBACK_TYPE as object and type +// eslint-disable-next-line @typescript-eslint/no-redeclare + +exports.CALLBACK_TYPE = CALLBACK_TYPE; + +class Gesture {} + +exports.Gesture = Gesture; + +class BaseGesture extends Gesture { + constructor(...args) { + super(...args); + + _defineProperty(this, "handlerTag", -1); + + _defineProperty(this, "handlerName", ''); + + _defineProperty(this, "config", {}); + + _defineProperty(this, "handlers", { + handlerTag: -1, + isWorklet: [false, false, false, false] + }); + } + + addDependency(key, gesture) { + const value = this.config[key]; + this.config[key] = value ? Array().concat(value, gesture) : [gesture]; + } + + withRef(ref) { + this.config.ref = ref; + return this; + } // eslint-disable-next-line @typescript-eslint/ban-types + + + isWorklet(callback) { + //@ts-ignore if callback is a worklet, the property will be available, if not then the check will return false + return callback.__workletHash !== undefined; + } + + onBegin(callback) { + this.handlers.onBegin = callback; + this.handlers.isWorklet[CALLBACK_TYPE.BEGAN] = this.isWorklet(callback); + return this; + } + + onStart(callback) { + this.handlers.onStart = callback; + this.handlers.isWorklet[CALLBACK_TYPE.START] = this.isWorklet(callback); + return this; + } + + onEnd(callback) { + this.handlers.onEnd = callback; //@ts-ignore if callback is a worklet, the property will be available, if not then the check will return false + + this.handlers.isWorklet[CALLBACK_TYPE.END] = this.isWorklet(callback); + return this; + } + + onFinalize(callback) { + this.handlers.onFinalize = callback; //@ts-ignore if callback is a worklet, the property will be available, if not then the check will return false + + this.handlers.isWorklet[CALLBACK_TYPE.FINALIZE] = this.isWorklet(callback); + return this; + } + + onTouchesDown(callback) { + this.config.needsPointerData = true; + this.handlers.onTouchesDown = callback; + this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_DOWN] = this.isWorklet(callback); + return this; + } + + onTouchesMove(callback) { + this.config.needsPointerData = true; + this.handlers.onTouchesMove = callback; + this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_MOVE] = this.isWorklet(callback); + return this; + } + + onTouchesUp(callback) { + this.config.needsPointerData = true; + this.handlers.onTouchesUp = callback; + this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_UP] = this.isWorklet(callback); + return this; + } + + onTouchesCancelled(callback) { + this.config.needsPointerData = true; + this.handlers.onTouchesCancelled = callback; + this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_CANCELLED] = this.isWorklet(callback); + return this; + } + + enabled(enabled) { + this.config.enabled = enabled; + return this; + } + + shouldCancelWhenOutside(value) { + this.config.shouldCancelWhenOutside = value; + return this; + } + + hitSlop(hitSlop) { + this.config.hitSlop = hitSlop; + return this; + } + + simultaneousWithExternalGesture(...gestures) { + for (const gesture of gestures) { + this.addDependency('simultaneousWith', gesture); + } + + return this; + } + + requireExternalGestureToFail(...gestures) { + for (const gesture of gestures) { + this.addDependency('requireToFail', gesture); + } + + return this; + } + + initialize() { + this.handlerTag = (0, _handlersRegistry.getNextHandlerTag)(); + this.handlers = { ...this.handlers, + handlerTag: this.handlerTag + }; + + if (this.config.ref) { + this.config.ref.current = this; + } + } + + toGestureArray() { + return [this]; + } // eslint-disable-next-line @typescript-eslint/no-empty-function + + + prepare() {} + +} + +exports.BaseGesture = BaseGesture; + +class ContinousBaseGesture extends BaseGesture { + onUpdate(callback) { + this.handlers.onUpdate = callback; + this.handlers.isWorklet[CALLBACK_TYPE.UPDATE] = this.isWorklet(callback); + return this; + } + + onChange(callback) { + this.handlers.onChange = callback; + this.handlers.isWorklet[CALLBACK_TYPE.CHANGE] = this.isWorklet(callback); + return this; + } + + manualActivation(manualActivation) { + this.config.manualActivation = manualActivation; + return this; + } + +} + +exports.ContinousBaseGesture = ContinousBaseGesture; +//# sourceMappingURL=gesture.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/gesture.js.map b/lib/commonjs/handlers/gestures/gesture.js.map new file mode 100644 index 0000000000..aad27d9fde --- /dev/null +++ b/lib/commonjs/handlers/gestures/gesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["gesture.ts"],"names":["CALLBACK_TYPE","UNDEFINED","BEGAN","START","UPDATE","CHANGE","END","FINALIZE","TOUCHES_DOWN","TOUCHES_MOVE","TOUCHES_UP","TOUCHES_CANCELLED","Gesture","BaseGesture","handlerTag","isWorklet","addDependency","key","gesture","value","config","Array","concat","withRef","ref","callback","__workletHash","undefined","onBegin","handlers","onStart","onEnd","onFinalize","onTouchesDown","needsPointerData","onTouchesMove","onTouchesUp","onTouchesCancelled","enabled","shouldCancelWhenOutside","hitSlop","simultaneousWithExternalGesture","gestures","requireExternalGestureToFail","initialize","current","toGestureArray","prepare","ContinousBaseGesture","onUpdate","onChange","manualActivation"],"mappings":";;;;;;;AASA;;;;AAkEO,MAAMA,aAAa,GAAG;AAC3BC,EAAAA,SAAS,EAAE,CADgB;AAE3BC,EAAAA,KAAK,EAAE,CAFoB;AAG3BC,EAAAA,KAAK,EAAE,CAHoB;AAI3BC,EAAAA,MAAM,EAAE,CAJmB;AAK3BC,EAAAA,MAAM,EAAE,CALmB;AAM3BC,EAAAA,GAAG,EAAE,CANsB;AAO3BC,EAAAA,QAAQ,EAAE,CAPiB;AAQ3BC,EAAAA,YAAY,EAAE,CARa;AAS3BC,EAAAA,YAAY,EAAE,CATa;AAU3BC,EAAAA,UAAU,EAAE,CAVe;AAW3BC,EAAAA,iBAAiB,EAAE;AAXQ,CAAtB,C,CAcP;AACA;;;;AAGO,MAAeC,OAAf,CAAuB;;;;AAoBvB,MAAeC,WAAf,SAEGD,OAFH,CAEW;AAAA;AAAA;;AAAA,wCACI,CAAC,CADL;;AAAA,yCAEK,EAFL;;AAAA,oCAGmB,EAHnB;;AAAA,sCAImC;AACjDE,MAAAA,UAAU,EAAE,CAAC,CADoC;AAEjDC,MAAAA,SAAS,EAAE,CAAC,KAAD,EAAQ,KAAR,EAAe,KAAf,EAAsB,KAAtB;AAFsC,KAJnC;AAAA;;AASRC,EAAAA,aAAa,CACnBC,GADmB,EAEnBC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AAL,CAAeU,QAAf,CAAhD;AACA,WAAO,IAAP;AACD;;AAEDyB,EAAAA,QAAQ,CACNzB,QADM,EAIN;AACA,SAAKI,QAAL,CAAcqB,QAAd,GAAyBzB,QAAzB;AACA,SAAKI,QAAL,CAAcd,SAAd,CAAwBf,aAAa,CAACK,MAAtC,IAAgD,KAAKU,SAAL,CAAeU,QAAf,CAAhD;AACA,WAAO,IAAP;AACD;;AAED0B,EAAAA,gBAAgB,CAACA,gBAAD,EAA4B;AAC1C,SAAK/B,MAAL,CAAY+B,gBAAZ,GAA+BA,gBAA/B;AACA,WAAO,IAAP;AACD;;AApBkC","sourcesContent":["import { FlingGestureHandlerEventPayload } from '../FlingGestureHandler';\nimport { ForceTouchGestureHandlerEventPayload } from '../ForceTouchGestureHandler';\nimport {\n HitSlop,\n CommonGestureConfig,\n GestureTouchEvent,\n GestureStateChangeEvent,\n GestureUpdateEvent,\n} from '../gestureHandlerCommon';\nimport { getNextHandlerTag } from '../handlersRegistry';\nimport { GestureStateManagerType } from './gestureStateManager';\nimport { LongPressGestureHandlerEventPayload } from '../LongPressGestureHandler';\nimport { PanGestureHandlerEventPayload } from '../PanGestureHandler';\nimport { PinchGestureHandlerEventPayload } from '../PinchGestureHandler';\nimport { RotationGestureHandlerEventPayload } from '../RotationGestureHandler';\nimport { TapGestureHandlerEventPayload } from '../TapGestureHandler';\nimport { NativeViewGestureHandlerPayload } from '../NativeViewGestureHandler';\n\nexport type GestureType =\n | BaseGesture>\n | BaseGesture>\n | BaseGesture\n | BaseGesture\n | BaseGesture\n | BaseGesture\n | BaseGesture\n | BaseGesture\n | BaseGesture\n | BaseGesture;\n\nexport type GestureRef =\n | number\n | GestureType\n | React.RefObject\n | React.RefObject; // allow adding a ref to a gesture handler\nexport interface BaseGestureConfig\n extends CommonGestureConfig,\n Record {\n ref?: React.MutableRefObject;\n requireToFail?: GestureRef[];\n simultaneousWith?: GestureRef[];\n needsPointerData?: boolean;\n manualActivation?: boolean;\n}\n\ntype TouchEventHandlerType = (\n event: GestureTouchEvent,\n stateManager: GestureStateManagerType\n) => void;\n\nexport type HandlerCallbacks> = {\n handlerTag: number;\n onBegin?: (event: GestureStateChangeEvent) => void;\n onStart?: (event: GestureStateChangeEvent) => void;\n onEnd?: (\n event: GestureStateChangeEvent,\n success: boolean\n ) => void;\n onFinalize?: (\n event: GestureStateChangeEvent,\n success: boolean\n ) => void;\n onUpdate?: (event: GestureUpdateEvent) => void;\n onChange?: (event: any) => void;\n onTouchesDown?: TouchEventHandlerType;\n onTouchesMove?: TouchEventHandlerType;\n onTouchesUp?: TouchEventHandlerType;\n onTouchesCancelled?: TouchEventHandlerType;\n changeEventCalculator?: (\n current: GestureUpdateEvent>,\n previous?: GestureUpdateEvent>\n ) => GestureUpdateEvent>;\n isWorklet: boolean[];\n};\n\nexport const CALLBACK_TYPE = {\n UNDEFINED: 0,\n BEGAN: 1,\n START: 2,\n UPDATE: 3,\n CHANGE: 4,\n END: 5,\n FINALIZE: 6,\n TOUCHES_DOWN: 7,\n TOUCHES_MOVE: 8,\n TOUCHES_UP: 9,\n TOUCHES_CANCELLED: 10,\n} as const;\n\n// Allow using CALLBACK_TYPE as object and type\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type CALLBACK_TYPE = typeof CALLBACK_TYPE[keyof typeof CALLBACK_TYPE];\n\nexport abstract class Gesture {\n /**\n * Return array of gestures, providing the same interface for creating and updating\n * handlers, no matter which object was used to create gesture instance.\n */\n abstract toGestureArray(): GestureType[];\n\n /**\n * Assign handlerTag to the gesture instance and set ref.current (if a ref is set)\n */\n abstract initialize(): void;\n\n /**\n * Make sure that values of properties defining relations are arrays. Do any necessary\n * preprocessing required to configure relations between handlers. Called just before\n * updating the handler on the native side.\n */\n abstract prepare(): void;\n}\n\nexport abstract class BaseGesture<\n EventPayloadT extends Record\n> extends Gesture {\n public handlerTag = -1;\n public handlerName = '';\n public config: BaseGestureConfig = {};\n public handlers: HandlerCallbacks = {\n handlerTag: -1,\n isWorklet: [false, false, false, false],\n };\n\n private addDependency(\n key: 'simultaneousWith' | 'requireToFail',\n gesture: Exclude\n ) {\n const value = this.config[key];\n this.config[key] = value\n ? Array().concat(value, gesture)\n : [gesture];\n }\n\n withRef(ref: React.MutableRefObject) {\n this.config.ref = ref;\n return this;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n protected isWorklet(callback: Function) {\n //@ts-ignore if callback is a worklet, the property will be available, if not then the check will return false\n return callback.__workletHash !== undefined;\n }\n\n onBegin(callback: (event: GestureStateChangeEvent) => void) {\n this.handlers.onBegin = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.BEGAN] = this.isWorklet(callback);\n return this;\n }\n\n onStart(callback: (event: GestureStateChangeEvent) => void) {\n this.handlers.onStart = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.START] = this.isWorklet(callback);\n return this;\n }\n\n onEnd(\n callback: (\n event: GestureStateChangeEvent,\n success: boolean\n ) => void\n ) {\n this.handlers.onEnd = callback;\n //@ts-ignore if callback is a worklet, the property will be available, if not then the check will return false\n this.handlers.isWorklet[CALLBACK_TYPE.END] = this.isWorklet(callback);\n return this;\n }\n\n onFinalize(\n callback: (\n event: GestureStateChangeEvent,\n success: boolean\n ) => void\n ) {\n this.handlers.onFinalize = callback;\n //@ts-ignore if callback is a worklet, the property will be available, if not then the check will return false\n this.handlers.isWorklet[CALLBACK_TYPE.FINALIZE] = this.isWorklet(callback);\n return this;\n }\n\n onTouchesDown(callback: TouchEventHandlerType) {\n this.config.needsPointerData = true;\n this.handlers.onTouchesDown = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_DOWN] = this.isWorklet(\n callback\n );\n\n return this;\n }\n\n onTouchesMove(callback: TouchEventHandlerType) {\n this.config.needsPointerData = true;\n this.handlers.onTouchesMove = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_MOVE] = this.isWorklet(\n callback\n );\n\n return this;\n }\n\n onTouchesUp(callback: TouchEventHandlerType) {\n this.config.needsPointerData = true;\n this.handlers.onTouchesUp = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_UP] = this.isWorklet(\n callback\n );\n\n return this;\n }\n\n onTouchesCancelled(callback: TouchEventHandlerType) {\n this.config.needsPointerData = true;\n this.handlers.onTouchesCancelled = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_CANCELLED] = this.isWorklet(\n callback\n );\n\n return this;\n }\n\n enabled(enabled: boolean) {\n this.config.enabled = enabled;\n return this;\n }\n\n shouldCancelWhenOutside(value: boolean) {\n this.config.shouldCancelWhenOutside = value;\n return this;\n }\n\n hitSlop(hitSlop: HitSlop) {\n this.config.hitSlop = hitSlop;\n return this;\n }\n\n simultaneousWithExternalGesture(...gestures: Exclude[]) {\n for (const gesture of gestures) {\n this.addDependency('simultaneousWith', gesture);\n }\n return this;\n }\n\n requireExternalGestureToFail(...gestures: Exclude[]) {\n for (const gesture of gestures) {\n this.addDependency('requireToFail', gesture);\n }\n return this;\n }\n\n initialize() {\n this.handlerTag = getNextHandlerTag();\n this.handlers = { ...this.handlers, handlerTag: this.handlerTag };\n\n if (this.config.ref) {\n this.config.ref.current = this as GestureType;\n }\n }\n\n toGestureArray(): GestureType[] {\n return [this as GestureType];\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n prepare() {}\n}\n\nexport abstract class ContinousBaseGesture<\n EventPayloadT extends Record,\n EventChangePayloadT extends Record\n> extends BaseGesture {\n onUpdate(callback: (event: GestureUpdateEvent) => void) {\n this.handlers.onUpdate = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.UPDATE] = this.isWorklet(callback);\n return this;\n }\n\n onChange(\n callback: (\n event: GestureUpdateEvent\n ) => void\n ) {\n this.handlers.onChange = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.CHANGE] = this.isWorklet(callback);\n return this;\n }\n\n manualActivation(manualActivation: boolean) {\n this.config.manualActivation = manualActivation;\n return this;\n }\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/gestureComposition.js b/lib/commonjs/handlers/gestures/gestureComposition.js new file mode 100644 index 0000000000..c582b8e916 --- /dev/null +++ b/lib/commonjs/handlers/gestures/gestureComposition.js @@ -0,0 +1,94 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ExclusiveGesture = exports.SimultaneousGesture = exports.ComposedGesture = void 0; + +var _gesture = require("./gesture"); + +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; } + +function extendRelation(currentRelation, extendWith) { + if (currentRelation === undefined) { + return [...extendWith]; + } else { + return [...currentRelation, ...extendWith]; + } +} + +class ComposedGesture extends _gesture.Gesture { + constructor(...gestures) { + super(); + + _defineProperty(this, "gestures", []); + + _defineProperty(this, "simultaneousGestures", []); + + _defineProperty(this, "requireGesturesToFail", []); + + this.gestures = gestures; + } + + prepareSingleGesture(gesture, simultaneousGestures, requireGesturesToFail) { + if (gesture instanceof _gesture.BaseGesture) { + const newConfig = { ...gesture.config + }; + newConfig.simultaneousWith = extendRelation(newConfig.simultaneousWith, simultaneousGestures); + newConfig.requireToFail = extendRelation(newConfig.requireToFail, requireGesturesToFail); + gesture.config = newConfig; + } else if (gesture instanceof ComposedGesture) { + gesture.simultaneousGestures = simultaneousGestures; + gesture.requireGesturesToFail = requireGesturesToFail; + gesture.prepare(); + } + } + + prepare() { + for (const gesture of this.gestures) { + this.prepareSingleGesture(gesture, this.simultaneousGestures, this.requireGesturesToFail); + } + } + + initialize() { + for (const gesture of this.gestures) { + gesture.initialize(); + } + } + + toGestureArray() { + return this.gestures.flatMap(gesture => gesture.toGestureArray()); + } + +} + +exports.ComposedGesture = ComposedGesture; + +class SimultaneousGesture extends ComposedGesture { + prepare() { + const simultaneousArray = this.gestures.flatMap(gesture => gesture.toGestureArray()).concat(this.simultaneousGestures); + + for (const gesture of this.gestures) { + this.prepareSingleGesture(gesture, simultaneousArray, this.requireGesturesToFail); + } + } + +} + +exports.SimultaneousGesture = SimultaneousGesture; + +class ExclusiveGesture extends ComposedGesture { + prepare() { + const gestureArrays = this.gestures.map(gesture => gesture.toGestureArray()); + let requireToFail = []; + + for (let i = 0; i < this.gestures.length; i++) { + this.prepareSingleGesture(this.gestures[i], this.simultaneousGestures, this.requireGesturesToFail.concat(requireToFail)); + requireToFail = requireToFail.concat(gestureArrays[i]); + } + } + +} + +exports.ExclusiveGesture = ExclusiveGesture; +//# sourceMappingURL=gestureComposition.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/gestureComposition.js.map b/lib/commonjs/handlers/gestures/gestureComposition.js.map new file mode 100644 index 0000000000..afbb97980f --- /dev/null +++ b/lib/commonjs/handlers/gestures/gestureComposition.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["gestureComposition.ts"],"names":["extendRelation","currentRelation","extendWith","undefined","ComposedGesture","Gesture","constructor","gestures","prepareSingleGesture","gesture","simultaneousGestures","requireGesturesToFail","BaseGesture","newConfig","config","simultaneousWith","requireToFail","prepare","initialize","toGestureArray","flatMap","SimultaneousGesture","simultaneousArray","concat","ExclusiveGesture","gestureArrays","map","i","length"],"mappings":";;;;;;;AAAA;;;;AAEA,SAASA,cAAT,CACEC,eADF,EAEEC,UAFF,EAGE;AACA,MAAID,eAAe,KAAKE,SAAxB,EAAmC;AACjC,WAAO,CAAC,GAAGD,UAAJ,CAAP;AACD,GAFD,MAEO;AACL,WAAO,CAAC,GAAGD,eAAJ,EAAqB,GAAGC,UAAxB,CAAP;AACD;AACF;;AAEM,MAAME,eAAN,SAA8BC,gBAA9B,CAAsC;AAK3CC,EAAAA,WAAW,CAAC,GAAGC,QAAJ,EAAyB;AAClC;;AADkC,sCAJJ,EAII;;AAAA,kDAHY,EAGZ;;AAAA,mDAFa,EAEb;;AAElC,SAAKA,QAAL,GAAgBA,QAAhB;AACD;;AAESC,EAAAA,oBAAoB,CAC5BC,OAD4B,EAE5BC,oBAF4B,EAG5BC,qB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,KAAKF,QAA3B,EAAqC;AACnC,WAAKC,oBAAL,CACEC,OADF,EAEEa,iBAFF,EAGE,KAAKX,qBAHP;AAKD;AACF;;AAbsD;;;;AAgBlD,MAAMa,gBAAN,SAA+BpB,eAA/B,CAA+C;AACpDa,EAAAA,OAAO,GAAG;AACR,UAAMQ,aAAa,GAAG,KAAKlB,QAAL,CAAcmB,GAAd,CAAmBjB,OAAD,IACtCA,OAAO,CAACU,cAAR,EADoB,CAAtB;AAIA,QAAIH,aAA4B,GAAG,EAAnC;;AAEA,SAAK,IAAIW,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAG,KAAKpB,QAAL,CAAcqB,MAAlC,EAA0CD,CAAC,EAA3C,EAA+C;AAC7C,WAAKnB,oBAAL,CACE,KAAKD,QAAL,CAAcoB,CAAd,CADF,EAEE,KAAKjB,oBAFP,EAGE,KAAKC,qBAAL,CAA2BY,MAA3B,CAAkCP,aAAlC,CAHF;AAMAA,MAAAA,aAAa,GAAGA,aAAa,CAACO,MAAd,CAAqBE,aAAa,CAACE,CAAD,CAAlC,CAAhB;AACD;AACF;;AAjBmD","sourcesContent":["import { BaseGesture, Gesture, GestureRef, GestureType } from './gesture';\n\nfunction extendRelation(\n currentRelation: GestureRef[] | undefined,\n extendWith: GestureType[]\n) {\n if (currentRelation === undefined) {\n return [...extendWith];\n } else {\n return [...currentRelation, ...extendWith];\n }\n}\n\nexport class ComposedGesture extends Gesture {\n protected gestures: Gesture[] = [];\n protected simultaneousGestures: GestureType[] = [];\n protected requireGesturesToFail: GestureType[] = [];\n\n constructor(...gestures: Gesture[]) {\n super();\n this.gestures = gestures;\n }\n\n protected prepareSingleGesture(\n gesture: Gesture,\n simultaneousGestures: GestureType[],\n requireGesturesToFail: GestureType[]\n ) {\n if (gesture instanceof BaseGesture) {\n const newConfig = { ...gesture.config };\n\n newConfig.simultaneousWith = extendRelation(\n newConfig.simultaneousWith,\n simultaneousGestures\n );\n newConfig.requireToFail = extendRelation(\n newConfig.requireToFail,\n requireGesturesToFail\n );\n\n gesture.config = newConfig;\n } else if (gesture instanceof ComposedGesture) {\n gesture.simultaneousGestures = simultaneousGestures;\n gesture.requireGesturesToFail = requireGesturesToFail;\n gesture.prepare();\n }\n }\n\n prepare() {\n for (const gesture of this.gestures) {\n this.prepareSingleGesture(\n gesture,\n this.simultaneousGestures,\n this.requireGesturesToFail\n );\n }\n }\n\n initialize() {\n for (const gesture of this.gestures) {\n gesture.initialize();\n }\n }\n\n toGestureArray(): GestureType[] {\n return this.gestures.flatMap((gesture) => gesture.toGestureArray());\n }\n}\n\nexport class SimultaneousGesture extends ComposedGesture {\n prepare() {\n const simultaneousArray = this.gestures\n .flatMap((gesture) => gesture.toGestureArray())\n .concat(this.simultaneousGestures);\n\n for (const gesture of this.gestures) {\n this.prepareSingleGesture(\n gesture,\n simultaneousArray,\n this.requireGesturesToFail\n );\n }\n }\n}\n\nexport class ExclusiveGesture extends ComposedGesture {\n prepare() {\n const gestureArrays = this.gestures.map((gesture) =>\n gesture.toGestureArray()\n );\n\n let requireToFail: GestureType[] = [];\n\n for (let i = 0; i < this.gestures.length; i++) {\n this.prepareSingleGesture(\n this.gestures[i],\n this.simultaneousGestures,\n this.requireGesturesToFail.concat(requireToFail)\n );\n\n requireToFail = requireToFail.concat(gestureArrays[i]);\n }\n }\n}\n\nexport type ComposedGestureType = InstanceType;\nexport type RaceGestureType = ComposedGestureType;\nexport type SimultaneousGestureType = InstanceType;\nexport type ExclusiveGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/gestureObjects.js b/lib/commonjs/handlers/gestures/gestureObjects.js new file mode 100644 index 0000000000..5bb9511201 --- /dev/null +++ b/lib/commonjs/handlers/gestures/gestureObjects.js @@ -0,0 +1,85 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GestureObjects = void 0; + +var _flingGesture = require("./flingGesture"); + +var _forceTouchGesture = require("./forceTouchGesture"); + +var _gestureComposition = require("./gestureComposition"); + +var _longPressGesture = require("./longPressGesture"); + +var _panGesture = require("./panGesture"); + +var _pinchGesture = require("./pinchGesture"); + +var _rotationGesture = require("./rotationGesture"); + +var _tapGesture = require("./tapGesture"); + +var _nativeGesture = require("./nativeGesture"); + +var _manualGesture = require("./manualGesture"); + +const GestureObjects = { + Tap: () => { + return new _tapGesture.TapGesture(); + }, + Pan: () => { + return new _panGesture.PanGesture(); + }, + Pinch: () => { + return new _pinchGesture.PinchGesture(); + }, + Rotation: () => { + return new _rotationGesture.RotationGesture(); + }, + Fling: () => { + return new _flingGesture.FlingGesture(); + }, + LongPress: () => { + return new _longPressGesture.LongPressGesture(); + }, + ForceTouch: () => { + return new _forceTouchGesture.ForceTouchGesture(); + }, + Native: () => { + return new _nativeGesture.NativeGesture(); + }, + Manual: () => { + return new _manualGesture.ManualGesture(); + }, + + /** + * Builds a composed gesture consisting of gestures provided as parameters. + * The first one that becomes active cancels the rest of gestures. + */ + Race: (...gestures) => { + return new _gestureComposition.ComposedGesture(...gestures); + }, + + /** + * Builds a composed gesture that allows all base gestures to run simultaneously. + */ + Simultaneous(...gestures) { + return new _gestureComposition.SimultaneousGesture(...gestures); + }, + + /** + * Builds a composed gesture where only one of the provided gestures can become active. + * Priority is decided through the order of gestures: the first one has higher priority + * than the second one, second one has higher priority than the third one, and so on. + * For example, to make a gesture that recognizes both single and double tap you need + * to call Exclusive(doubleTap, singleTap). + */ + Exclusive(...gestures) { + return new _gestureComposition.ExclusiveGesture(...gestures); + } + +}; +exports.GestureObjects = GestureObjects; +//# sourceMappingURL=gestureObjects.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/gestureObjects.js.map b/lib/commonjs/handlers/gestures/gestureObjects.js.map new file mode 100644 index 0000000000..268c7acb08 --- /dev/null +++ b/lib/commonjs/handlers/gestures/gestureObjects.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["gestureObjects.ts"],"names":["GestureObjects","Tap","TapGesture","Pan","PanGesture","Pinch","PinchGesture","Rotation","RotationGesture","Fling","FlingGesture","LongPress","LongPressGesture","ForceTouch","ForceTouchGesture","Native","NativeGesture","Manual","ManualGesture","Race","gestures","ComposedGesture","Simultaneous","SimultaneousGesture","Exclusive","ExclusiveGesture"],"mappings":";;;;;;;AAAA;;AACA;;AAEA;;AAKA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAEO,MAAMA,cAAc,GAAG;AAC5BC,EAAAA,GAAG,EAAE,MAAM;AACT,WAAO,IAAIC,sBAAJ,EAAP;AACD,GAH2B;AAK5BC,EAAAA,GAAG,EAAE,MAAM;AACT,WAAO,IAAIC,sBAAJ,EAAP;AACD,GAP2B;AAS5BC,EAAAA,KAAK,EAAE,MAAM;AACX,WAAO,IAAIC,0BAAJ,EAAP;AACD,GAX2B;AAa5BC,EAAAA,QAAQ,EAAE,MAAM;AACd,WAAO,IAAIC,gCAAJ,EAAP;AACD,GAf2B;AAiB5BC,EAAAA,KAAK,EAAE,MAAM;AACX,WAAO,IAAIC,0BAAJ,EAAP;AACD,GAnB2B;AAqB5BC,EAAAA,SAAS,EAAE,MAAM;AACf,WAAO,IAAIC,kCAAJ,EAAP;AACD,GAvB2B;AAyB5BC,EAAAA,UAAU,EAAE,MAAM;AAChB,WAAO,IAAIC,oCAAJ,EAAP;AACD,GA3B2B;AA6B5BC,EAAAA,MAAM,EAAE,MAAM;AACZ,WAAO,IAAIC,4BAAJ,EAAP;AACD,GA/B2B;AAiC5BC,EAAAA,MAAM,EAAE,MAAM;AACZ,WAAO,IAAIC,4BAAJ,EAAP;AACD,GAnC2B;;AAqC5B;AACF;AACA;AACA;AACEC,EAAAA,IAAI,EAAE,CAAC,GAAGC,QAAJ,KAA4B;AAChC,WAAO,IAAIC,mCAAJ,CAAoB,GAAGD,QAAvB,CAAP;AACD,GA3C2B;;AA6C5B;AACF;AACA;AACEE,EAAAA,YAAY,CAAC,GAAGF,QAAJ,EAAyB;AACnC,WAAO,IAAIG,uCAAJ,CAAwB,GAAGH,QAA3B,CAAP;AACD,GAlD2B;;AAoD5B;AACF;AACA;AACA;AACA;AACA;AACA;AACEI,EAAAA,SAAS,CAAC,GAAGJ,QAAJ,EAAyB;AAChC,WAAO,IAAIK,oCAAJ,CAAqB,GAAGL,QAAxB,CAAP;AACD;;AA7D2B,CAAvB","sourcesContent":["import { FlingGesture } from './flingGesture';\nimport { ForceTouchGesture } from './forceTouchGesture';\nimport { Gesture } from './gesture';\nimport {\n ComposedGesture,\n ExclusiveGesture,\n SimultaneousGesture,\n} from './gestureComposition';\nimport { LongPressGesture } from './longPressGesture';\nimport { PanGesture } from './panGesture';\nimport { PinchGesture } from './pinchGesture';\nimport { RotationGesture } from './rotationGesture';\nimport { TapGesture } from './tapGesture';\nimport { NativeGesture } from './nativeGesture';\nimport { ManualGesture } from './manualGesture';\n\nexport const GestureObjects = {\n Tap: () => {\n return new TapGesture();\n },\n\n Pan: () => {\n return new PanGesture();\n },\n\n Pinch: () => {\n return new PinchGesture();\n },\n\n Rotation: () => {\n return new RotationGesture();\n },\n\n Fling: () => {\n return new FlingGesture();\n },\n\n LongPress: () => {\n return new LongPressGesture();\n },\n\n ForceTouch: () => {\n return new ForceTouchGesture();\n },\n\n Native: () => {\n return new NativeGesture();\n },\n\n Manual: () => {\n return new ManualGesture();\n },\n\n /**\n * Builds a composed gesture consisting of gestures provided as parameters.\n * The first one that becomes active cancels the rest of gestures.\n */\n Race: (...gestures: Gesture[]) => {\n return new ComposedGesture(...gestures);\n },\n\n /**\n * Builds a composed gesture that allows all base gestures to run simultaneously.\n */\n Simultaneous(...gestures: Gesture[]) {\n return new SimultaneousGesture(...gestures);\n },\n\n /**\n * Builds a composed gesture where only one of the provided gestures can become active.\n * Priority is decided through the order of gestures: the first one has higher priority\n * than the second one, second one has higher priority than the third one, and so on.\n * For example, to make a gesture that recognizes both single and double tap you need\n * to call Exclusive(doubleTap, singleTap).\n */\n Exclusive(...gestures: Gesture[]) {\n return new ExclusiveGesture(...gestures);\n },\n};\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/gestureStateManager.js b/lib/commonjs/handlers/gestures/gestureStateManager.js new file mode 100644 index 0000000000..dece00fdd5 --- /dev/null +++ b/lib/commonjs/handlers/gestures/gestureStateManager.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GestureStateManager = void 0; + +var _reanimatedWrapper = require("./reanimatedWrapper"); + +var _State = require("../../State"); + +const GestureStateManager = { + create(handlerTag) { + 'worklet'; + + return { + begin: () => { + 'worklet'; + + if (_reanimatedWrapper.Reanimated) { + _reanimatedWrapper.Reanimated.setGestureState(handlerTag, _State.State.BEGAN); + } else { + console.warn('react-native-reanimated is required in order to use synchronous state management'); + } + }, + activate: () => { + 'worklet'; + + if (_reanimatedWrapper.Reanimated) { + _reanimatedWrapper.Reanimated.setGestureState(handlerTag, _State.State.ACTIVE); + } else { + console.warn('react-native-reanimated is required in order to use synchronous state management'); + } + }, + fail: () => { + 'worklet'; + + if (_reanimatedWrapper.Reanimated) { + _reanimatedWrapper.Reanimated.setGestureState(handlerTag, _State.State.FAILED); + } else { + console.warn('react-native-reanimated is required in order to use synchronous state management'); + } + }, + end: () => { + 'worklet'; + + if (_reanimatedWrapper.Reanimated) { + _reanimatedWrapper.Reanimated.setGestureState(handlerTag, _State.State.END); + } else { + console.warn('react-native-reanimated is required in order to use synchronous state management'); + } + } + }; + } + +}; +exports.GestureStateManager = GestureStateManager; +//# sourceMappingURL=gestureStateManager.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/gestureStateManager.js.map b/lib/commonjs/handlers/gestures/gestureStateManager.js.map new file mode 100644 index 0000000000..3be27408fa --- /dev/null +++ b/lib/commonjs/handlers/gestures/gestureStateManager.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["gestureStateManager.ts"],"names":["GestureStateManager","create","handlerTag","begin","Reanimated","setGestureState","State","BEGAN","console","warn","activate","ACTIVE","fail","FAILED","end","END"],"mappings":";;;;;;;AAAA;;AACA;;AASO,MAAMA,mBAAmB,GAAG;AACjCC,EAAAA,MAAM,CAACC,UAAD,EAA8C;AAClD;;AACA,WAAO;AACLC,MAAAA,KAAK,EAAE,MAAM;AACX;;AACA,YAAIC,6BAAJ,EAAgB;AACdA,wCAAWC,eAAX,CAA2BH,UAA3B,EAAuCI,aAAMC,KAA7C;AACD,SAFD,MAEO;AACLC,UAAAA,OAAO,CAACC,IAAR,CACE,kFADF;AAGD;AACF,OAVI;AAYLC,MAAAA,QAAQ,EAAE,MAAM;AACd;;AACA,YAAIN,6BAAJ,EAAgB;AACdA,wCAAWC,eAAX,CAA2BH,UAA3B,EAAuCI,aAAMK,MAA7C;AACD,SAFD,MAEO;AACLH,UAAAA,OAAO,CAACC,IAAR,CACE,kFADF;AAGD;AACF,OArBI;AAuBLG,MAAAA,IAAI,EAAE,MAAM;AACV;;AACA,YAAIR,6BAAJ,EAAgB;AACdA,wCAAWC,eAAX,CAA2BH,UAA3B,EAAuCI,aAAMO,MAA7C;AACD,SAFD,MAEO;AACLL,UAAAA,OAAO,CAACC,IAAR,CACE,kFADF;AAGD;AACF,OAhCI;AAkCLK,MAAAA,GAAG,EAAE,MAAM;AACT;;AACA,YAAIV,6BAAJ,EAAgB;AACdA,wCAAWC,eAAX,CAA2BH,UAA3B,EAAuCI,aAAMS,GAA7C;AACD,SAFD,MAEO;AACLP,UAAAA,OAAO,CAACC,IAAR,CACE,kFADF;AAGD;AACF;AA3CI,KAAP;AA6CD;;AAhDgC,CAA5B","sourcesContent":["import { Reanimated } from './reanimatedWrapper';\nimport { State } from '../../State';\n\nexport interface GestureStateManagerType {\n begin: () => void;\n activate: () => void;\n fail: () => void;\n end: () => void;\n}\n\nexport const GestureStateManager = {\n create(handlerTag: number): GestureStateManagerType {\n 'worklet';\n return {\n begin: () => {\n 'worklet';\n if (Reanimated) {\n Reanimated.setGestureState(handlerTag, State.BEGAN);\n } else {\n console.warn(\n 'react-native-reanimated is required in order to use synchronous state management'\n );\n }\n },\n\n activate: () => {\n 'worklet';\n if (Reanimated) {\n Reanimated.setGestureState(handlerTag, State.ACTIVE);\n } else {\n console.warn(\n 'react-native-reanimated is required in order to use synchronous state management'\n );\n }\n },\n\n fail: () => {\n 'worklet';\n if (Reanimated) {\n Reanimated.setGestureState(handlerTag, State.FAILED);\n } else {\n console.warn(\n 'react-native-reanimated is required in order to use synchronous state management'\n );\n }\n },\n\n end: () => {\n 'worklet';\n if (Reanimated) {\n Reanimated.setGestureState(handlerTag, State.END);\n } else {\n console.warn(\n 'react-native-reanimated is required in order to use synchronous state management'\n );\n }\n },\n };\n },\n};\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/longPressGesture.js b/lib/commonjs/handlers/gestures/longPressGesture.js new file mode 100644 index 0000000000..5f8eb2cad9 --- /dev/null +++ b/lib/commonjs/handlers/gestures/longPressGesture.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LongPressGesture = void 0; + +var _gesture = require("./gesture"); + +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; } + +class LongPressGesture extends _gesture.BaseGesture { + constructor() { + super(); + + _defineProperty(this, "config", {}); + + this.handlerName = 'LongPressGestureHandler'; + } + + minDuration(duration) { + this.config.minDurationMs = duration; + return this; + } + + maxDistance(distance) { + this.config.maxDist = distance; + return this; + } + +} + +exports.LongPressGesture = LongPressGesture; +//# sourceMappingURL=longPressGesture.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/longPressGesture.js.map b/lib/commonjs/handlers/gestures/longPressGesture.js.map new file mode 100644 index 0000000000..5d2978fa76 --- /dev/null +++ b/lib/commonjs/handlers/gestures/longPressGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["longPressGesture.ts"],"names":["LongPressGesture","BaseGesture","constructor","handlerName","minDuration","duration","config","minDurationMs","maxDistance","distance","maxDist"],"mappings":";;;;;;;AAAA;;;;AAMO,MAAMA,gBAAN,SAA+BC,oBAA/B,CAAgF;AAGrFC,EAAAA,WAAW,GAAG;AACZ;;AADY,oCAF8C,EAE9C;;AAGZ,SAAKC,WAAL,GAAmB,yBAAnB;AACD;;AAEDC,EAAAA,WAAW,CAACC,QAAD,EAAmB;AAC5B,SAAKC,MAAL,CAAYC,aAAZ,GAA4BF,QAA5B;AACA,WAAO,IAAP;AACD;;AAEDG,EAAAA,WAAW,CAACC,QAAD,EAAmB;AAC5B,SAAKH,MAAL,CAAYI,OAAZ,GAAsBD,QAAtB;AACA,WAAO,IAAP;AACD;;AAjBoF","sourcesContent":["import { BaseGesture, BaseGestureConfig } from './gesture';\nimport {\n LongPressGestureConfig,\n LongPressGestureHandlerEventPayload,\n} from '../LongPressGestureHandler';\n\nexport class LongPressGesture extends BaseGesture {\n public config: BaseGestureConfig & LongPressGestureConfig = {};\n\n constructor() {\n super();\n\n this.handlerName = 'LongPressGestureHandler';\n }\n\n minDuration(duration: number) {\n this.config.minDurationMs = duration;\n return this;\n }\n\n maxDistance(distance: number) {\n this.config.maxDist = distance;\n return this;\n }\n}\n\nexport type LongPressGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/manualGesture.js b/lib/commonjs/handlers/gestures/manualGesture.js new file mode 100644 index 0000000000..c7cfaf3de4 --- /dev/null +++ b/lib/commonjs/handlers/gestures/manualGesture.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ManualGesture = void 0; + +var _gesture = require("./gesture"); + +function changeEventCalculator(current, _previous) { + 'worklet'; + + return current; +} + +class ManualGesture extends _gesture.ContinousBaseGesture { + constructor() { + super(); + this.handlerName = 'ManualGestureHandler'; + } + + onChange(callback) { + // @ts-ignore TS being overprotective, Record is Record + this.handlers.changeEventCalculator = changeEventCalculator; + return super.onChange(callback); + } + +} + +exports.ManualGesture = ManualGesture; +//# sourceMappingURL=manualGesture.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/manualGesture.js.map b/lib/commonjs/handlers/gestures/manualGesture.js.map new file mode 100644 index 0000000000..4272d43965 --- /dev/null +++ b/lib/commonjs/handlers/gestures/manualGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["manualGesture.ts"],"names":["changeEventCalculator","current","_previous","ManualGesture","ContinousBaseGesture","constructor","handlerName","onChange","callback","handlers"],"mappings":";;;;;;;AACA;;AAEA,SAASA,qBAAT,CACEC,OADF,EAEEC,SAFF,EAGE;AACA;;AACA,SAAOD,OAAP;AACD;;AAEM,MAAME,aAAN,SAA4BC,6BAA5B,CAGL;AACAC,EAAAA,WAAW,GAAG;AACZ;AAEA,SAAKC,WAAL,GAAmB,sBAAnB;AACD;;AAEDC,EAAAA,QAAQ,CACNC,QADM,EAEN;AACA;AACA,SAAKC,QAAL,CAAcT,qBAAd,GAAsCA,qBAAtC;AACA,WAAO,MAAMO,QAAN,CAAeC,QAAf,CAAP;AACD;;AAbD","sourcesContent":["import { GestureUpdateEvent } from '../gestureHandlerCommon';\nimport { ContinousBaseGesture } from './gesture';\n\nfunction changeEventCalculator(\n current: GestureUpdateEvent>,\n _previous?: GestureUpdateEvent>\n) {\n 'worklet';\n return current;\n}\n\nexport class ManualGesture extends ContinousBaseGesture<\n Record,\n Record\n> {\n constructor() {\n super();\n\n this.handlerName = 'ManualGestureHandler';\n }\n\n onChange(\n callback: (event: GestureUpdateEvent>) => void\n ) {\n // @ts-ignore TS being overprotective, Record is Record\n this.handlers.changeEventCalculator = changeEventCalculator;\n return super.onChange(callback);\n }\n}\n\nexport type ManualGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/nativeGesture.js b/lib/commonjs/handlers/gestures/nativeGesture.js new file mode 100644 index 0000000000..7deb3f0560 --- /dev/null +++ b/lib/commonjs/handlers/gestures/nativeGesture.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.NativeGesture = void 0; + +var _gesture = require("./gesture"); + +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; } + +class NativeGesture extends _gesture.BaseGesture { + constructor() { + super(); + + _defineProperty(this, "config", {}); + + this.handlerName = 'NativeViewGestureHandler'; + } + + shouldActivateOnStart(value) { + this.config.shouldActivateOnStart = value; + return this; + } + + disallowInterruption(value) { + this.config.disallowInterruption = value; + return this; + } + +} + +exports.NativeGesture = NativeGesture; +//# sourceMappingURL=nativeGesture.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/nativeGesture.js.map b/lib/commonjs/handlers/gestures/nativeGesture.js.map new file mode 100644 index 0000000000..7514e3896e --- /dev/null +++ b/lib/commonjs/handlers/gestures/nativeGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["nativeGesture.ts"],"names":["NativeGesture","BaseGesture","constructor","handlerName","shouldActivateOnStart","value","config","disallowInterruption"],"mappings":";;;;;;;AAAA;;;;AAMO,MAAMA,aAAN,SAA4BC,oBAA5B,CAAyE;AAG9EC,EAAAA,WAAW,GAAG;AACZ;;AADY,oCAF+C,EAE/C;;AAGZ,SAAKC,WAAL,GAAmB,0BAAnB;AACD;;AAEDC,EAAAA,qBAAqB,CAACC,KAAD,EAAiB;AACpC,SAAKC,MAAL,CAAYF,qBAAZ,GAAoCC,KAApC;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,oBAAoB,CAACF,KAAD,EAAiB;AACnC,SAAKC,MAAL,CAAYC,oBAAZ,GAAmCF,KAAnC;AACA,WAAO,IAAP;AACD;;AAjB6E","sourcesContent":["import { BaseGestureConfig, BaseGesture } from './gesture';\nimport {\n NativeViewGestureConfig,\n NativeViewGestureHandlerPayload,\n} from '../NativeViewGestureHandler';\n\nexport class NativeGesture extends BaseGesture {\n public config: BaseGestureConfig & NativeViewGestureConfig = {};\n\n constructor() {\n super();\n\n this.handlerName = 'NativeViewGestureHandler';\n }\n\n shouldActivateOnStart(value: boolean) {\n this.config.shouldActivateOnStart = value;\n return this;\n }\n\n disallowInterruption(value: boolean) {\n this.config.disallowInterruption = value;\n return this;\n }\n}\n\nexport type NativeGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/panGesture.js b/lib/commonjs/handlers/gestures/panGesture.js new file mode 100644 index 0000000000..6375c530de --- /dev/null +++ b/lib/commonjs/handlers/gestures/panGesture.js @@ -0,0 +1,144 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PanGesture = void 0; + +var _gesture = require("./gesture"); + +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; } + +function changeEventCalculator(current, previous) { + 'worklet'; + + let changePayload; + + if (previous === undefined) { + changePayload = { + changeX: current.translationX, + changeY: current.translationY + }; + } else { + changePayload = { + changeX: current.translationX - previous.translationX, + changeY: current.translationY - previous.translationY + }; + } + + return { ...current, + ...changePayload + }; +} + +class PanGesture extends _gesture.ContinousBaseGesture { + constructor() { + super(); + + _defineProperty(this, "config", {}); + + this.handlerName = 'PanGestureHandler'; + } + + activeOffsetY(offset) { + if (Array.isArray(offset)) { + this.config.activeOffsetYStart = offset[0]; + this.config.activeOffsetYEnd = offset[1]; + } else if (offset < 0) { + this.config.activeOffsetYStart = offset; + } else { + this.config.activeOffsetYEnd = offset; + } + + return this; + } + + activeOffsetX(offset) { + if (Array.isArray(offset)) { + this.config.activeOffsetXStart = offset[0]; + this.config.activeOffsetXEnd = offset[1]; + } else if (offset < 0) { + this.config.activeOffsetXStart = offset; + } else { + this.config.activeOffsetXEnd = offset; + } + + return this; + } + + failOffsetY(offset) { + if (Array.isArray(offset)) { + this.config.failOffsetYStart = offset[0]; + this.config.failOffsetYEnd = offset[1]; + } else if (offset < 0) { + this.config.failOffsetYStart = offset; + } else { + this.config.failOffsetYEnd = offset; + } + + return this; + } + + failOffsetX(offset) { + if (Array.isArray(offset)) { + this.config.failOffsetXStart = offset[0]; + this.config.failOffsetXEnd = offset[1]; + } else if (offset < 0) { + this.config.failOffsetXStart = offset; + } else { + this.config.failOffsetXEnd = offset; + } + + return this; + } + + minPointers(minPointers) { + this.config.minPointers = minPointers; + return this; + } + + maxPointers(maxPointers) { + this.config.maxPointers = maxPointers; + return this; + } + + minDistance(distance) { + this.config.minDist = distance; + return this; + } + + minVelocity(velocity) { + this.config.minVelocity = velocity; + return this; + } + + minVelocityX(velocity) { + this.config.minVelocityX = velocity; + return this; + } + + minVelocityY(velocity) { + this.config.minVelocityY = velocity; + return this; + } + + averageTouches(value) { + this.config.avgTouches = value; + return this; + } + + enableTrackpadTwoFingerGesture(value) { + this.config.enableTrackpadTwoFingerGesture = value; + return this; + } + + onChange(callback) { + // @ts-ignore TS being overprotective, PanGestureHandlerEventPayload is Record + this.handlers.changeEventCalculator = changeEventCalculator; + return super.onChange(callback); + } + +} + +exports.PanGesture = PanGesture; +//# sourceMappingURL=panGesture.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/panGesture.js.map b/lib/commonjs/handlers/gestures/panGesture.js.map new file mode 100644 index 0000000000..f2e8d56e92 --- /dev/null +++ b/lib/commonjs/handlers/gestures/panGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["panGesture.ts"],"names":["changeEventCalculator","current","previous","changePayload","undefined","changeX","translationX","changeY","translationY","PanGesture","ContinousBaseGesture","constructor","handlerName","activeOffsetY","offset","Array","isArray","config","activeOffsetYStart","activeOffsetYEnd","activeOffsetX","activeOffsetXStart","activeOffsetXEnd","failOffsetY","failOffsetYStart","failOffsetYEnd","failOffsetX","failOffsetXStart","failOffsetXEnd","minPointers","maxPointers","minDistance","distance","minDist","minVelocity","velocity","minVelocityX","minVelocityY","averageTouches","value","avgTouches","enableTrackpadTwoFingerGesture","onChange","callback","handlers"],"mappings":";;;;;;;AAAA;;;;AAYA,SAASA,qBA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AAEDC,EAAAA,WAAW,CAACA,WAAD,EAAsB;AAC/B,SAAKb,MAAL,CAAYa,WAAZ,GAA0BA,WAA1B;AACA,WAAO,IAAP;AACD;;AAEDC,EAAAA,WAAW,CAACC,QAAD,EAAmB;AAC5B,SAAKf,MAAL,CAAYgB,OAAZ,GAAsBD,QAAtB;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,WAAW,CAACC,QAAD,EAAmB;AAC5B,SAAKlB,MAAL,CAAYiB,WAAZ,GAA0BC,QAA1B;AACA,WAAO,IAAP;AACD;;AAEDC,EAAAA,YAAY,CAACD,QAAD,EAAmB;AAC7B,SAAKlB,MAAL,CAAYmB,YAAZ,GAA2BD,QAA3B;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,YAAY,CAACF,QAAD,EAAmB;AAC7B,SAAKlB,MAAL,CAAYoB,YAAZ,GAA2BF,QAA3B;AACA,WAAO,IAAP;AACD;;AAEDG,EAAAA,cAAc,CAACC,KAAD,EAAiB;AAC7B,SAAKtB,MAAL,CAAYuB,UAAZ,GAAyBD,KAAzB;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,8BAA8B,CAACF,KAAD,EAAiB;AAC7C,SAAKtB,MAAL,CAAYwB,8BAAZ,GAA6CF,KAA7C;AACA,WAAO,IAAP;AACD;;AAEDG,EAAAA,QAAQ,CACNC,QADM,EAMN;AACA;AACA,SAAKC,QAAL,CAAc5C,qBAAd,GAAsCA,qBAAtC;AACA,WAAO,MAAM0C,QAAN,CAAeC,QAAf,CAAP;AACD;;AA3GD","sourcesContent":["import { BaseGestureConfig, ContinousBaseGesture } from './gesture';\nimport { GestureUpdateEvent } from '../gestureHandlerCommon';\nimport {\n PanGestureConfig,\n PanGestureHandlerEventPayload,\n} from '../PanGestureHandler';\n\ntype PanGestureChangeEventPayload = {\n changeX: number;\n changeY: number;\n};\n\nfunction changeEventCalculator(\n current: GestureUpdateEvent,\n previous?: GestureUpdateEvent\n) {\n 'worklet';\n let changePayload: PanGestureChangeEventPayload;\n if (previous === undefined) {\n changePayload = {\n changeX: current.translationX,\n changeY: current.translationY,\n };\n } else {\n changePayload = {\n changeX: current.translationX - previous.translationX,\n changeY: current.translationY - previous.translationY,\n };\n }\n\n return { ...current, ...changePayload };\n}\n\nexport class PanGesture extends ContinousBaseGesture<\n PanGestureHandlerEventPayload,\n PanGestureChangeEventPayload\n> {\n public config: BaseGestureConfig & PanGestureConfig = {};\n\n constructor() {\n super();\n\n this.handlerName = 'PanGestureHandler';\n }\n\n activeOffsetY(offset: number | number[]) {\n if (Array.isArray(offset)) {\n this.config.activeOffsetYStart = offset[0];\n this.config.activeOffsetYEnd = offset[1];\n } else if (offset < 0) {\n this.config.activeOffsetYStart = offset;\n } else {\n this.config.activeOffsetYEnd = offset;\n }\n return this;\n }\n\n activeOffsetX(offset: number | number[]) {\n if (Array.isArray(offset)) {\n this.config.activeOffsetXStart = offset[0];\n this.config.activeOffsetXEnd = offset[1];\n } else if (offset < 0) {\n this.config.activeOffsetXStart = offset;\n } else {\n this.config.activeOffsetXEnd = offset;\n }\n return this;\n }\n\n failOffsetY(offset: number | number[]) {\n if (Array.isArray(offset)) {\n this.config.failOffsetYStart = offset[0];\n this.config.failOffsetYEnd = offset[1];\n } else if (offset < 0) {\n this.config.failOffsetYStart = offset;\n } else {\n this.config.failOffsetYEnd = offset;\n }\n return this;\n }\n\n failOffsetX(offset: number | number[]) {\n if (Array.isArray(offset)) {\n this.config.failOffsetXStart = offset[0];\n this.config.failOffsetXEnd = offset[1];\n } else if (offset < 0) {\n this.config.failOffsetXStart = offset;\n } else {\n this.config.failOffsetXEnd = offset;\n }\n return this;\n }\n\n minPointers(minPointers: number) {\n this.config.minPointers = minPointers;\n return this;\n }\n\n maxPointers(maxPointers: number) {\n this.config.maxPointers = maxPointers;\n return this;\n }\n\n minDistance(distance: number) {\n this.config.minDist = distance;\n return this;\n }\n\n minVelocity(velocity: number) {\n this.config.minVelocity = velocity;\n return this;\n }\n\n minVelocityX(velocity: number) {\n this.config.minVelocityX = velocity;\n return this;\n }\n\n minVelocityY(velocity: number) {\n this.config.minVelocityY = velocity;\n return this;\n }\n\n averageTouches(value: boolean) {\n this.config.avgTouches = value;\n return this;\n }\n\n enableTrackpadTwoFingerGesture(value: boolean) {\n this.config.enableTrackpadTwoFingerGesture = value;\n return this;\n }\n\n onChange(\n callback: (\n event: GestureUpdateEvent<\n PanGestureHandlerEventPayload & PanGestureChangeEventPayload\n >\n ) => void\n ) {\n // @ts-ignore TS being overprotective, PanGestureHandlerEventPayload is Record\n this.handlers.changeEventCalculator = changeEventCalculator;\n return super.onChange(callback);\n }\n}\n\nexport type PanGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/pinchGesture.js b/lib/commonjs/handlers/gestures/pinchGesture.js new file mode 100644 index 0000000000..bd51a5ffa6 --- /dev/null +++ b/lib/commonjs/handlers/gestures/pinchGesture.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.PinchGesture = void 0; + +var _gesture = require("./gesture"); + +function changeEventCalculator(current, previous) { + 'worklet'; + + let changePayload; + + if (previous === undefined) { + changePayload = { + scaleChange: current.scale + }; + } else { + changePayload = { + scaleChange: current.scale / previous.scale + }; + } + + return { ...current, + ...changePayload + }; +} + +class PinchGesture extends _gesture.ContinousBaseGesture { + constructor() { + super(); + this.handlerName = 'PinchGestureHandler'; + } + + onChange(callback) { + // @ts-ignore TS being overprotective, PinchGestureHandlerEventPayload is Record + this.handlers.changeEventCalculator = changeEventCalculator; + return super.onChange(callback); + } + +} + +exports.PinchGesture = PinchGesture; +//# sourceMappingURL=pinchGesture.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/pinchGesture.js.map b/lib/commonjs/handlers/gestures/pinchGesture.js.map new file mode 100644 index 0000000000..47bf2c87d4 --- /dev/null +++ b/lib/commonjs/handlers/gestures/pinchGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["pinchGesture.ts"],"names":["changeEventCalculator","current","previous","changePayload","undefined","scaleChange","scale","PinchGesture","ContinousBaseGesture","constructor","handlerName","onChange","callback","handlers"],"mappings":";;;;;;;AAAA;;AAQA,SAASA,qBAAT,CACEC,OADF,EAEEC,QAFF,EAGE;AACA;;AACA,MAAIC,aAAJ;;AACA,MAAID,QAAQ,KAAKE,SAAjB,EAA4B;AAC1BD,IAAAA,aAAa,GAAG;AACdE,MAAAA,WAAW,EAAEJ,OAAO,CAACK;AADP,KAAhB;AAGD,GAJD,MAIO;AACLH,IAAAA,aAAa,GAAG;AACdE,MAAAA,WAAW,EAAEJ,OAAO,CAACK,KAAR,GAAgBJ,QAAQ,CAACI;AADxB,KAAhB;AAGD;;AAED,SAAO,EAAE,GAAGL,OAAL;AAAc,OAAGE;AAAjB,GAAP;AACD;;AAEM,MAAMI,YAAN,SAA2BC,6BAA3B,CAGL;AACAC,EAAAA,WAAW,GAAG;AACZ;AAEA,SAAKC,WAAL,GAAmB,qBAAnB;AACD;;AAEDC,EAAAA,QAAQ,CACNC,QADM,EAMN;AACA;AACA,SAAKC,QAAL,CAAcb,qBAAd,GAAsCA,qBAAtC;AACA,WAAO,MAAMW,QAAN,CAAeC,QAAf,CAAP;AACD;;AAjBD","sourcesContent":["import { ContinousBaseGesture } from './gesture';\nimport { PinchGestureHandlerEventPayload } from '../PinchGestureHandler';\nimport { GestureUpdateEvent } from '../gestureHandlerCommon';\n\ntype PinchGestureChangeEventPayload = {\n scaleChange: number;\n};\n\nfunction changeEventCalculator(\n current: GestureUpdateEvent,\n previous?: GestureUpdateEvent\n) {\n 'worklet';\n let changePayload: PinchGestureChangeEventPayload;\n if (previous === undefined) {\n changePayload = {\n scaleChange: current.scale,\n };\n } else {\n changePayload = {\n scaleChange: current.scale / previous.scale,\n };\n }\n\n return { ...current, ...changePayload };\n}\n\nexport class PinchGesture extends ContinousBaseGesture<\n PinchGestureHandlerEventPayload,\n PinchGestureChangeEventPayload\n> {\n constructor() {\n super();\n\n this.handlerName = 'PinchGestureHandler';\n }\n\n onChange(\n callback: (\n event: GestureUpdateEvent<\n PinchGestureHandlerEventPayload & PinchGestureChangeEventPayload\n >\n ) => void\n ) {\n // @ts-ignore TS being overprotective, PinchGestureHandlerEventPayload is Record\n this.handlers.changeEventCalculator = changeEventCalculator;\n return super.onChange(callback);\n }\n}\n\nexport type PinchGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/reanimatedWrapper.js b/lib/commonjs/handlers/gestures/reanimatedWrapper.js new file mode 100644 index 0000000000..7e376f661d --- /dev/null +++ b/lib/commonjs/handlers/gestures/reanimatedWrapper.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Reanimated = void 0; +let Reanimated; +exports.Reanimated = Reanimated; + +try { + exports.Reanimated = Reanimated = require('react-native-reanimated'); + + if (!Reanimated.setGestureState) { + Reanimated.setGestureState = () => { + 'worklet'; + + console.warn('Please use newer version of react-native-reanimated in order to control state of the gestures.'); + }; + } // When 'react-native-reanimated' is not available we want to + // quietly continue + // eslint-disable-next-line no-empty + +} catch (e) {} +//# sourceMappingURL=reanimatedWrapper.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/reanimatedWrapper.js.map b/lib/commonjs/handlers/gestures/reanimatedWrapper.js.map new file mode 100644 index 0000000000..ecd0cccaef --- /dev/null +++ b/lib/commonjs/handlers/gestures/reanimatedWrapper.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["reanimatedWrapper.ts"],"names":["Reanimated","require","setGestureState","console","warn","e"],"mappings":";;;;;;AAUA,IAAIA,UAAJ;;;AAkBA,IAAI;AACF,uBAAAA,UAAU,GAAGC,OAAO,CAAC,yBAAD,CAApB;;AAEA,MAAI,CAACD,UAAU,CAACE,eAAhB,EAAiC;AAC/BF,IAAAA,UAAU,CAACE,eAAX,GAA6B,MAAM;AACjC;;AACAC,MAAAA,OAAO,CAACC,IAAR,CACE,gGADF;AAGD,KALD;AAMD,GAVC,CAWF;AACA;AACA;;AACD,CAdD,CAcE,OAAOC,CAAP,EAAU,CAAE","sourcesContent":["import { ComponentClass } from 'react';\nimport {\n GestureUpdateEvent,\n GestureStateChangeEvent,\n} from '../gestureHandlerCommon';\n\nexport interface SharedValue {\n value: T;\n}\n\nlet Reanimated: {\n default: {\n // Slightly modified definition copied from 'react-native-reanimated'\n // eslint-disable-next-line @typescript-eslint/ban-types\n createAnimatedComponent

(\n component: ComponentClass

,\n options?: unknown\n ): ComponentClass

;\n };\n useEvent: (\n callback: (event: GestureUpdateEvent | GestureStateChangeEvent) => void,\n events: string[],\n rebuild: boolean\n ) => unknown;\n useSharedValue: (value: T) => SharedValue;\n setGestureState: (handlerTag: number, newState: number) => void;\n};\n\ntry {\n Reanimated = require('react-native-reanimated');\n\n if (!Reanimated.setGestureState) {\n Reanimated.setGestureState = () => {\n 'worklet';\n console.warn(\n 'Please use newer version of react-native-reanimated in order to control state of the gestures.'\n );\n };\n }\n // When 'react-native-reanimated' is not available we want to\n // quietly continue\n // eslint-disable-next-line no-empty\n} catch (e) {}\n\nexport { Reanimated };\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/rotationGesture.js b/lib/commonjs/handlers/gestures/rotationGesture.js new file mode 100644 index 0000000000..94a33bacb6 --- /dev/null +++ b/lib/commonjs/handlers/gestures/rotationGesture.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RotationGesture = void 0; + +var _gesture = require("./gesture"); + +function changeEventCalculator(current, previous) { + 'worklet'; + + let changePayload; + + if (previous === undefined) { + changePayload = { + rotationChange: current.rotation + }; + } else { + changePayload = { + rotationChange: current.rotation - previous.rotation + }; + } + + return { ...current, + ...changePayload + }; +} + +class RotationGesture extends _gesture.ContinousBaseGesture { + constructor() { + super(); + this.handlerName = 'RotationGestureHandler'; + } + + onChange(callback) { + // @ts-ignore TS being overprotective, RotationGestureHandlerEventPayload is Record + this.handlers.changeEventCalculator = changeEventCalculator; + return super.onChange(callback); + } + +} + +exports.RotationGesture = RotationGesture; +//# sourceMappingURL=rotationGesture.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/rotationGesture.js.map b/lib/commonjs/handlers/gestures/rotationGesture.js.map new file mode 100644 index 0000000000..357dbc8bb9 --- /dev/null +++ b/lib/commonjs/handlers/gestures/rotationGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["rotationGesture.ts"],"names":["changeEventCalculator","current","previous","changePayload","undefined","rotationChange","rotation","RotationGesture","ContinousBaseGesture","constructor","handlerName","onChange","callback","handlers"],"mappings":";;;;;;;AAAA;;AAQA,SAASA,qBAAT,CACEC,OADF,EAEEC,QAFF,EAGE;AACA;;AACA,MAAIC,aAAJ;;AACA,MAAID,QAAQ,KAAKE,SAAjB,EAA4B;AAC1BD,IAAAA,aAAa,GAAG;AACdE,MAAAA,cAAc,EAAEJ,OAAO,CAACK;AADV,KAAhB;AAGD,GAJD,MAIO;AACLH,IAAAA,aAAa,GAAG;AACdE,MAAAA,cAAc,EAAEJ,OAAO,CAACK,QAAR,GAAmBJ,QAAQ,CAACI;AAD9B,KAAhB;AAGD;;AAED,SAAO,EAAE,GAAGL,OAAL;AAAc,OAAGE;AAAjB,GAAP;AACD;;AAEM,MAAMI,eAAN,SAA8BC,6BAA9B,CAGL;AACAC,EAAAA,WAAW,GAAG;AACZ;AAEA,SAAKC,WAAL,GAAmB,wBAAnB;AACD;;AAEDC,EAAAA,QAAQ,CACNC,QADM,EAMN;AACA;AACA,SAAKC,QAAL,CAAcb,qBAAd,GAAsCA,qBAAtC;AACA,WAAO,MAAMW,QAAN,CAAeC,QAAf,CAAP;AACD;;AAjBD","sourcesContent":["import { ContinousBaseGesture } from './gesture';\nimport { RotationGestureHandlerEventPayload } from '../RotationGestureHandler';\nimport { GestureUpdateEvent } from '../gestureHandlerCommon';\n\ntype RotationGestureChangeEventPayload = {\n rotationChange: number;\n};\n\nfunction changeEventCalculator(\n current: GestureUpdateEvent,\n previous?: GestureUpdateEvent\n) {\n 'worklet';\n let changePayload: RotationGestureChangeEventPayload;\n if (previous === undefined) {\n changePayload = {\n rotationChange: current.rotation,\n };\n } else {\n changePayload = {\n rotationChange: current.rotation - previous.rotation,\n };\n }\n\n return { ...current, ...changePayload };\n}\n\nexport class RotationGesture extends ContinousBaseGesture<\n RotationGestureHandlerEventPayload,\n RotationGestureChangeEventPayload\n> {\n constructor() {\n super();\n\n this.handlerName = 'RotationGestureHandler';\n }\n\n onChange(\n callback: (\n event: GestureUpdateEvent<\n RotationGestureHandlerEventPayload & RotationGestureChangeEventPayload\n >\n ) => void\n ) {\n // @ts-ignore TS being overprotective, RotationGestureHandlerEventPayload is Record\n this.handlers.changeEventCalculator = changeEventCalculator;\n return super.onChange(callback);\n }\n}\n\nexport type RotationGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/tapGesture.js b/lib/commonjs/handlers/gestures/tapGesture.js new file mode 100644 index 0000000000..34111adb9f --- /dev/null +++ b/lib/commonjs/handlers/gestures/tapGesture.js @@ -0,0 +1,59 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TapGesture = void 0; + +var _gesture = require("./gesture"); + +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; } + +class TapGesture extends _gesture.BaseGesture { + constructor() { + super(); + + _defineProperty(this, "config", {}); + + this.handlerName = 'TapGestureHandler'; + } + + minPointers(minPointers) { + this.config.minPointers = minPointers; + return this; + } + + numberOfTaps(count) { + this.config.numberOfTaps = count; + return this; + } + + maxDistance(maxDist) { + this.config.maxDist = maxDist; + return this; + } + + maxDuration(duration) { + this.config.maxDurationMs = duration; + return this; + } + + maxDelay(delay) { + this.config.maxDelayMs = delay; + return this; + } + + maxDeltaX(delta) { + this.config.maxDeltaX = delta; + return this; + } + + maxDeltaY(delta) { + this.config.maxDeltaY = delta; + return this; + } + +} + +exports.TapGesture = TapGesture; +//# sourceMappingURL=tapGesture.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/gestures/tapGesture.js.map b/lib/commonjs/handlers/gestures/tapGesture.js.map new file mode 100644 index 0000000000..1fa6e950ff --- /dev/null +++ b/lib/commonjs/handlers/gestures/tapGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["tapGesture.ts"],"names":["TapGesture","BaseGesture","constructor","handlerName","minPointers","config","numberOfTaps","count","maxDistance","maxDist","maxDuration","duration","maxDurationMs","maxDelay","delay","maxDelayMs","maxDeltaX","delta","maxDeltaY"],"mappings":";;;;;;;AAAA;;;;AAMO,MAAMA,UAAN,SAAyBC,oBAAzB,CAAoE;AAGzEC,EAAAA,WAAW,GAAG;AACZ;;AADY,oCAFwC,EAExC;;AAGZ,SAAKC,WAAL,GAAmB,mBAAnB;AACD;;AAEDC,EAAAA,WAAW,CAACA,WAAD,EAAsB;AAC/B,SAAKC,MAAL,CAAYD,WAAZ,GAA0BA,WAA1B;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,YAAY,CAACC,KAAD,EAAgB;AAC1B,SAAKF,MAAL,CAAYC,YAAZ,GAA2BC,KAA3B;AACA,WAAO,IAAP;AACD;;AAEDC,EAAAA,WAAW,CAACC,OAAD,EAAkB;AAC3B,SAAKJ,MAAL,CAAYI,OAAZ,GAAsBA,OAAtB;AACA,WAAO,IAAP;AACD;;AAEDC,EAAAA,WAAW,CAACC,QAAD,EAAmB;AAC5B,SAAKN,MAAL,CAAYO,aAAZ,GAA4BD,QAA5B;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,QAAQ,CAACC,KAAD,EAAgB;AACtB,SAAKT,MAAL,CAAYU,UAAZ,GAAyBD,KAAzB;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,SAAS,CAACC,KAAD,EAAgB;AACvB,SAAKZ,MAAL,CAAYW,SAAZ,GAAwBC,KAAxB;AACA,WAAO,IAAP;AACD;;AAEDC,EAAAA,SAAS,CAACD,KAAD,EAAgB;AACvB,SAAKZ,MAAL,CAAYa,SAAZ,GAAwBD,KAAxB;AACA,WAAO,IAAP;AACD;;AA1CwE","sourcesContent":["import { BaseGestureConfig, BaseGesture } from './gesture';\nimport {\n TapGestureConfig,\n TapGestureHandlerEventPayload,\n} from '../TapGestureHandler';\n\nexport class TapGesture extends BaseGesture {\n public config: BaseGestureConfig & TapGestureConfig = {};\n\n constructor() {\n super();\n\n this.handlerName = 'TapGestureHandler';\n }\n\n minPointers(minPointers: number) {\n this.config.minPointers = minPointers;\n return this;\n }\n\n numberOfTaps(count: number) {\n this.config.numberOfTaps = count;\n return this;\n }\n\n maxDistance(maxDist: number) {\n this.config.maxDist = maxDist;\n return this;\n }\n\n maxDuration(duration: number) {\n this.config.maxDurationMs = duration;\n return this;\n }\n\n maxDelay(delay: number) {\n this.config.maxDelayMs = delay;\n return this;\n }\n\n maxDeltaX(delta: number) {\n this.config.maxDeltaX = delta;\n return this;\n }\n\n maxDeltaY(delta: number) {\n this.config.maxDeltaY = delta;\n return this;\n }\n}\n\nexport type TapGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/commonjs/handlers/handlersRegistry.js b/lib/commonjs/handlers/handlersRegistry.js new file mode 100644 index 0000000000..3ac12105ea --- /dev/null +++ b/lib/commonjs/handlers/handlersRegistry.js @@ -0,0 +1,31 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getNextHandlerTag = getNextHandlerTag; +exports.registerHandler = registerHandler; +exports.unregisterHandler = unregisterHandler; +exports.findHandler = findHandler; +exports.handlerIDToTag = void 0; +const handlerIDToTag = {}; +exports.handlerIDToTag = handlerIDToTag; +const handlers = new Map(); +let handlerTag = 1; + +function getNextHandlerTag() { + return handlerTag++; +} + +function registerHandler(handlerTag, handler) { + handlers.set(handlerTag, handler); +} + +function unregisterHandler(handlerTag) { + handlers.delete(handlerTag); +} + +function findHandler(handlerTag) { + return handlers.get(handlerTag); +} +//# sourceMappingURL=handlersRegistry.js.map \ No newline at end of file diff --git a/lib/commonjs/handlers/handlersRegistry.js.map b/lib/commonjs/handlers/handlersRegistry.js.map new file mode 100644 index 0000000000..6a868ab0b6 --- /dev/null +++ b/lib/commonjs/handlers/handlersRegistry.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["handlersRegistry.ts"],"names":["handlerIDToTag","handlers","Map","handlerTag","getNextHandlerTag","registerHandler","handler","set","unregisterHandler","delete","findHandler","get"],"mappings":";;;;;;;;;;AAEO,MAAMA,cAAsC,GAAG,EAA/C;;AACP,MAAMC,QAAQ,GAAG,IAAIC,GAAJ,EAAjB;AAEA,IAAIC,UAAU,GAAG,CAAjB;;AAEO,SAASC,iBAAT,GAAqC;AAC1C,SAAOD,UAAU,EAAjB;AACD;;AAEM,SAASE,eAAT,CAAyBF,UAAzB,EAA6CG,OAA7C,EAAmE;AACxEL,EAAAA,QAAQ,CAACM,GAAT,CAAaJ,UAAb,EAAyBG,OAAzB;AACD;;AAEM,SAASE,iBAAT,CAA2BL,UAA3B,EAA+C;AACpDF,EAAAA,QAAQ,CAACQ,MAAT,CAAgBN,UAAhB;AACD;;AAEM,SAASO,WAAT,CAAqBP,UAArB,EAAyC;AAC9C,SAAOF,QAAQ,CAACU,GAAT,CAAaR,UAAb,CAAP;AACD","sourcesContent":["import { GestureType } from './gestures/gesture';\n\nexport const handlerIDToTag: Record = {};\nconst handlers = new Map();\n\nlet handlerTag = 1;\n\nexport function getNextHandlerTag(): number {\n return handlerTag++;\n}\n\nexport function registerHandler(handlerTag: number, handler: GestureType) {\n handlers.set(handlerTag, handler);\n}\n\nexport function unregisterHandler(handlerTag: number) {\n handlers.delete(handlerTag);\n}\n\nexport function findHandler(handlerTag: number) {\n return handlers.get(handlerTag);\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/index.js b/lib/commonjs/index.js new file mode 100644 index 0000000000..53f35b08a8 --- /dev/null +++ b/lib/commonjs/index.js @@ -0,0 +1,232 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "Directions", { + enumerable: true, + get: function () { + return _Directions.Directions; + } +}); +Object.defineProperty(exports, "State", { + enumerable: true, + get: function () { + return _State.State; + } +}); +Object.defineProperty(exports, "gestureHandlerRootHOC", { + enumerable: true, + get: function () { + return _gestureHandlerRootHOC.default; + } +}); +Object.defineProperty(exports, "GestureHandlerRootView", { + enumerable: true, + get: function () { + return _GestureHandlerRootView.default; + } +}); +Object.defineProperty(exports, "TapGestureHandler", { + enumerable: true, + get: function () { + return _TapGestureHandler.TapGestureHandler; + } +}); +Object.defineProperty(exports, "ForceTouchGestureHandler", { + enumerable: true, + get: function () { + return _ForceTouchGestureHandler.ForceTouchGestureHandler; + } +}); +Object.defineProperty(exports, "LongPressGestureHandler", { + enumerable: true, + get: function () { + return _LongPressGestureHandler.LongPressGestureHandler; + } +}); +Object.defineProperty(exports, "PanGestureHandler", { + enumerable: true, + get: function () { + return _PanGestureHandler.PanGestureHandler; + } +}); +Object.defineProperty(exports, "PinchGestureHandler", { + enumerable: true, + get: function () { + return _PinchGestureHandler.PinchGestureHandler; + } +}); +Object.defineProperty(exports, "RotationGestureHandler", { + enumerable: true, + get: function () { + return _RotationGestureHandler.RotationGestureHandler; + } +}); +Object.defineProperty(exports, "FlingGestureHandler", { + enumerable: true, + get: function () { + return _FlingGestureHandler.FlingGestureHandler; + } +}); +Object.defineProperty(exports, "createNativeWrapper", { + enumerable: true, + get: function () { + return _createNativeWrapper.default; + } +}); +Object.defineProperty(exports, "GestureDetector", { + enumerable: true, + get: function () { + return _GestureDetector.GestureDetector; + } +}); +Object.defineProperty(exports, "Gesture", { + enumerable: true, + get: function () { + return _gestureObjects.GestureObjects; + } +}); +Object.defineProperty(exports, "NativeViewGestureHandler", { + enumerable: true, + get: function () { + return _NativeViewGestureHandler.NativeViewGestureHandler; + } +}); +Object.defineProperty(exports, "RawButton", { + enumerable: true, + get: function () { + return _GestureButtons.RawButton; + } +}); +Object.defineProperty(exports, "BaseButton", { + enumerable: true, + get: function () { + return _GestureButtons.BaseButton; + } +}); +Object.defineProperty(exports, "RectButton", { + enumerable: true, + get: function () { + return _GestureButtons.RectButton; + } +}); +Object.defineProperty(exports, "BorderlessButton", { + enumerable: true, + get: function () { + return _GestureButtons.BorderlessButton; + } +}); +Object.defineProperty(exports, "TouchableHighlight", { + enumerable: true, + get: function () { + return _touchables.TouchableHighlight; + } +}); +Object.defineProperty(exports, "TouchableNativeFeedback", { + enumerable: true, + get: function () { + return _touchables.TouchableNativeFeedback; + } +}); +Object.defineProperty(exports, "TouchableOpacity", { + enumerable: true, + get: function () { + return _touchables.TouchableOpacity; + } +}); +Object.defineProperty(exports, "TouchableWithoutFeedback", { + enumerable: true, + get: function () { + return _touchables.TouchableWithoutFeedback; + } +}); +Object.defineProperty(exports, "ScrollView", { + enumerable: true, + get: function () { + return _GestureComponents.ScrollView; + } +}); +Object.defineProperty(exports, "Switch", { + enumerable: true, + get: function () { + return _GestureComponents.Switch; + } +}); +Object.defineProperty(exports, "TextInput", { + enumerable: true, + get: function () { + return _GestureComponents.TextInput; + } +}); +Object.defineProperty(exports, "DrawerLayoutAndroid", { + enumerable: true, + get: function () { + return _GestureComponents.DrawerLayoutAndroid; + } +}); +Object.defineProperty(exports, "FlatList", { + enumerable: true, + get: function () { + return _GestureComponents.FlatList; + } +}); +Object.defineProperty(exports, "Swipeable", { + enumerable: true, + get: function () { + return _Swipeable.default; + } +}); +Object.defineProperty(exports, "DrawerLayout", { + enumerable: true, + get: function () { + return _DrawerLayout.default; + } +}); + +var _init = require("./init"); + +var _Directions = require("./Directions"); + +var _State = require("./State"); + +var _gestureHandlerRootHOC = _interopRequireDefault(require("./gestureHandlerRootHOC")); + +var _GestureHandlerRootView = _interopRequireDefault(require("./GestureHandlerRootView")); + +var _TapGestureHandler = require("./handlers/TapGestureHandler"); + +var _ForceTouchGestureHandler = require("./handlers/ForceTouchGestureHandler"); + +var _LongPressGestureHandler = require("./handlers/LongPressGestureHandler"); + +var _PanGestureHandler = require("./handlers/PanGestureHandler"); + +var _PinchGestureHandler = require("./handlers/PinchGestureHandler"); + +var _RotationGestureHandler = require("./handlers/RotationGestureHandler"); + +var _FlingGestureHandler = require("./handlers/FlingGestureHandler"); + +var _createNativeWrapper = _interopRequireDefault(require("./handlers/createNativeWrapper")); + +var _GestureDetector = require("./handlers/gestures/GestureDetector"); + +var _gestureObjects = require("./handlers/gestures/gestureObjects"); + +var _NativeViewGestureHandler = require("./handlers/NativeViewGestureHandler"); + +var _GestureButtons = require("./components/GestureButtons"); + +var _touchables = require("./components/touchables"); + +var _GestureComponents = require("./components/GestureComponents"); + +var _Swipeable = _interopRequireDefault(require("./components/Swipeable")); + +var _DrawerLayout = _interopRequireDefault(require("./components/DrawerLayout")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +(0, _init.initialize)(); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/commonjs/index.js.map b/lib/commonjs/index.js.map new file mode 100644 index 0000000000..00f4743e2d --- /dev/null +++ b/lib/commonjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;AAEA;;AACA;;AACA;;AACA;;AA4CA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAKA;;AACA;;AAiBA;;AAOA;;AAMA;;AAMA;;AA8CA;;AASA;;;;AAEA","sourcesContent":["import { initialize } from './init';\n\nexport { Directions } from './Directions';\nexport { State } from './State';\nexport { default as gestureHandlerRootHOC } from './gestureHandlerRootHOC';\nexport { default as GestureHandlerRootView } from './GestureHandlerRootView';\nexport type {\n // event types\n GestureEvent,\n HandlerStateChangeEvent,\n // event payloads types\n GestureEventPayload,\n HandlerStateChangeEventPayload,\n // pointer events\n GestureTouchEvent,\n TouchData,\n // new api event types\n GestureUpdateEvent,\n GestureStateChangeEvent,\n} from './handlers/gestureHandlerCommon';\nexport type { GestureType } from './handlers/gestures/gesture';\nexport type {\n TapGestureHandlerEventPayload,\n TapGestureHandlerProps,\n} from './handlers/TapGestureHandler';\nexport type {\n ForceTouchGestureHandlerEventPayload,\n ForceTouchGestureHandlerProps,\n} from './handlers/ForceTouchGestureHandler';\nexport type {\n LongPressGestureHandlerEventPayload,\n LongPressGestureHandlerProps,\n} from './handlers/LongPressGestureHandler';\nexport type {\n PanGestureHandlerEventPayload,\n PanGestureHandlerProps,\n} from './handlers/PanGestureHandler';\nexport type {\n PinchGestureHandlerEventPayload,\n PinchGestureHandlerProps,\n} from './handlers/PinchGestureHandler';\nexport type {\n RotationGestureHandlerEventPayload,\n RotationGestureHandlerProps,\n} from './handlers/RotationGestureHandler';\nexport type {\n FlingGestureHandlerEventPayload,\n FlingGestureHandlerProps,\n} from './handlers/FlingGestureHandler';\nexport { TapGestureHandler } from './handlers/TapGestureHandler';\nexport { ForceTouchGestureHandler } from './handlers/ForceTouchGestureHandler';\nexport { LongPressGestureHandler } from './handlers/LongPressGestureHandler';\nexport { PanGestureHandler } from './handlers/PanGestureHandler';\nexport { PinchGestureHandler } from './handlers/PinchGestureHandler';\nexport { RotationGestureHandler } from './handlers/RotationGestureHandler';\nexport { FlingGestureHandler } from './handlers/FlingGestureHandler';\nexport { default as createNativeWrapper } from './handlers/createNativeWrapper';\nexport type {\n NativeViewGestureHandlerPayload,\n NativeViewGestureHandlerProps,\n} from './handlers/NativeViewGestureHandler';\nexport { GestureDetector } from './handlers/gestures/GestureDetector';\nexport { GestureObjects as Gesture } from './handlers/gestures/gestureObjects';\nexport type { TapGestureType as TapGesture } from './handlers/gestures/tapGesture';\nexport type { PanGestureType as PanGesture } from './handlers/gestures/panGesture';\nexport type { FlingGestureType as FlingGesture } from './handlers/gestures/flingGesture';\nexport type { LongPressGestureType as LongPressGesture } from './handlers/gestures/longPressGesture';\nexport type { PinchGestureType as PinchGesture } from './handlers/gestures/pinchGesture';\nexport type { RotationGestureType as RotationGesture } from './handlers/gestures/rotationGesture';\nexport type { ForceTouchGestureType as ForceTouchGesture } from './handlers/gestures/forceTouchGesture';\nexport type { NativeGestureType as NativeGesture } from './handlers/gestures/nativeGesture';\nexport type { ManualGestureType as ManualGesture } from './handlers/gestures/manualGesture';\nexport type {\n ComposedGestureType as ComposedGesture,\n RaceGestureType as RaceGesture,\n SimultaneousGestureType as SimultaneousGesture,\n ExclusiveGestureType as ExclusiveGesture,\n} from './handlers/gestures/gestureComposition';\nexport type { GestureStateManagerType as GestureStateManager } from './handlers/gestures/gestureStateManager';\nexport { NativeViewGestureHandler } from './handlers/NativeViewGestureHandler';\nexport type {\n RawButtonProps,\n BaseButtonProps,\n RectButtonProps,\n BorderlessButtonProps,\n} from './components/GestureButtons';\nexport {\n RawButton,\n BaseButton,\n RectButton,\n BorderlessButton,\n} from './components/GestureButtons';\nexport {\n TouchableHighlight,\n TouchableNativeFeedback,\n TouchableOpacity,\n TouchableWithoutFeedback,\n} from './components/touchables';\nexport {\n ScrollView,\n Switch,\n TextInput,\n DrawerLayoutAndroid,\n FlatList,\n} from './components/GestureComponents';\nexport type {\n //events\n GestureHandlerGestureEvent,\n GestureHandlerStateChangeEvent,\n //event payloads\n GestureHandlerGestureEventNativeEvent,\n GestureHandlerStateChangeNativeEvent,\n NativeViewGestureHandlerGestureEvent,\n NativeViewGestureHandlerStateChangeEvent,\n TapGestureHandlerGestureEvent,\n TapGestureHandlerStateChangeEvent,\n ForceTouchGestureHandlerGestureEvent,\n ForceTouchGestureHandlerStateChangeEvent,\n LongPressGestureHandlerGestureEvent,\n LongPressGestureHandlerStateChangeEvent,\n PanGestureHandlerGestureEvent,\n PanGestureHandlerStateChangeEvent,\n PinchGestureHandlerGestureEvent,\n PinchGestureHandlerStateChangeEvent,\n RotationGestureHandlerGestureEvent,\n RotationGestureHandlerStateChangeEvent,\n FlingGestureHandlerGestureEvent,\n FlingGestureHandlerStateChangeEvent,\n // handlers props\n NativeViewGestureHandlerProperties,\n TapGestureHandlerProperties,\n LongPressGestureHandlerProperties,\n PanGestureHandlerProperties,\n PinchGestureHandlerProperties,\n RotationGestureHandlerProperties,\n FlingGestureHandlerProperties,\n ForceTouchGestureHandlerProperties,\n // buttons props\n RawButtonProperties,\n BaseButtonProperties,\n RectButtonProperties,\n BorderlessButtonProperties,\n} from './handlers/gestureHandlerTypesCompat';\n\nexport { default as Swipeable } from './components/Swipeable';\nexport type {\n DrawerLayoutProps,\n DrawerPosition,\n DrawerState,\n DrawerType,\n DrawerLockMode,\n DrawerKeyboardDismissMode,\n} from './components/DrawerLayout';\nexport { default as DrawerLayout } from './components/DrawerLayout';\n\ninitialize();\n"]} \ No newline at end of file diff --git a/lib/commonjs/init.js b/lib/commonjs/init.js new file mode 100644 index 0000000000..73ae9d230f --- /dev/null +++ b/lib/commonjs/init.js @@ -0,0 +1,13 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.initialize = initialize; + +var _eventReceiver = require("./handlers/gestures/eventReceiver"); + +function initialize() { + (0, _eventReceiver.startListening)(); +} +//# sourceMappingURL=init.js.map \ No newline at end of file diff --git a/lib/commonjs/init.js.map b/lib/commonjs/init.js.map new file mode 100644 index 0000000000..6371c19eb7 --- /dev/null +++ b/lib/commonjs/init.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["init.ts"],"names":["initialize"],"mappings":";;;;;;;AAAA;;AAEO,SAASA,UAAT,GAAsB;AAC3B;AACD","sourcesContent":["import { startListening } from './handlers/gestures/eventReceiver';\n\nexport function initialize() {\n startListening();\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/mocks.js b/lib/commonjs/mocks.js new file mode 100644 index 0000000000..5b4fdc033b --- /dev/null +++ b/lib/commonjs/mocks.js @@ -0,0 +1,64 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _reactNative = require("react-native"); + +var _State = require("./State"); + +var _Directions = require("./Directions"); + +const NOOP = () => {// do nothing +}; + +const PanGestureHandler = _reactNative.View; +const attachGestureHandler = NOOP; +const createGestureHandler = NOOP; +const dropGestureHandler = NOOP; +const updateGestureHandler = NOOP; +const NativeViewGestureHandler = _reactNative.View; +const TapGestureHandler = _reactNative.View; +const ForceTouchGestureHandler = _reactNative.View; +const LongPressGestureHandler = _reactNative.View; +const PinchGestureHandler = _reactNative.View; +const RotationGestureHandler = _reactNative.View; +const FlingGestureHandler = _reactNative.View; +const RawButton = _reactNative.TouchableNativeFeedback; +const BaseButton = _reactNative.TouchableNativeFeedback; +const RectButton = _reactNative.TouchableNativeFeedback; +const BorderlessButton = _reactNative.TouchableNativeFeedback; +var _default = { + TouchableHighlight: _reactNative.TouchableHighlight, + TouchableNativeFeedback: _reactNative.TouchableNativeFeedback, + TouchableOpacity: _reactNative.TouchableOpacity, + TouchableWithoutFeedback: _reactNative.TouchableWithoutFeedback, + ScrollView: _reactNative.ScrollView, + FlatList: _reactNative.FlatList, + Switch: _reactNative.Switch, + TextInput: _reactNative.TextInput, + DrawerLayoutAndroid: _reactNative.DrawerLayoutAndroid, + NativeViewGestureHandler, + TapGestureHandler, + ForceTouchGestureHandler, + LongPressGestureHandler, + PinchGestureHandler, + RotationGestureHandler, + FlingGestureHandler, + RawButton, + BaseButton, + RectButton, + BorderlessButton, + PanGestureHandler, + attachGestureHandler, + createGestureHandler, + dropGestureHandler, + updateGestureHandler, + // probably can be removed + Directions: _Directions.Directions, + State: _State.State +}; +exports.default = _default; +//# sourceMappingURL=mocks.js.map \ No newline at end of file diff --git a/lib/commonjs/mocks.js.map b/lib/commonjs/mocks.js.map new file mode 100644 index 0000000000..cce7f5cd4d --- /dev/null +++ b/lib/commonjs/mocks.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["mocks.ts"],"names":["NOOP","PanGestureHandler","View","attachGestureHandler","createGestureHandler","dropGestureHandler","updateGestureHandler","NativeViewGestureHandler","TapGestureHandler","ForceTouchGestureHandler","LongPressGestureHandler","PinchGestureHandler","RotationGestureHandler","FlingGestureHandler","RawButton","TouchableNativeFeedback","BaseButton","RectButton","BorderlessButton","TouchableHighlight","TouchableOpacity","TouchableWithoutFeedback","ScrollView","FlatList","Switch","TextInput","DrawerLayoutAndroid","Directions","State"],"mappings":";;;;;;;AAAA;;AAYA;;AACA;;AAEA,MAAMA,IAAI,GAAG,MAAM,CACjB;AACD,CAFD;;AAGA,MAAMC,iBAAiB,GAAGC,iBAA1B;AACA,MAAMC,oBAAoB,GAAGH,IAA7B;AACA,MAAMI,oBAAoB,GAAGJ,IAA7B;AACA,MAAMK,kBAAkB,GAAGL,IAA3B;AACA,MAAMM,oBAAoB,GAAGN,IAA7B;AACA,MAAMO,wBAAwB,GAAGL,iBAAjC;AACA,MAAMM,iBAAiB,GAAGN,iBAA1B;AACA,MAAMO,wBAAwB,GAAGP,iBAAjC;AACA,MAAMQ,uBAAuB,GAAGR,iBAAhC;AACA,MAAMS,mBAAmB,GAAGT,iBAA5B;AACA,MAAMU,sBAAsB,GAAGV,iBAA/B;AACA,MAAMW,mBAAmB,GAAGX,iBAA5B;AACA,MAAMY,SAAS,GAAGC,oCAAlB;AACA,MAAMC,UAAU,GAAGD,oCAAnB;AACA,MAAME,UAAU,GAAGF,oCAAnB;AACA,MAAMG,gBAAgB,GAAGH,oCAAzB;eAEe;AACbI,EAAAA,kBAAkB,EAAlBA,+BADa;AAEbJ,EAAAA,uBAAuB,EAAvBA,oCAFa;AAGbK,EAAAA,gBAAgB,EAAhBA,6BAHa;AAIbC,EAAAA,wBAAwB,EAAxBA,qCAJa;AAKbC,EAAAA,UAAU,EAAVA,uBALa;AAMbC,EAAAA,QAAQ,EAARA,qBANa;AAObC,EAAAA,MAAM,EAANA,mBAPa;AAQbC,EAAAA,SAAS,EAATA,sBARa;AASbC,EAAAA,mBAAmB,EAAnBA,gCATa;AAUbnB,EAAAA,wBAVa;AAWbC,EAAAA,iBAXa;AAYbC,EAAAA,wBAZa;AAabC,EAAAA,uBAba;AAcbC,EAAAA,mBAda;AAebC,EAAAA,sBAfa;AAgBbC,EAAAA,mBAhBa;AAiBbC,EAAAA,SAjBa;AAkBbE,EAAAA,UAlBa;AAmBbC,EAAAA,UAnBa;AAoBbC,EAAAA,gBApBa;AAqBbjB,EAAAA,iBArBa;AAsBbE,EAAAA,oBAtBa;AAuBbC,EAAAA,oBAvBa;AAwBbC,EAAAA,kBAxBa;AAyBbC,EAAAA,oBAzBa;AA0Bb;AACAqB,EAAAA,UAAU,EAAVA,sBA3Ba;AA4BbC,EAAAA,KAAK,EAALA;AA5Ba,C","sourcesContent":["import {\n TouchableHighlight,\n TouchableNativeFeedback,\n TouchableOpacity,\n TouchableWithoutFeedback,\n ScrollView,\n FlatList,\n Switch,\n TextInput,\n DrawerLayoutAndroid,\n View,\n} from 'react-native';\nimport { State } from './State';\nimport { Directions } from './Directions';\n\nconst NOOP = () => {\n // do nothing\n};\nconst PanGestureHandler = View;\nconst attachGestureHandler = NOOP;\nconst createGestureHandler = NOOP;\nconst dropGestureHandler = NOOP;\nconst updateGestureHandler = NOOP;\nconst NativeViewGestureHandler = View;\nconst TapGestureHandler = View;\nconst ForceTouchGestureHandler = View;\nconst LongPressGestureHandler = View;\nconst PinchGestureHandler = View;\nconst RotationGestureHandler = View;\nconst FlingGestureHandler = View;\nconst RawButton = TouchableNativeFeedback;\nconst BaseButton = TouchableNativeFeedback;\nconst RectButton = TouchableNativeFeedback;\nconst BorderlessButton = TouchableNativeFeedback;\n\nexport default {\n TouchableHighlight,\n TouchableNativeFeedback,\n TouchableOpacity,\n TouchableWithoutFeedback,\n ScrollView,\n FlatList,\n Switch,\n TextInput,\n DrawerLayoutAndroid,\n NativeViewGestureHandler,\n TapGestureHandler,\n ForceTouchGestureHandler,\n LongPressGestureHandler,\n PinchGestureHandler,\n RotationGestureHandler,\n FlingGestureHandler,\n RawButton,\n BaseButton,\n RectButton,\n BorderlessButton,\n PanGestureHandler,\n attachGestureHandler,\n createGestureHandler,\n dropGestureHandler,\n updateGestureHandler,\n // probably can be removed\n Directions,\n State,\n} as const;\n"]} \ No newline at end of file diff --git a/lib/commonjs/typeUtils.js b/lib/commonjs/typeUtils.js new file mode 100644 index 0000000000..ae0eefb321 --- /dev/null +++ b/lib/commonjs/typeUtils.js @@ -0,0 +1,2 @@ +"use strict"; +//# sourceMappingURL=typeUtils.js.map \ No newline at end of file diff --git a/lib/commonjs/typeUtils.js.map b/lib/commonjs/typeUtils.js.map new file mode 100644 index 0000000000..9ffd4b22fc --- /dev/null +++ b/lib/commonjs/typeUtils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","sourcesContent":[]} \ No newline at end of file diff --git a/lib/commonjs/utils.js b/lib/commonjs/utils.js new file mode 100644 index 0000000000..b1720bf8e0 --- /dev/null +++ b/lib/commonjs/utils.js @@ -0,0 +1,15 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.toArray = toArray; + +function toArray(object) { + if (!Array.isArray(object)) { + return [object]; + } + + return object; +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/lib/commonjs/utils.js.map b/lib/commonjs/utils.js.map new file mode 100644 index 0000000000..31448144f1 --- /dev/null +++ b/lib/commonjs/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["utils.ts"],"names":["toArray","object","Array","isArray"],"mappings":";;;;;;;AAAO,SAASA,OAAT,CAAoBC,MAApB,EAA0C;AAC/C,MAAI,CAACC,KAAK,CAACC,OAAN,CAAcF,MAAd,CAAL,EAA4B;AAC1B,WAAO,CAACA,MAAD,CAAP;AACD;;AAED,SAAOA,MAAP;AACD","sourcesContent":["export function toArray(object: T | T[]): T[] {\n if (!Array.isArray(object)) {\n return [object];\n }\n\n return object;\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/DiscreteGestureHandler.js b/lib/commonjs/web/DiscreteGestureHandler.js new file mode 100644 index 0000000000..e9cf916a19 --- /dev/null +++ b/lib/commonjs/web/DiscreteGestureHandler.js @@ -0,0 +1,105 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _GestureHandler = _interopRequireDefault(require("./GestureHandler")); + +var _utils = require("./utils"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint-disable eslint-comments/no-unlimited-disable */ + +/* eslint-disable */ +class DiscreteGestureHandler extends _GestureHandler.default { + get isDiscrete() { + return true; + } + + get shouldEnableGestureOnSetup() { + return true; + } + + shouldFailUnderCustomCriteria({ + x, + y, + deltaX, + deltaY + }, { + maxDeltaX, + maxDeltaY, + maxDistSq, + shouldCancelWhenOutside + }) { + if (shouldCancelWhenOutside) { + if (!this.isPointInView({ + x, + y + })) { + return true; + } + } + + return (0, _utils.TEST_MAX_IF_NOT_NAN)(Math.abs(deltaX), maxDeltaX) || (0, _utils.TEST_MAX_IF_NOT_NAN)(Math.abs(deltaY), maxDeltaY) || (0, _utils.TEST_MAX_IF_NOT_NAN)(Math.abs(deltaY * deltaY + deltaX * deltaX), maxDistSq); + } + + transformNativeEvent({ + center: { + x, + y + } + }) { + // @ts-ignore FIXME(TS) + const rect = this.view.getBoundingClientRect(); + return { + absoluteX: x, + absoluteY: y, + x: x - rect.left, + y: y - rect.top + }; + } + + isGestureEnabledForEvent({ + minPointers, + maxPointers, + maxDeltaX, + maxDeltaY, + maxDistSq, + shouldCancelWhenOutside + }, _recognizer, { + maxPointers: pointerLength, + center, + deltaX, + deltaY + }) { + const validPointerCount = pointerLength >= minPointers && pointerLength <= maxPointers; + + if (this.shouldFailUnderCustomCriteria({ ...center, + deltaX, + deltaY + }, { + maxDeltaX, + maxDeltaY, + maxDistSq, + shouldCancelWhenOutside + }) || // A user probably won't land a multi-pointer tap on the first tick (so we cannot just cancel each time) + // but if the gesture is running and the user adds or subtracts another pointer then it should fail. + !validPointerCount && this.isGestureRunning) { + return { + failed: true + }; + } + + return { + success: validPointerCount + }; + } + +} + +var _default = DiscreteGestureHandler; +exports.default = _default; +//# sourceMappingURL=DiscreteGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/web/DiscreteGestureHandler.js.map b/lib/commonjs/web/DiscreteGestureHandler.js.map new file mode 100644 index 0000000000..a15efc5aa5 --- /dev/null +++ b/lib/commonjs/web/DiscreteGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["DiscreteGestureHandler.ts"],"names":["DiscreteGestureHandler","GestureHandler","isDiscrete","shouldEnableGestureOnSetup","shouldFailUnderCustomCriteria","x","y","deltaX","deltaY","maxDeltaX","maxDeltaY","maxDistSq","shouldCancelWhenOutside","isPointInView","Math","abs","transformNativeEvent","center","rect","view","getBoundingClientRect","absoluteX","absoluteY","left","top","isGestureEnabledForEvent","minPointers","maxPointers","_recognizer","pointerLength","validPointerCount","isGestureRunning","failed","success"],"mappings":";;;;;;;AAEA;;AACA;;;;AAHA;;AACA;AAIA,MAAeA,sBAAf,SAA8CC,uBAA9C,CAA6D;AAC7C,MAAVC,UAAU,GAAG;AACf,WAAO,IAAP;AACD;;AAE6B,MAA1BC,0BAA0B,GAAG;AAC/B,WAAO,IAAP;AACD;;AAEDC,EAAAA,6BAA6B,CAC3B;AAAEC,IAAAA,CAAF;AAAKC,IAAAA,CAAL;AAAQC,IAAAA,MAAR;AAAgBC,IAAAA;AAAhB,GAD2B,EAE3B;AAAEC,IAAAA,SAAF;AAAaC,IAAAA,SAAb;AAAwBC,IAAAA,SAAxB;AAAmCC,IAAAA;AAAnC,GAF2B,EAG3B;AACA,QAAIA,uBAAJ,EAA6B;AAC3B,UAAI,CAAC,KAAKC,aAAL,CAAmB;AAAER,QAAAA,CAAF;AAAKC,QAAAA;AAAL,OAAnB,CAAL,EAAmC;AACjC,eAAO,IAAP;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C,KAACkB,iBAAD,IAAsB,KAAKC,gBAZ9B,EAaE;AACA,aAAO;AAAEC,QAAAA,MAAM,EAAE;AAAV,OAAP;AACD;;AAED,WAAO;AAAEC,MAAAA,OAAO,EAAEH;AAAX,KAAP;AACD;;AAzE0D;;eA4E9C9B,sB","sourcesContent":["/* eslint-disable eslint-comments/no-unlimited-disable */\n/* eslint-disable */\nimport GestureHandler from './GestureHandler';\nimport { TEST_MAX_IF_NOT_NAN } from './utils';\n\nabstract class DiscreteGestureHandler extends GestureHandler {\n get isDiscrete() {\n return true;\n }\n\n get shouldEnableGestureOnSetup() {\n return true;\n }\n\n shouldFailUnderCustomCriteria(\n { x, y, deltaX, deltaY }: any,\n { maxDeltaX, maxDeltaY, maxDistSq, shouldCancelWhenOutside }: any\n ) {\n if (shouldCancelWhenOutside) {\n if (!this.isPointInView({ x, y })) {\n return true;\n }\n }\n return (\n TEST_MAX_IF_NOT_NAN(Math.abs(deltaX), maxDeltaX) ||\n TEST_MAX_IF_NOT_NAN(Math.abs(deltaY), maxDeltaY) ||\n TEST_MAX_IF_NOT_NAN(\n Math.abs(deltaY * deltaY + deltaX * deltaX),\n maxDistSq\n )\n );\n }\n\n transformNativeEvent({ center: { x, y } }: any) {\n // @ts-ignore FIXME(TS)\n const rect = this.view!.getBoundingClientRect();\n\n return {\n absoluteX: x,\n absoluteY: y,\n x: x - rect.left,\n y: y - rect.top,\n };\n }\n\n isGestureEnabledForEvent(\n {\n minPointers,\n maxPointers,\n maxDeltaX,\n maxDeltaY,\n maxDistSq,\n shouldCancelWhenOutside,\n }: any,\n _recognizer: any,\n { maxPointers: pointerLength, center, deltaX, deltaY }: any\n ) {\n const validPointerCount =\n pointerLength >= minPointers && pointerLength <= maxPointers;\n\n if (\n this.shouldFailUnderCustomCriteria(\n { ...center, deltaX, deltaY },\n {\n maxDeltaX,\n maxDeltaY,\n maxDistSq,\n shouldCancelWhenOutside,\n }\n ) ||\n // A user probably won't land a multi-pointer tap on the first tick (so we cannot just cancel each time)\n // but if the gesture is running and the user adds or subtracts another pointer then it should fail.\n (!validPointerCount && this.isGestureRunning)\n ) {\n return { failed: true };\n }\n\n return { success: validPointerCount };\n }\n}\n\nexport default DiscreteGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/DraggingGestureHandler.js b/lib/commonjs/web/DraggingGestureHandler.js new file mode 100644 index 0000000000..82a4e21530 --- /dev/null +++ b/lib/commonjs/web/DraggingGestureHandler.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _GestureHandler = _interopRequireDefault(require("./GestureHandler")); + +var _reactNative = require("react-native"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint-disable eslint-comments/no-unlimited-disable */ + +/* eslint-disable */ +class DraggingGestureHandler extends _GestureHandler.default { + get shouldEnableGestureOnSetup() { + return true; + } + + transformNativeEvent({ + deltaX, + deltaY, + velocityX, + velocityY, + center: { + x, + y + } + }) { + // @ts-ignore FIXME(TS) + const rect = this.view.getBoundingClientRect(); + + const ratio = _reactNative.PixelRatio.get(); + + return { + translationX: deltaX - (this.__initialX || 0), + translationY: deltaY - (this.__initialY || 0), + absoluteX: x, + absoluteY: y, + velocityX: velocityX * ratio, + velocityY: velocityY * ratio, + x: x - rect.left, + y: y - rect.top + }; + } + +} + +var _default = DraggingGestureHandler; +exports.default = _default; +//# sourceMappingURL=DraggingGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/web/DraggingGestureHandler.js.map b/lib/commonjs/web/DraggingGestureHandler.js.map new file mode 100644 index 0000000000..f2b17a86fd --- /dev/null +++ b/lib/commonjs/web/DraggingGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["DraggingGestureHandler.ts"],"names":["DraggingGestureHandler","GestureHandler","shouldEnableGestureOnSetup","transformNativeEvent","deltaX","deltaY","velocityX","velocityY","center","x","y","rect","view","getBoundingClientRect","ratio","PixelRatio","get","translationX","__initialX","translationY","__initialY","absoluteX","absoluteY","left","top"],"mappings":";;;;;;;AAEA;;AACA;;;;AAHA;;AACA;AAIA,MAAeA,sBAAf,SAA8CC,uBAA9C,CAA6D;AAC7B,MAA1BC,0BAA0B,GAAG;AAC/B,WAAO,IAAP;AACD;;AAEDC,EAAAA,oBAAoB,CAAC;AACnBC,IAAAA,MADmB;AAEnBC,IAAAA,MAFmB;AAGnBC,IAAAA,SAHmB;AAInBC,IAAAA,SAJmB;AAKnBC,IAAAA,MAAM,EAAE;AAAEC,MAAAA,CAAF;AAAKC,MAAAA;AAAL;AALW,GAAD,EAMD;AACjB;AACA,UAAMC,IAAI,GAAG,KAAKC,IAAL,CAAWC,qBAAX,EAAb;;AACA,UAAMC,KAAK,GAAGC,wBAAWC,GAAX,EAAd;;AACA,WAAO;AACLC,MAAAA,YAAY,EAAEb,MAAM,IAAI,KAAKc,UAAL,IAAmB,CAAvB,CADf;AAELC,MAAAA,YAAY,EAAEd,MAAM,IAAI,KAAKe,UAAL,IAAmB,CAAvB,CAFf;AAGLC,MAAAA,SAAS,EAAEZ,CAHN;AAILa,MAAAA,SAAS,EAAEZ,CAJN;AAKLJ,MAAAA,SAAS,EAAEA,SAAS,GAAGQ,KALlB;AAMLP,MAAAA,SAAS,EAAEA,SAAS,GAAGO,KANlB;AAOLL,MAAAA,CAAC,EAAEA,CAAC,GAAGE,IAAI,CAACY,IAPP;AAQLb,MAAAA,CAAC,EAAEA,CAAC,GAAGC,IAAI,CAACa;AARP,KAAP;AAUD;;AAzB0D;;eA4B9CxB,sB","sourcesContent":["/* eslint-disable eslint-comments/no-unlimited-disable */\n/* eslint-disable */\nimport GestureHandler, { HammerInputExt } from './GestureHandler';\nimport { PixelRatio } from 'react-native';\n\nabstract class DraggingGestureHandler extends GestureHandler {\n get shouldEnableGestureOnSetup() {\n return true;\n }\n\n transformNativeEvent({\n deltaX,\n deltaY,\n velocityX,\n velocityY,\n center: { x, y },\n }: HammerInputExt) {\n // @ts-ignore FIXME(TS)\n const rect = this.view!.getBoundingClientRect();\n const ratio = PixelRatio.get();\n return {\n translationX: deltaX - (this.__initialX || 0),\n translationY: deltaY - (this.__initialY || 0),\n absoluteX: x,\n absoluteY: y,\n velocityX: velocityX * ratio,\n velocityY: velocityY * ratio,\n x: x - rect.left,\n y: y - rect.top,\n };\n }\n}\n\nexport default DraggingGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/Errors.js b/lib/commonjs/web/Errors.js new file mode 100644 index 0000000000..01eeb4eea8 --- /dev/null +++ b/lib/commonjs/web/Errors.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GesturePropError = void 0; + +class GesturePropError extends Error { + constructor(name, value, expectedType) { + super(`Invalid property \`${name}: ${value}\` expected \`${expectedType}\``); + } + +} + +exports.GesturePropError = GesturePropError; +//# sourceMappingURL=Errors.js.map \ No newline at end of file diff --git a/lib/commonjs/web/Errors.js.map b/lib/commonjs/web/Errors.js.map new file mode 100644 index 0000000000..97a926b421 --- /dev/null +++ b/lib/commonjs/web/Errors.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["Errors.ts"],"names":["GesturePropError","Error","constructor","name","value","expectedType"],"mappings":";;;;;;;AAAO,MAAMA,gBAAN,SAA+BC,KAA/B,CAAqC;AAC1CC,EAAAA,WAAW,CAACC,IAAD,EAAeC,KAAf,EAA+BC,YAA/B,EAAqD;AAC9D,UACG,sBAAqBF,IAAK,KAAIC,KAAM,iBAAgBC,YAAa,IADpE;AAGD;;AALyC","sourcesContent":["export class GesturePropError extends Error {\n constructor(name: string, value: unknown, expectedType: string) {\n super(\n `Invalid property \\`${name}: ${value}\\` expected \\`${expectedType}\\``\n );\n }\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/FlingGestureHandler.js b/lib/commonjs/web/FlingGestureHandler.js new file mode 100644 index 0000000000..554f5fd888 --- /dev/null +++ b/lib/commonjs/web/FlingGestureHandler.js @@ -0,0 +1,170 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _hammerjs = _interopRequireDefault(require("@egjs/hammerjs")); + +var _constants = require("./constants"); + +var _Errors = require("./Errors"); + +var _DraggingGestureHandler = _interopRequireDefault(require("./DraggingGestureHandler")); + +var _utils = require("./utils"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint-disable eslint-comments/no-unlimited-disable */ + +/* eslint-disable */ +class FlingGestureHandler extends _DraggingGestureHandler.default { + get name() { + return 'swipe'; + } + + get NativeGestureClass() { + return _hammerjs.default.Swipe; + } + + onGestureActivated(event) { + this.sendEvent({ ...event, + eventType: _hammerjs.default.INPUT_MOVE, + isFinal: false, + isFirst: true + }); + this.isGestureRunning = false; + this.hasGestureFailed = false; + this.sendEvent({ ...event, + eventType: _hammerjs.default.INPUT_END, + isFinal: true + }); + } + + onRawEvent(ev) { + super.onRawEvent(ev); + + if (this.hasGestureFailed) { + return; + } // Hammer doesn't send a `cancel` event for taps. + // Manually fail the event. + + + if (ev.isFinal) { + setTimeout(() => { + if (this.isGestureRunning) { + this.cancelEvent(ev); + } + }); + } else if (!this.hasGestureFailed && !this.isGestureRunning) { + // Tap Gesture start event + const gesture = this.hammer.get(this.name); // @ts-ignore FIXME(TS) + + if (gesture.options.enable(gesture, ev)) { + this.onStart(ev); + this.sendEvent(ev); + } + } + } + + getHammerConfig() { + return { + // @ts-ignore FIXME(TS) + pointers: this.config.numberOfPointers, + direction: this.getDirection() + }; + } + + getTargetDirections(direction) { + const directions = []; + + if (direction & _constants.Direction.RIGHT) { + directions.push(_hammerjs.default.DIRECTION_RIGHT); + } + + if (direction & _constants.Direction.LEFT) { + directions.push(_hammerjs.default.DIRECTION_LEFT); + } + + if (direction & _constants.Direction.UP) { + directions.push(_hammerjs.default.DIRECTION_UP); + } + + if (direction & _constants.Direction.DOWN) { + directions.push(_hammerjs.default.DIRECTION_DOWN); + } // const hammerDirection = directions.reduce((a, b) => a | b, 0); + + + return directions; + } + + getDirection() { + // @ts-ignore FIXME(TS) + const { + direction + } = this.getConfig(); + let directions = []; + + if (direction & _constants.Direction.RIGHT) { + directions.push(_hammerjs.default.DIRECTION_HORIZONTAL); + } + + if (direction & _constants.Direction.LEFT) { + directions.push(_hammerjs.default.DIRECTION_HORIZONTAL); + } + + if (direction & _constants.Direction.UP) { + directions.push(_hammerjs.default.DIRECTION_VERTICAL); + } + + if (direction & _constants.Direction.DOWN) { + directions.push(_hammerjs.default.DIRECTION_VERTICAL); + } + + directions = [...new Set(directions)]; + if (directions.length === 0) return _hammerjs.default.DIRECTION_NONE; + if (directions.length === 1) return directions[0]; + return _hammerjs.default.DIRECTION_ALL; + } + + isGestureEnabledForEvent({ + numberOfPointers + }, _recognizer, { + maxPointers: pointerLength + }) { + const validPointerCount = pointerLength === numberOfPointers; + + if (!validPointerCount && this.isGestureRunning) { + return { + failed: true + }; + } + + return { + success: validPointerCount + }; + } + + updateGestureConfig({ + numberOfPointers = 1, + direction, + ...props + }) { + if ((0, _utils.isnan)(direction) || typeof direction !== 'number') { + throw new _Errors.GesturePropError('direction', direction, 'number'); + } + + return super.updateGestureConfig({ + numberOfPointers, + direction, + ...props + }); + } + +} + +var _default = FlingGestureHandler; +exports.default = _default; +//# sourceMappingURL=FlingGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/web/FlingGestureHandler.js.map b/lib/commonjs/web/FlingGestureHandler.js.map new file mode 100644 index 0000000000..226f11494c --- /dev/null +++ b/lib/commonjs/web/FlingGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["FlingGestureHandler.ts"],"names":["FlingGestureHandler","DraggingGestureHandler","name","NativeGestureClass","Hammer","Swipe","onGestureActivated","event","sendEvent","eventType","INPUT_MOVE","isFinal","isFirst","isGestureRunning","hasGestureFailed","INPUT_END","onRawEvent","ev","setTimeout","cancelEvent","gesture","hammer","get","options","enable","onStart","getHammerConfig","pointers","config","numberOfPointers","direction","getDirection","getTargetDirections","directions","Direction","RIGHT","push","DIRECTION_RIGHT","LEFT","DIRECTION_LEFT","UP","DIRECTION_UP","DOWN","DIRECTION_DOWN","getConfig","DIRECTION_HORIZONTAL","DIRECTION_VERTICAL","Set","length","DIRECTION_NONE","DIRECTION_ALL","isGestureEnabledForEvent","_recognizer","maxPointers","pointerLength","validPointerCount","failed","success","updateGestureConfig","props","GesturePropError"],"mappings":";;;;;;;AAEA;;AAEA;;AACA;;AACA;;AACA;;;;AAPA;;AACA;AASA,MAAMA,mBAAN,SAAkCC,+BAAlC,CAAyD;AAC/C,MAAJC,IAAI,GAAG;AACT,WAAO,OAAP;AACD;;AAEqB,MAAlBC,kBAAkB,GAAG;AACvB,WAAOC,kBAAOC,KAAd;AACD;;AAEDC,EAAAA,kBAAkB,CAACC,KAAD,EAAwB;AACxC,SAAKC,SAAL,CAAe,EACb,GAAGD,KADU;AAEbE,MAAAA,SAAS,EAAEL,kBAAOM,UAFL;AAGbC,MAAAA,OAAO,EAAE,KAHI;AAIbC,MAAAA,OAAO,EAAE;AAJI,KAAf;AAMA,SAAKC,gBAAL,GAAwB,KAAxB;AACA,SAAKC,gBAAL,GAAwB,KAAxB;AACA,SAAKN,SAAL,CAAe,EACb,GAAGD,KADU;AAEbE,MAAAA,SAAS,EAAEL,kBAAOW,SAFL;AAGbJ,MAAAA,OAAO,EAAE;AAHI,KAAf;AAKD;;AAEDK,EAAAA,UAAU,CAACC,EAAD,EAAqB;AAC7B,UAAMD,UAAN,CAAiBC,EAAjB;;AACA,QAAI,KAAKH,gBAAT,EAA2B;AACzB;AACD,KAJ4B,CAK7B;AACA;;;AACA,QAAIG,EAAE,CAACN,OAAP,EAAgB;AACdO,MAAAA,UAAU,CAAC,MAAM;AACf,YAAI,KAAKL,gBAAT,EAA2B;AACzB,eAAKM,WAAL,CAAiBF,EAAjB;AACD;AACF,OAJS,CAAV;AAKD,KAND,MAMO,IAAI,CAAC,KAAKH,gBAAN,IAA0B,CAAC,KAAKD,gB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AAqB,WAArB,EAAkC9B,SAAlC,EAA6C,QAA7C,CAAN;AACD;;AACD,WAAO,MAAM4B,mBAAN,CAA0B;AAC/B7B,MAAAA,gBAD+B;AAE/BC,MAAAA,SAF+B;AAG/B,SAAG6B;AAH4B,KAA1B,CAAP;AAKD;;AAxHsD;;eA2H1C3D,mB","sourcesContent":["/* eslint-disable eslint-comments/no-unlimited-disable */\n/* eslint-disable */\nimport Hammer from '@egjs/hammerjs';\n\nimport { Direction } from './constants';\nimport { GesturePropError } from './Errors';\nimport DraggingGestureHandler from './DraggingGestureHandler';\nimport { isnan } from './utils';\nimport { HammerInputExt } from './GestureHandler';\n\nclass FlingGestureHandler extends DraggingGestureHandler {\n get name() {\n return 'swipe';\n }\n\n get NativeGestureClass() {\n return Hammer.Swipe;\n }\n\n onGestureActivated(event: HammerInputExt) {\n this.sendEvent({\n ...event,\n eventType: Hammer.INPUT_MOVE,\n isFinal: false,\n isFirst: true,\n });\n this.isGestureRunning = false;\n this.hasGestureFailed = false;\n this.sendEvent({\n ...event,\n eventType: Hammer.INPUT_END,\n isFinal: true,\n });\n }\n\n onRawEvent(ev: HammerInputExt) {\n super.onRawEvent(ev);\n if (this.hasGestureFailed) {\n return;\n }\n // Hammer doesn't send a `cancel` event for taps.\n // Manually fail the event.\n if (ev.isFinal) {\n setTimeout(() => {\n if (this.isGestureRunning) {\n this.cancelEvent(ev);\n }\n });\n } else if (!this.hasGestureFailed && !this.isGestureRunning) {\n // Tap Gesture start event\n const gesture = this.hammer!.get(this.name);\n // @ts-ignore FIXME(TS)\n if (gesture.options.enable(gesture, ev)) {\n this.onStart(ev);\n this.sendEvent(ev);\n }\n }\n }\n\n getHammerConfig() {\n return {\n // @ts-ignore FIXME(TS)\n pointers: this.config.numberOfPointers,\n direction: this.getDirection(),\n };\n }\n\n getTargetDirections(direction: number) {\n const directions = [];\n if (direction & Direction.RIGHT) {\n directions.push(Hammer.DIRECTION_RIGHT);\n }\n if (direction & Direction.LEFT) {\n directions.push(Hammer.DIRECTION_LEFT);\n }\n if (direction & Direction.UP) {\n directions.push(Hammer.DIRECTION_UP);\n }\n if (direction & Direction.DOWN) {\n directions.push(Hammer.DIRECTION_DOWN);\n }\n // const hammerDirection = directions.reduce((a, b) => a | b, 0);\n return directions;\n }\n\n getDirection() {\n // @ts-ignore FIXME(TS)\n const { direction } = this.getConfig();\n\n let directions = [];\n if (direction & Direction.RIGHT) {\n directions.push(Hammer.DIRECTION_HORIZONTAL);\n }\n if (direction & Direction.LEFT) {\n directions.push(Hammer.DIRECTION_HORIZONTAL);\n }\n if (direction & Direction.UP) {\n directions.push(Hammer.DIRECTION_VERTICAL);\n }\n if (direction & Direction.DOWN) {\n directions.push(Hammer.DIRECTION_VERTICAL);\n }\n directions = [...new Set(directions)];\n\n if (directions.length === 0) return Hammer.DIRECTION_NONE;\n if (directions.length === 1) return directions[0];\n return Hammer.DIRECTION_ALL;\n }\n\n isGestureEnabledForEvent(\n { numberOfPointers }: any,\n _recognizer: any,\n { maxPointers: pointerLength }: any\n ) {\n const validPointerCount = pointerLength === numberOfPointers;\n if (!validPointerCount && this.isGestureRunning) {\n return { failed: true };\n }\n return { success: validPointerCount };\n }\n\n updateGestureConfig({ numberOfPointers = 1, direction, ...props }: any) {\n if (isnan(direction) || typeof direction !== 'number') {\n throw new GesturePropError('direction', direction, 'number');\n }\n return super.updateGestureConfig({\n numberOfPointers,\n direction,\n ...props,\n });\n }\n}\n\nexport default FlingGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/GestureHandler.js b/lib/commonjs/web/GestureHandler.js new file mode 100644 index 0000000000..88cf5228cc --- /dev/null +++ b/lib/commonjs/web/GestureHandler.js @@ -0,0 +1,533 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _hammerjs = _interopRequireDefault(require("@egjs/hammerjs")); + +var _reactNative = require("react-native"); + +var _State = require("../State"); + +var _constants = require("./constants"); + +var NodeManager = _interopRequireWildcard(require("./NodeManager")); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +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; } + +let gestureInstances = 0; + +class GestureHandler { + get id() { + return `${this.name}${this.gestureInstance}`; + } + + get isDiscrete() { + return false; + } + + get shouldEnableGestureOnSetup() { + throw new Error('Must override GestureHandler.shouldEnableGestureOnSetup'); + } + + constructor() { + _defineProperty(this, "handlerTag", void 0); + + _defineProperty(this, "isGestureRunning", false); + + _defineProperty(this, "view", null); + + _defineProperty(this, "hasCustomActivationCriteria", void 0); + + _defineProperty(this, "hasGestureFailed", false); + + _defineProperty(this, "hammer", null); + + _defineProperty(this, "initialRotation", null); + + _defineProperty(this, "__initialX", void 0); + + _defineProperty(this, "__initialY", void 0); + + _defineProperty(this, "config", {}); + + _defineProperty(this, "previousState", _State.State.UNDETERMINED); + + _defineProperty(this, "pendingGestures", {}); + + _defineProperty(this, "oldState", _State.State.UNDETERMINED); + + _defineProperty(this, "lastSentState", null); + + _defineProperty(this, "gestureInstance", void 0); + + _defineProperty(this, "_stillWaiting", void 0); + + _defineProperty(this, "propsRef", void 0); + + _defineProperty(this, "ref", void 0); + + _defineProperty(this, "clearSelfAsPending", () => { + if (Array.isArray(this.config.waitFor)) { + for (const gesture of this.config.waitFor) { + gesture.removePendingGesture(this.id); + } + } + }); + + _defineProperty(this, "destroy", () => { + this.clearSelfAsPending(); + + if (this.hammer) { + this.hammer.stop(false); + this.hammer.destroy(); + } + + this.hammer = null; + }); + + _defineProperty(this, "isPointInView", ({ + x, + y + }) => { + // @ts-ignore FIXME(TS) + const rect = this.view.getBoundingClientRect(); + const pointerInside = x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom; + return pointerInside; + }); + + _defineProperty(this, "sendEvent", nativeEvent => { + const { + onGestureHandlerEvent, + onGestureHandlerStateChange + } = this.propsRef.current; + const event = this.transformEventData(nativeEvent); + invokeNullableMethod(onGestureHandlerEvent, event); + + if (this.lastSentState !== event.nativeEvent.state) { + this.lastSentState = event.nativeEvent.state; + invokeNullableMethod(onGestureHandlerStateChange, event); + } + }); + + _defineProperty(this, "sync", () => { + const gesture = this.hammer.get(this.name); + if (!gesture) return; + + const enable = (recognizer, inputData) => { + if (!this.config.enabled) { + this.isGestureRunning = false; + this.hasGestureFailed = false; + return false; + } // Prevent events before the system is ready. + + + if (!inputData || !recognizer.options || typeof inputData.maxPointers === 'undefined') { + return this.shouldEnableGestureOnSetup; + } + + if (this.hasGestureFailed) { + return false; + } + + if (!this.isDiscrete) { + if (this.isGestureRunning) { + return true; + } // The built-in hammer.js "waitFor" doesn't work across multiple views. + // Only process if there are views to wait for. + + + this._stillWaiting = this._getPendingGestures(); // This gesture should continue waiting. + + if (this._stillWaiting.length) { + // Check to see if one of the gestures you're waiting for has started. + // If it has then the gesture should fail. + for (const gesture of this._stillWaiting) { + // When the target gesture has started, this gesture must force fail. + if (!gesture.isDiscrete && gesture.isGestureRunning) { + this.hasGestureFailed = true; + this.isGestureRunning = false; + return false; + } + } // This gesture shouldn't start until the others have finished. + + + return false; + } + } // Use default behaviour + + + if (!this.hasCustomActivationCriteria) { + return true; + } + + const deltaRotation = this.initialRotation == null ? 0 : inputData.rotation - this.initialRotation; // @ts-ignore FIXME(TS) + + const { + success, + failed + } = this.isGestureEnabledForEvent(this.getConfig(), recognizer, { ...inputData, + deltaRotation + }); + + if (failed) { + this.simulateCancelEvent(inputData); + this.hasGestureFailed = true; + } + + return success; + }; + + const params = this.getHammerConfig(); // @ts-ignore FIXME(TS) + + gesture.set({ ...params, + enable + }); + }); + + this.gestureInstance = gestureInstances++; + this.hasCustomActivationCriteria = false; + } + + getConfig() { + return this.config; + } + + onWaitingEnded(_gesture) {} + + removePendingGesture(id) { + delete this.pendingGestures[id]; + } + + addPendingGesture(gesture) { + this.pendingGestures[gesture.id] = gesture; + } + + isGestureEnabledForEvent(_config, _recognizer, _event) { + return { + success: true + }; + } + + get NativeGestureClass() { + throw new Error('Must override GestureHandler.NativeGestureClass'); + } + + updateHasCustomActivationCriteria(_config) { + return true; + } + + updateGestureConfig({ + enabled = true, + ...props + }) { + this.clearSelfAsPending(); + this.config = ensureConfig({ + enabled, + ...props + }); + this.hasCustomActivationCriteria = this.updateHasCustomActivationCriteria(this.config); + + if (Array.isArray(this.config.waitFor)) { + for (const gesture of this.config.waitFor) { + gesture.addPendingGesture(this); + } + } + + if (this.hammer) { + this.sync(); + } + + return this.config; + } + + getState(type) { + // @ts-ignore TODO(TS) check if this is needed + if (type == 0) { + return 0; + } + + return _constants.EventMap[type]; + } + + transformEventData(event) { + const { + eventType, + maxPointers: numberOfPointers + } = event; // const direction = DirectionMap[ev.direction]; + + const changedTouch = event.changedPointers[0]; + const pointerInside = this.isPointInView({ + x: changedTouch.clientX, + y: changedTouch.clientY + }); // TODO(TS) Remove cast after https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50966 is merged. + + const state = this.getState(eventType); + + if (state !== this.previousState) { + this.oldState = this.previousState; + this.previousState = state; + } + + return { + nativeEvent: { + numberOfPointers, + state, + pointerInside, + ...this.transformNativeEvent(event), + // onHandlerStateChange only + handlerTag: this.handlerTag, + target: this.ref, + oldState: this.oldState + }, + timeStamp: Date.now() + }; + } + + transformNativeEvent(_event) { + return {}; + } + + cancelPendingGestures(event) { + for (const gesture of Object.values(this.pendingGestures)) { + if (gesture && gesture.isGestureRunning) { + gesture.hasGestureFailed = true; + gesture.cancelEvent(event); + } + } + } + + notifyPendingGestures() { + for (const gesture of Object.values(this.pendingGestures)) { + if (gesture) { + gesture.onWaitingEnded(this); + } + } + } // FIXME event is undefined in runtime when firstly invoked (see Draggable example), check other functions taking event as input + + + onGestureEnded(event) { + this.isGestureRunning = false; + this.cancelPendingGestures(event); + } + + forceInvalidate(event) { + if (this.isGestureRunning) { + this.hasGestureFailed = true; + this.cancelEvent(event); + } + } + + cancelEvent(event) { + this.notifyPendingGestures(); + this.sendEvent({ ...event, + eventType: _hammerjs.default.INPUT_CANCEL, + isFinal: true + }); + this.onGestureEnded(event); + } + + onRawEvent({ + isFirst + }) { + if (isFirst) { + this.hasGestureFailed = false; + } + } + + setView(ref, propsRef) { + if (ref == null) { + this.destroy(); + this.view = null; + return; + } + + this.propsRef = propsRef; + this.ref = ref; + this.view = (0, _reactNative.findNodeHandle)(ref); + this.hammer = new _hammerjs.default.Manager(this.view); + this.oldState = _State.State.UNDETERMINED; + this.previousState = _State.State.UNDETERMINED; + this.lastSentState = null; + const { + NativeGestureClass + } = this; // @ts-ignore TODO(TS) + + const gesture = new NativeGestureClass(this.getHammerConfig()); + this.hammer.add(gesture); + this.hammer.on('hammer.input', ev => { + if (!this.config.enabled) { + this.hasGestureFailed = false; + this.isGestureRunning = false; + return; + } + + this.onRawEvent(ev); // TODO: Bacon: Check against something other than null + // The isFirst value is not called when the first rotation is calculated. + + if (this.initialRotation === null && ev.rotation !== 0) { + this.initialRotation = ev.rotation; + } + + if (ev.isFinal) { + // in favor of a willFail otherwise the last frame of the gesture will be captured. + setTimeout(() => { + this.initialRotation = null; + this.hasGestureFailed = false; + }); + } + }); + this.setupEvents(); + this.sync(); + } + + setupEvents() { + // TODO(TS) Hammer types aren't exactly that what we get in runtime + if (!this.isDiscrete) { + this.hammer.on(`${this.name}start`, event => this.onStart(event)); + this.hammer.on(`${this.name}end ${this.name}cancel`, event => { + this.onGestureEnded(event); + }); + } + + this.hammer.on(this.name, ev => this.onGestureActivated(ev)); // TODO(TS) remove cast after https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50438 is merged + } + + onStart({ + deltaX, + deltaY, + rotation + }) { + // Reset the state for the next gesture + this.oldState = _State.State.UNDETERMINED; + this.previousState = _State.State.UNDETERMINED; + this.lastSentState = null; + this.isGestureRunning = true; + this.__initialX = deltaX; + this.__initialY = deltaY; + this.initialRotation = rotation; + } + + onGestureActivated(ev) { + this.sendEvent(ev); + } + + onSuccess() {} + + _getPendingGestures() { + if (Array.isArray(this.config.waitFor) && this.config.waitFor.length) { + // Get the list of gestures that this gesture is still waiting for. + // Use `=== false` in case a ref that isn't a gesture handler is used. + const stillWaiting = this.config.waitFor.filter(({ + hasGestureFailed + }) => hasGestureFailed === false); + return stillWaiting; + } + + return []; + } + + getHammerConfig() { + const pointers = this.config.minPointers === this.config.maxPointers ? this.config.minPointers : 0; + return { + pointers + }; + } + + simulateCancelEvent(_inputData) {} + +} // TODO(TS) investigate this method +// Used for sending data to a callback or AnimatedEvent + + +function invokeNullableMethod(method, event) { + if (method) { + if (typeof method === 'function') { + method(event); + } else { + // For use with reanimated's AnimatedEvent + if ('__getHandler' in method && typeof method.__getHandler === 'function') { + const handler = method.__getHandler(); + + invokeNullableMethod(handler, event); + } else { + if ('__nodeConfig' in method) { + const { + argMapping + } = method.__nodeConfig; + + if (Array.isArray(argMapping)) { + for (const [index, [key, value]] of argMapping.entries()) { + if (key in event.nativeEvent) { + // @ts-ignore fix method type + const nativeValue = event.nativeEvent[key]; + + if (value && value.setValue) { + // Reanimated API + value.setValue(nativeValue); + } else { + // RN Animated API + method.__nodeConfig.argMapping[index] = [key, nativeValue]; + } + } + } + } + } + } + } + } +} // Validate the props + + +function ensureConfig(config) { + const props = { ...config + }; // TODO(TS) We use ! to assert that if property is present then value is not empty (null, undefined) + + if ('minDist' in config) { + props.minDist = config.minDist; + props.minDistSq = props.minDist * props.minDist; + } + + if ('minVelocity' in config) { + props.minVelocity = config.minVelocity; + props.minVelocitySq = props.minVelocity * props.minVelocity; + } + + if ('maxDist' in config) { + props.maxDist = config.maxDist; + props.maxDistSq = config.maxDist * config.maxDist; + } + + if ('waitFor' in config) { + props.waitFor = asArray(config.waitFor).map(({ + handlerTag + }) => NodeManager.getHandler(handlerTag)).filter(v => v); + } else { + props.waitFor = null; + } + + const configProps = ['minPointers', 'maxPointers', 'minDist', 'maxDist', 'maxDistSq', 'minVelocitySq', 'minDistSq', 'minVelocity', 'failOffsetXStart', 'failOffsetYStart', 'failOffsetXEnd', 'failOffsetYEnd', 'activeOffsetXStart', 'activeOffsetXEnd', 'activeOffsetYStart', 'activeOffsetYEnd']; + configProps.forEach(prop => { + if (typeof props[prop] === 'undefined') { + props[prop] = Number.NaN; + } + }); + return props; // TODO(TS) how to convince TS that props are filled? +} + +function asArray(value) { + // TODO(TS) use config.waitFor type + return value == null ? [] : Array.isArray(value) ? value : [value]; +} + +var _default = GestureHandler; +exports.default = _default; +//# sourceMappingURL=GestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/web/GestureHandler.js.map b/lib/commonjs/web/GestureHandler.js.map new file mode 100644 index 0000000000..07c80e18dc --- /dev/null +++ b/lib/commonjs/web/GestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureHandler.ts"],"names":["gestureInstances","GestureHandler","id","name","gestureInstance","isDiscrete","shouldEnableGestureOnSetup","Error","constructor","State","UNDETERMINED","Array","isArray","config","waitFor","gesture","removePendingGesture","clearSelfAsPending","hammer","stop","destroy","x","y","rect","view","getBoundingClientRect","pointerInside","left","right","top","bottom","nativeEvent","onGestureHandlerEvent","onGestureHandlerStateChange","propsRef","current","event","transformEventData","invokeNullableMethod","lastSentState","state","get","enable","recognizer","inputData","enabled","isGestureRunning","hasGestureFailed","options","maxPointers","_stillWaiting","_getPendingGestures","length","hasCustomActivationCriteria","deltaRotation","initialRotation","rotation","success","failed","isGestureEnabledForEvent","getConfig","simulateCancelEvent","params","getHammerConfig","set","onWaitingEnded","_gesture","pendingGestures","addPendingGesture","_config","_recognizer","_event","NativeGestureClass","updateHasCustomActivationCriteria","updateGestureConfig","props","ensureConfig","sync","getState","type","EventMap","eventType","numberOfPointers","changedTouch","changedPointers","isPointInView","clientX","clientY","previousState","oldState","transformNativeEvent","handlerTag","target","ref","timeStamp","Date","now","cancelPendingGestures","Object","values","cancelEvent","notifyPendingGestures","onGestureEnded","forceInvalidate","sendEvent","Hammer","INPUT_CANCEL","isFinal","onRawEvent","isFirst","setView","Manager","add","on","ev","setTimeout","setupEvents","onStart","onGestureActivated","deltaX","deltaY","__initialX","__initialY","onSuccess","stillWaiting","filter","pointers","minPointers","_inputData","method","__getHandler","handler","argMapping","__nodeConfig","index","key","value","entries","nativeValue","setValue","minDist","minDistSq","minVelocity","minVelocitySq","maxDist","maxDistSq","asArray","map","NodeManager","getHandler","v","configProps","forEach","prop","Number","NaN"],"mappings":";;;;;;;AAEA;;AACA;;AAEA;;AACA;;AACA;;;;;;;;;;AA4BA,IAAIA,gBAAgB,GAAG,CAAvB;;AAEA,MAAeC,cAAf,CAA8B;AAsBtB,MAAFC,EAAE,GAAG;AACP,WAAQ,GAAE,KAAKC,IAAK,GAAE,KAAKC,eAAgB,EAA3C;AACD;;AAEa,MAAVC,UAAU,GAAG;AACf,WAAO,KAAP;AACD;;AAE6B,MAA1BC,0BAA0B,GAAY;AACxC,UAAM,IAAIC,KAAJ,CAAU,yDAAV,CAAN;AACD;;AAEDC,EAAAA,WAAW,GAAG;AAAA;;AAAA,8CAhCY,KAgCZ;;AAAA,kCA/Be,IA+Bf;;AAAA;;AAAA,8CA7Be,KA6Bf;;AAAA,oCA5B2B,IA4B3B;;AAAA,6CA3B6B,IA2B7B;;AAAA;;AAAA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AASuE,OAAT,CAAoBV,KAApB,EAAoC;AAClC;AACA,SAAOA,KAAK,IAAI,IAAT,GAAgB,EAAhB,GAAqB7H,KAAK,CAACC,OAAN,CAAc4H,KAAd,IAAuBA,KAAvB,GAA+B,CAACA,KAAD,CAA3D;AACD;;eAEcvI,c","sourcesContent":["/* eslint-disable eslint-comments/no-unlimited-disable */\n/* eslint-disable */\nimport Hammer from '@egjs/hammerjs';\nimport { findNodeHandle } from 'react-native';\n\nimport { State } from '../State';\nimport { EventMap } from './constants';\nimport * as NodeManager from './NodeManager';\n\n// TODO(TS) Replace with HammerInput if https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50438/files is merged\nexport type HammerInputExt = Omit;\n\nexport type Config = Partial<{\n enabled: boolean;\n minPointers: number;\n maxPointers: number;\n minDist: number;\n minDistSq: number;\n minVelocity: number;\n minVelocitySq: number;\n maxDist: number;\n maxDistSq: number;\n failOffsetXStart: number;\n failOffsetYStart: number;\n failOffsetXEnd: number;\n failOffsetYEnd: number;\n activeOffsetXStart: number;\n activeOffsetXEnd: number;\n activeOffsetYStart: number;\n activeOffsetYEnd: number;\n waitFor: any[] | null;\n}>;\n\ntype NativeEvent = ReturnType;\n\nlet gestureInstances = 0;\n\nabstract class GestureHandler {\n public handlerTag: any;\n public isGestureRunning = false;\n public view: number | null = null;\n protected hasCustomActivationCriteria: boolean;\n protected hasGestureFailed = false;\n protected hammer: HammerManager | null = null;\n protected initialRotation: number | null = null;\n protected __initialX: any;\n protected __initialY: any;\n protected config: Config = {};\n protected previousState: State = State.UNDETERMINED;\n private pendingGestures: Record = {};\n private oldState: State = State.UNDETERMINED;\n private lastSentState: State | null = null;\n private gestureInstance: number;\n private _stillWaiting: any;\n private propsRef: any;\n private ref: any;\n\n abstract get name(): string;\n\n get id() {\n return `${this.name}${this.gestureInstance}`;\n }\n\n get isDiscrete() {\n return false;\n }\n\n get shouldEnableGestureOnSetup(): boolean {\n throw new Error('Must override GestureHandler.shouldEnableGestureOnSetup');\n }\n\n constructor() {\n this.gestureInstance = gestureInstances++;\n this.hasCustomActivationCriteria = false;\n }\n\n getConfig() {\n return this.config;\n }\n\n onWaitingEnded(_gesture: this) {}\n\n removePendingGesture(id: string) {\n delete this.pendingGestures[id];\n }\n\n addPendingGesture(gesture: this) {\n this.pendingGestures[gesture.id] = gesture;\n }\n\n isGestureEnabledForEvent(\n _config: any,\n _recognizer: any,\n _event: any\n ): { failed?: boolean; success?: boolean } {\n return { success: true };\n }\n\n get NativeGestureClass(): RecognizerStatic {\n throw new Error('Must override GestureHandler.NativeGestureClass');\n }\n\n updateHasCustomActivationCriteria(_config: Config) {\n return true;\n }\n\n clearSelfAsPending = () => {\n if (Array.isArray(this.config.waitFor)) {\n for (const gesture of this.config.waitFor) {\n gesture.removePendingGesture(this.id);\n }\n }\n };\n\n updateGestureConfig({ enabled = true, ...props }) {\n this.clearSelfAsPending();\n\n this.config = ensureConfig({ enabled, ...props });\n this.hasCustomActivationCriteria = this.updateHasCustomActivationCriteria(\n this.config\n );\n if (Array.isArray(this.config.waitFor)) {\n for (const gesture of this.config.waitFor) {\n gesture.addPendingGesture(this);\n }\n }\n\n if (this.hammer) {\n this.sync();\n }\n return this.config;\n }\n\n destroy = () => {\n this.clearSelfAsPending();\n\n if (this.hammer) {\n this.hammer.stop(false);\n this.hammer.destroy();\n }\n this.hammer = null;\n };\n\n isPointInView = ({ x, y }: { x: number; y: number }) => {\n // @ts-ignore FIXME(TS)\n const rect = this.view!.getBoundingClientRect();\n const pointerInside =\n x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;\n return pointerInside;\n };\n\n getState(type: keyof typeof EventMap): State {\n // @ts-ignore TODO(TS) check if this is needed\n if (type == 0) {\n return 0;\n }\n return EventMap[type];\n }\n\n transformEventData(event: HammerInputExt) {\n const { eventType, maxPointers: numberOfPointers } = event;\n // const direction = DirectionMap[ev.direction];\n const changedTouch = event.changedPointers[0];\n const pointerInside = this.isPointInView({\n x: changedTouch.clientX,\n y: changedTouch.clientY,\n });\n\n // TODO(TS) Remove cast after https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50966 is merged.\n const state = this.getState(eventType as 1 | 2 | 4 | 8);\n if (state !== this.previousState) {\n this.oldState = this.previousState;\n this.previousState = state;\n }\n\n return {\n nativeEvent: {\n numberOfPointers,\n state,\n pointerInside,\n ...this.transformNativeEvent(event),\n // onHandlerStateChange only\n handlerTag: this.handlerTag,\n target: this.ref,\n oldState: this.oldState,\n },\n timeStamp: Date.now(),\n };\n }\n\n transformNativeEvent(_event: HammerInputExt) {\n return {};\n }\n\n sendEvent = (nativeEvent: HammerInputExt) => {\n const {\n onGestureHandlerEvent,\n onGestureHandlerStateChange,\n } = this.propsRef.current;\n\n const event = this.transformEventData(nativeEvent);\n\n invokeNullableMethod(onGestureHandlerEvent, event);\n if (this.lastSentState !== event.nativeEvent.state) {\n this.lastSentState = event.nativeEvent.state as State;\n invokeNullableMethod(onGestureHandlerStateChange, event);\n }\n };\n\n cancelPendingGestures(event: HammerInputExt) {\n for (const gesture of Object.values(this.pendingGestures)) {\n if (gesture && gesture.isGestureRunning) {\n gesture.hasGestureFailed = true;\n gesture.cancelEvent(event);\n }\n }\n }\n\n notifyPendingGestures() {\n for (const gesture of Object.values(this.pendingGestures)) {\n if (gesture) {\n gesture.onWaitingEnded(this);\n }\n }\n }\n\n // FIXME event is undefined in runtime when firstly invoked (see Draggable example), check other functions taking event as input\n onGestureEnded(event: HammerInputExt) {\n this.isGestureRunning = false;\n this.cancelPendingGestures(event);\n }\n\n forceInvalidate(event: HammerInputExt) {\n if (this.isGestureRunning) {\n this.hasGestureFailed = true;\n this.cancelEvent(event);\n }\n }\n\n cancelEvent(event: HammerInputExt) {\n this.notifyPendingGestures();\n this.sendEvent({\n ...event,\n eventType: Hammer.INPUT_CANCEL,\n isFinal: true,\n });\n this.onGestureEnded(event);\n }\n\n onRawEvent({ isFirst }: HammerInputExt) {\n if (isFirst) {\n this.hasGestureFailed = false;\n }\n }\n\n setView(ref: Parameters['0'], propsRef: any) {\n if (ref == null) {\n this.destroy();\n this.view = null;\n return;\n }\n\n this.propsRef = propsRef;\n this.ref = ref;\n\n this.view = findNodeHandle(ref);\n this.hammer = new Hammer.Manager(this.view as any);\n\n this.oldState = State.UNDETERMINED;\n this.previousState = State.UNDETERMINED;\n this.lastSentState = null;\n\n const { NativeGestureClass } = this;\n // @ts-ignore TODO(TS)\n const gesture = new NativeGestureClass(this.getHammerConfig());\n this.hammer.add(gesture);\n\n this.hammer.on('hammer.input', (ev: HammerInput) => {\n if (!this.config.enabled) {\n this.hasGestureFailed = false;\n this.isGestureRunning = false;\n return;\n }\n\n this.onRawEvent((ev as unknown) as HammerInputExt);\n\n // TODO: Bacon: Check against something other than null\n // The isFirst value is not called when the first rotation is calculated.\n if (this.initialRotation === null && ev.rotation !== 0) {\n this.initialRotation = ev.rotation;\n }\n if (ev.isFinal) {\n // in favor of a willFail otherwise the last frame of the gesture will be captured.\n setTimeout(() => {\n this.initialRotation = null;\n this.hasGestureFailed = false;\n });\n }\n });\n\n this.setupEvents();\n this.sync();\n }\n\n setupEvents() {\n // TODO(TS) Hammer types aren't exactly that what we get in runtime\n if (!this.isDiscrete) {\n this.hammer!.on(`${this.name}start`, (event: HammerInput) =>\n this.onStart((event as unknown) as HammerInputExt)\n );\n this.hammer!.on(\n `${this.name}end ${this.name}cancel`,\n (event: HammerInput) => {\n this.onGestureEnded((event as unknown) as HammerInputExt);\n }\n );\n }\n this.hammer!.on(this.name, (ev: HammerInput) =>\n this.onGestureActivated((ev as unknown) as HammerInputExt)\n ); // TODO(TS) remove cast after https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50438 is merged\n }\n\n onStart({ deltaX, deltaY, rotation }: HammerInputExt) {\n // Reset the state for the next gesture\n this.oldState = State.UNDETERMINED;\n this.previousState = State.UNDETERMINED;\n this.lastSentState = null;\n\n this.isGestureRunning = true;\n this.__initialX = deltaX;\n this.__initialY = deltaY;\n this.initialRotation = rotation;\n }\n\n onGestureActivated(ev: HammerInputExt) {\n this.sendEvent(ev);\n }\n\n onSuccess() {}\n\n _getPendingGestures() {\n if (Array.isArray(this.config.waitFor) && this.config.waitFor.length) {\n // Get the list of gestures that this gesture is still waiting for.\n // Use `=== false` in case a ref that isn't a gesture handler is used.\n const stillWaiting = this.config.waitFor.filter(\n ({ hasGestureFailed }) => hasGestureFailed === false\n );\n return stillWaiting;\n }\n return [];\n }\n\n getHammerConfig() {\n const pointers =\n this.config.minPointers === this.config.maxPointers\n ? this.config.minPointers\n : 0;\n return {\n pointers,\n };\n }\n\n sync = () => {\n const gesture = this.hammer!.get(this.name);\n if (!gesture) return;\n\n const enable = (recognizer: any, inputData: any) => {\n if (!this.config.enabled) {\n this.isGestureRunning = false;\n this.hasGestureFailed = false;\n return false;\n }\n\n // Prevent events before the system is ready.\n if (\n !inputData ||\n !recognizer.options ||\n typeof inputData.maxPointers === 'undefined'\n ) {\n return this.shouldEnableGestureOnSetup;\n }\n\n if (this.hasGestureFailed) {\n return false;\n }\n\n if (!this.isDiscrete) {\n if (this.isGestureRunning) {\n return true;\n }\n // The built-in hammer.js \"waitFor\" doesn't work across multiple views.\n // Only process if there are views to wait for.\n this._stillWaiting = this._getPendingGestures();\n // This gesture should continue waiting.\n if (this._stillWaiting.length) {\n // Check to see if one of the gestures you're waiting for has started.\n // If it has then the gesture should fail.\n for (const gesture of this._stillWaiting) {\n // When the target gesture has started, this gesture must force fail.\n if (!gesture.isDiscrete && gesture.isGestureRunning) {\n this.hasGestureFailed = true;\n this.isGestureRunning = false;\n return false;\n }\n }\n // This gesture shouldn't start until the others have finished.\n return false;\n }\n }\n\n // Use default behaviour\n if (!this.hasCustomActivationCriteria) {\n return true;\n }\n\n const deltaRotation =\n this.initialRotation == null\n ? 0\n : inputData.rotation - this.initialRotation;\n // @ts-ignore FIXME(TS)\n const { success, failed } = this.isGestureEnabledForEvent(\n this.getConfig(),\n recognizer,\n {\n ...inputData,\n deltaRotation,\n }\n );\n\n if (failed) {\n this.simulateCancelEvent(inputData);\n this.hasGestureFailed = true;\n }\n return success;\n };\n\n const params = this.getHammerConfig();\n // @ts-ignore FIXME(TS)\n gesture.set({ ...params, enable });\n };\n\n simulateCancelEvent(_inputData: any) {}\n}\n\n// TODO(TS) investigate this method\n// Used for sending data to a callback or AnimatedEvent\nfunction invokeNullableMethod(\n method:\n | ((event: NativeEvent) => void)\n | { __getHandler: () => (event: NativeEvent) => void }\n | { __nodeConfig: { argMapping: any } },\n event: NativeEvent\n) {\n if (method) {\n if (typeof method === 'function') {\n method(event);\n } else {\n // For use with reanimated's AnimatedEvent\n if (\n '__getHandler' in method &&\n typeof method.__getHandler === 'function'\n ) {\n const handler = method.__getHandler();\n invokeNullableMethod(handler, event);\n } else {\n if ('__nodeConfig' in method) {\n const { argMapping } = method.__nodeConfig;\n if (Array.isArray(argMapping)) {\n for (const [index, [key, value]] of argMapping.entries()) {\n if (key in event.nativeEvent) {\n // @ts-ignore fix method type\n const nativeValue = event.nativeEvent[key];\n if (value && value.setValue) {\n // Reanimated API\n value.setValue(nativeValue);\n } else {\n // RN Animated API\n method.__nodeConfig.argMapping[index] = [key, nativeValue];\n }\n }\n }\n }\n }\n }\n }\n }\n}\n\n// Validate the props\nfunction ensureConfig(config: Config): Required {\n const props = { ...config };\n\n // TODO(TS) We use ! to assert that if property is present then value is not empty (null, undefined)\n if ('minDist' in config) {\n props.minDist = config.minDist;\n props.minDistSq = props.minDist! * props.minDist!;\n }\n if ('minVelocity' in config) {\n props.minVelocity = config.minVelocity;\n props.minVelocitySq = props.minVelocity! * props.minVelocity!;\n }\n if ('maxDist' in config) {\n props.maxDist = config.maxDist;\n props.maxDistSq = config.maxDist! * config.maxDist!;\n }\n if ('waitFor' in config) {\n props.waitFor = asArray(config.waitFor)\n .map(({ handlerTag }: { handlerTag: number }) =>\n NodeManager.getHandler(handlerTag)\n )\n .filter((v) => v);\n } else {\n props.waitFor = null;\n }\n\n const configProps = [\n 'minPointers',\n 'maxPointers',\n 'minDist',\n 'maxDist',\n 'maxDistSq',\n 'minVelocitySq',\n 'minDistSq',\n 'minVelocity',\n 'failOffsetXStart',\n 'failOffsetYStart',\n 'failOffsetXEnd',\n 'failOffsetYEnd',\n 'activeOffsetXStart',\n 'activeOffsetXEnd',\n 'activeOffsetYStart',\n 'activeOffsetYEnd',\n ] as const;\n configProps.forEach((prop: typeof configProps[number]) => {\n if (typeof props[prop] === 'undefined') {\n props[prop] = Number.NaN;\n }\n });\n return props as Required; // TODO(TS) how to convince TS that props are filled?\n}\n\nfunction asArray(value: T | T[]) {\n // TODO(TS) use config.waitFor type\n return value == null ? [] : Array.isArray(value) ? value : [value];\n}\n\nexport default GestureHandler;\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/IndiscreteGestureHandler.js b/lib/commonjs/web/IndiscreteGestureHandler.js new file mode 100644 index 0000000000..af2ea46cd0 --- /dev/null +++ b/lib/commonjs/web/IndiscreteGestureHandler.js @@ -0,0 +1,54 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _GestureHandler = _interopRequireDefault(require("./GestureHandler")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * The base class for **Rotation** and **Pinch** gesture handlers. + */ +class IndiscreteGestureHandler extends _GestureHandler.default { + get shouldEnableGestureOnSetup() { + return false; + } + + updateGestureConfig({ + minPointers = 2, + maxPointers = 2, + ...props + }) { + return super.updateGestureConfig({ + minPointers, + maxPointers, + ...props + }); + } + + isGestureEnabledForEvent({ + minPointers, + maxPointers + }, _recognizer, { + maxPointers: pointerLength + }) { + if (pointerLength > maxPointers) { + return { + failed: true + }; + } + + const validPointerCount = pointerLength >= minPointers; + return { + success: validPointerCount + }; + } + +} + +var _default = IndiscreteGestureHandler; +exports.default = _default; +//# sourceMappingURL=IndiscreteGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/web/IndiscreteGestureHandler.js.map b/lib/commonjs/web/IndiscreteGestureHandler.js.map new file mode 100644 index 0000000000..e2d9306c95 --- /dev/null +++ b/lib/commonjs/web/IndiscreteGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["IndiscreteGestureHandler.ts"],"names":["IndiscreteGestureHandler","GestureHandler","shouldEnableGestureOnSetup","updateGestureConfig","minPointers","maxPointers","props","isGestureEnabledForEvent","_recognizer","pointerLength","failed","validPointerCount","success"],"mappings":";;;;;;;AAAA;;;;AAEA;AACA;AACA;AACA,MAAeA,wBAAf,SAAgDC,uBAAhD,CAA+D;AAC/B,MAA1BC,0BAA0B,GAAG;AAC/B,WAAO,KAAP;AACD;;AAEDC,EAAAA,mBAAmB,CAAC;AAAEC,IAAAA,WAAW,GAAG,CAAhB;AAAmBC,IAAAA,WAAW,GAAG,CAAjC;AAAoC,OAAGC;AAAvC,GAAD,EAAiD;AAClE,WAAO,MAAMH,mBAAN,CAA0B;AAC/BC,MAAAA,WAD+B;AAE/BC,MAAAA,WAF+B;AAG/B,SAAGC;AAH4B,KAA1B,CAAP;AAKD;;AAEDC,EAAAA,wBAAwB,CACtB;AAAEH,IAAAA,WAAF;AAAeC,IAAAA;AAAf,GADsB,EAEtBG,WAFsB,EAGtB;AAAEH,IAAAA,WAAW,EAAEI;AAAf,GAHsB,EAItB;AACA,QAAIA,aAAa,GAAGJ,WAApB,EAAiC;AAC/B,aAAO;AAAEK,QAAAA,MAAM,EAAE;AAAV,OAAP;AACD;;AACD,UAAMC,iBAAiB,GAAGF,aAAa,IAAIL,WAA3C;AACA,WAAO;AACLQ,MAAAA,OAAO,EAAED;AADJ,KAAP;AAGD;;AAzB4D;;eA2BhDX,wB","sourcesContent":["import GestureHandler from './GestureHandler';\n\n/**\n * The base class for **Rotation** and **Pinch** gesture handlers.\n */\nabstract class IndiscreteGestureHandler extends GestureHandler {\n get shouldEnableGestureOnSetup() {\n return false;\n }\n\n updateGestureConfig({ minPointers = 2, maxPointers = 2, ...props }) {\n return super.updateGestureConfig({\n minPointers,\n maxPointers,\n ...props,\n });\n }\n\n isGestureEnabledForEvent(\n { minPointers, maxPointers }: any,\n _recognizer: any,\n { maxPointers: pointerLength }: any\n ) {\n if (pointerLength > maxPointers) {\n return { failed: true };\n }\n const validPointerCount = pointerLength >= minPointers;\n return {\n success: validPointerCount,\n };\n }\n}\nexport default IndiscreteGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/LongPressGestureHandler.js b/lib/commonjs/web/LongPressGestureHandler.js new file mode 100644 index 0000000000..4b4db63b41 --- /dev/null +++ b/lib/commonjs/web/LongPressGestureHandler.js @@ -0,0 +1,71 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _hammerjs = _interopRequireDefault(require("@egjs/hammerjs")); + +var _State = require("../State"); + +var _PressGestureHandler = _interopRequireDefault(require("./PressGestureHandler")); + +var _utils = require("./utils"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint-disable eslint-comments/no-unlimited-disable */ + +/* eslint-disable */ +class LongPressGestureHandler extends _PressGestureHandler.default { + get minDurationMs() { + // @ts-ignore FIXNE(TS) + return (0, _utils.isnan)(this.config.minDurationMs) ? 251 : this.config.minDurationMs; + } + + get maxDist() { + // @ts-ignore FIXNE(TS) + return (0, _utils.isnan)(this.config.maxDist) ? 9 : this.config.maxDist; + } + + updateHasCustomActivationCriteria({ + maxDistSq + }) { + return !(0, _utils.isValidNumber)(maxDistSq); + } + + getConfig() { + if (!this.hasCustomActivationCriteria) { + // Default config + // If no params have been defined then this config should emulate the native gesture as closely as possible. + return { + shouldCancelWhenOutside: true, + maxDistSq: 10 + }; + } + + return this.config; + } + + getHammerConfig() { + return { ...super.getHammerConfig(), + // threshold: this.maxDist, + time: this.minDurationMs + }; + } + + getState(type) { + return { + [_hammerjs.default.INPUT_START]: _State.State.ACTIVE, + [_hammerjs.default.INPUT_MOVE]: _State.State.ACTIVE, + [_hammerjs.default.INPUT_END]: _State.State.END, + [_hammerjs.default.INPUT_CANCEL]: _State.State.FAILED + }[type]; + } + +} + +var _default = LongPressGestureHandler; +exports.default = _default; +//# sourceMappingURL=LongPressGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/web/LongPressGestureHandler.js.map b/lib/commonjs/web/LongPressGestureHandler.js.map new file mode 100644 index 0000000000..193998a796 --- /dev/null +++ b/lib/commonjs/web/LongPressGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["LongPressGestureHandler.ts"],"names":["LongPressGestureHandler","PressGestureHandler","minDurationMs","config","maxDist","updateHasCustomActivationCriteria","maxDistSq","getConfig","hasCustomActivationCriteria","shouldCancelWhenOutside","getHammerConfig","time","getState","type","Hammer","INPUT_START","State","ACTIVE","INPUT_MOVE","INPUT_END","END","INPUT_CANCEL","FAILED"],"mappings":";;;;;;;AAEA;;AAEA;;AACA;;AACA;;;;AANA;;AACA;AASA,MAAMA,uBAAN,SAAsCC,4BAAtC,CAA0D;AACvC,MAAbC,aAAa,GAAW;AAC1B;AACA,WAAO,kBAAM,KAAKC,MAAL,CAAYD,aAAlB,IAAmC,GAAnC,GAAyC,KAAKC,MAAL,CAAYD,aAA5D;AACD;;AAEU,MAAPE,OAAO,GAAG;AACZ;AACA,WAAO,kBAAM,KAAKD,MAAL,CAAYC,OAAlB,IAA6B,CAA7B,GAAiC,KAAKD,MAAL,CAAYC,OAApD;AACD;;AAEDC,EAAAA,iCAAiC,CAAC;AAAEC,IAAAA;AAAF,GAAD,EAAwB;AACvD,WAAO,CAAC,0BAAcA,SAAd,CAAR;AACD;;AAEDC,EAAAA,SAAS,GAAG;AACV,QAAI,CAAC,KAAKC,2BAAV,EAAuC;AACrC;AACA;AACA,aAAO;AACLC,QAAAA,uBAAuB,EAAE,IADpB;AAELH,QAAAA,SAAS,EAAE;AAFN,OAAP;AAID;;AACD,WAAO,KAAKH,MAAZ;AACD;;AAEDO,EAAAA,eAAe,GAAG;AAChB,WAAO,EACL,GAAG,MAAMA,eAAN,EADE;AAEL;AACAC,MAAAA,IAAI,EAAE,KAAKT;AAHN,KAAP;AAKD;;AAEDU,EAAAA,QAAQ,CAACC,IAAD,EAAsC;AAC5C,WAAO;AACL,OAACC,kBAAOC,WAAR,GAAsBC,aAAMC,MADvB;AAEL,OAACH,kBAAOI,UAAR,GAAqBF,aAAMC,MAFtB;AAGL,OAACH,kBAAOK,SAAR,GAAoBH,aAAMI,GAHrB;AAIL,OAACN,kBAAOO,YAAR,GAAuBL,aAAMM;AAJxB,MAKLT,IALK,CAAP;AAMD;;AA1CuD;;eA6C3Cb,uB","sourcesContent":["/* eslint-disable eslint-comments/no-unlimited-disable */\n/* eslint-disable */\nimport Hammer from '@egjs/hammerjs';\n\nimport { State } from '../State';\nimport PressGestureHandler from './PressGestureHandler';\nimport { isnan, isValidNumber } from './utils';\nimport { Config } from './GestureHandler';\nimport { HammerInputNames } from './constants';\n\nclass LongPressGestureHandler extends PressGestureHandler {\n get minDurationMs(): number {\n // @ts-ignore FIXNE(TS)\n return isnan(this.config.minDurationMs) ? 251 : this.config.minDurationMs;\n }\n\n get maxDist() {\n // @ts-ignore FIXNE(TS)\n return isnan(this.config.maxDist) ? 9 : this.config.maxDist;\n }\n\n updateHasCustomActivationCriteria({ maxDistSq }: Config) {\n return !isValidNumber(maxDistSq);\n }\n\n getConfig() {\n if (!this.hasCustomActivationCriteria) {\n // Default config\n // If no params have been defined then this config should emulate the native gesture as closely as possible.\n return {\n shouldCancelWhenOutside: true,\n maxDistSq: 10,\n };\n }\n return this.config;\n }\n\n getHammerConfig() {\n return {\n ...super.getHammerConfig(),\n // threshold: this.maxDist,\n time: this.minDurationMs,\n };\n }\n\n getState(type: keyof typeof HammerInputNames) {\n return {\n [Hammer.INPUT_START]: State.ACTIVE,\n [Hammer.INPUT_MOVE]: State.ACTIVE,\n [Hammer.INPUT_END]: State.END,\n [Hammer.INPUT_CANCEL]: State.FAILED,\n }[type];\n }\n}\n\nexport default LongPressGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/NativeViewGestureHandler.js b/lib/commonjs/web/NativeViewGestureHandler.js new file mode 100644 index 0000000000..0bc023bfce --- /dev/null +++ b/lib/commonjs/web/NativeViewGestureHandler.js @@ -0,0 +1,62 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _DiscreteGestureHandler = _interopRequireDefault(require("./DiscreteGestureHandler")); + +var NodeManager = _interopRequireWildcard(require("./NodeManager")); + +var _PressGestureHandler = _interopRequireDefault(require("./PressGestureHandler")); + +var _utils = require("./utils"); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +class NativeViewGestureHandler extends _PressGestureHandler.default { + onRawEvent(ev) { + super.onRawEvent(ev); + + if (!ev.isFinal) { + // if (this.ref instanceof ScrollView) { + if ((0, _utils.TEST_MIN_IF_NOT_NAN)((0, _utils.VEC_LEN_SQ)({ + x: ev.deltaX, + y: ev.deltaY + }), 10)) { + // @ts-ignore FIXME(TS) config type + if (this.config.disallowInterruption) { + const gestures = Object.values(NodeManager.getNodes()).filter(gesture => { + const { + handlerTag, + view, + isGestureRunning + } = gesture; + return (// Check if this gesture isn't self + handlerTag !== this.handlerTag && // Ensure the gesture needs to be cancelled + isGestureRunning && // ScrollView can cancel discrete gestures like taps and presses + gesture instanceof _DiscreteGestureHandler.default && // Ensure a view exists and is a child of the current view + view && // @ts-ignore FIXME(TS) view type + this.view.contains(view) + ); + }); // Cancel all of the gestures that passed the filter + + for (const gesture of gestures) { + // TODO: Bacon: Send some cached event. + gesture.forceInvalidate(ev); + } + } + } + } + } + +} + +var _default = NativeViewGestureHandler; +exports.default = _default; +//# sourceMappingURL=NativeViewGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/web/NativeViewGestureHandler.js.map b/lib/commonjs/web/NativeViewGestureHandler.js.map new file mode 100644 index 0000000000..7d3db538b0 --- /dev/null +++ b/lib/commonjs/web/NativeViewGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["NativeViewGestureHandler.ts"],"names":["NativeViewGestureHandler","PressGestureHandler","onRawEvent","ev","isFinal","x","deltaX","y","deltaY","config","disallowInterruption","gestures","Object","values","NodeManager","getNodes","filter","gesture","handlerTag","view","isGestureRunning","DiscreteGestureHandler","contains","forceInvalidate"],"mappings":";;;;;;;AAAA;;AAEA;;AACA;;AACA;;;;;;;;AAEA,MAAMA,wBAAN,SAAuCC,4BAAvC,CAA2D;AACzDC,EAAAA,UAAU,CAACC,EAAD,EAAqB;AAC7B,UAAMD,UAAN,CAAiBC,EAAjB;;AACA,QAAI,CAACA,EAAE,CAACC,OAAR,EAAiB;AACf;AACA,UAAI,gCAAoB,uBAAW;AAAEC,QAAAA,CAAC,EAAEF,EAAE,CAACG,MAAR;AAAgBC,QAAAA,CAAC,EAAEJ,EAAE,CAACK;AAAtB,OAAX,CAApB,EAAgE,EAAhE,CAAJ,EAAyE;AACvE;AACA,YAAI,KAAKC,MAAL,CAAYC,oBAAhB,EAAsC;AACpC,gBAAMC,QAAQ,GAAGC,MAAM,CAACC,MAAP,CAAcC,WAAW,CAACC,QAAZ,EAAd,EAAsCC,MAAtC,CACdC,OAAD,IAAa;AACX,kBAAM;AAAEC,cAAAA,UAAF;AAAcC,cAAAA,IAAd;AAAoBC,cAAAA;AAApB,gBAAyCH,OAA/C;AACA,mBACE;AACAC,cAAAA,UAAU,KAAK,KAAKA,UAApB,IACA;AACAE,cAAAA,gBAFA,IAGA;AACAH,cAAAA,OAAO,YAAYI,+BAJnB,IAKA;AACAF,cAAAA,IANA,IAOA;AACA,mBAAKA,IAAL,CAAUG,QAAV,CAAmBH,IAAnB;AAVF;AAYD,WAfc,CAAjB,CADoC,CAkBpC;;AACA,eAAK,MAAMF,OAAX,IAAsBN,QAAtB,EAAgC;AAC9B;AACAM,YAAAA,OAAO,CAACM,eAAR,CAAwBpB,EAAxB;AACD;AACF;AACF;AACF;AACF;;AAjCwD;;eAoC5CH,wB","sourcesContent":["import DiscreteGestureHandler from './DiscreteGestureHandler';\nimport { HammerInputExt } from './GestureHandler';\nimport * as NodeManager from './NodeManager';\nimport PressGestureHandler from './PressGestureHandler';\nimport { TEST_MIN_IF_NOT_NAN, VEC_LEN_SQ } from './utils';\n\nclass NativeViewGestureHandler extends PressGestureHandler {\n onRawEvent(ev: HammerInputExt) {\n super.onRawEvent(ev);\n if (!ev.isFinal) {\n // if (this.ref instanceof ScrollView) {\n if (TEST_MIN_IF_NOT_NAN(VEC_LEN_SQ({ x: ev.deltaX, y: ev.deltaY }), 10)) {\n // @ts-ignore FIXME(TS) config type\n if (this.config.disallowInterruption) {\n const gestures = Object.values(NodeManager.getNodes()).filter(\n (gesture) => {\n const { handlerTag, view, isGestureRunning } = gesture;\n return (\n // Check if this gesture isn't self\n handlerTag !== this.handlerTag &&\n // Ensure the gesture needs to be cancelled\n isGestureRunning &&\n // ScrollView can cancel discrete gestures like taps and presses\n gesture instanceof DiscreteGestureHandler &&\n // Ensure a view exists and is a child of the current view\n view &&\n // @ts-ignore FIXME(TS) view type\n this.view.contains(view)\n );\n }\n );\n // Cancel all of the gestures that passed the filter\n for (const gesture of gestures) {\n // TODO: Bacon: Send some cached event.\n gesture.forceInvalidate(ev);\n }\n }\n }\n }\n }\n}\n\nexport default NativeViewGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/NodeManager.js b/lib/commonjs/web/NodeManager.js new file mode 100644 index 0000000000..546931e08a --- /dev/null +++ b/lib/commonjs/web/NodeManager.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getHandler = getHandler; +exports.createGestureHandler = createGestureHandler; +exports.dropGestureHandler = dropGestureHandler; +exports.getNodes = getNodes; +const gestures = {}; + +function getHandler(tag) { + if (tag in gestures) return gestures[tag]; + throw new Error(`No handler for tag ${tag}`); +} + +function createGestureHandler(handlerTag, handler) { + if (handlerTag in gestures) { + throw new Error(`Handler with tag ${handlerTag} already exists`); + } + + gestures[handlerTag] = handler; // @ts-ignore no types for web handlers yet + + gestures[handlerTag].handlerTag = handlerTag; +} + +function dropGestureHandler(handlerTag) { + // Since React 18, there are cases where componentWillUnmount gets called twice in a row + // so skip this if the tag was already removed. + if (!(handlerTag in gestures)) { + return; + } + + getHandler(handlerTag).destroy(); // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + + delete gestures[handlerTag]; +} + +function getNodes() { + return { ...gestures + }; +} +//# sourceMappingURL=NodeManager.js.map \ No newline at end of file diff --git a/lib/commonjs/web/NodeManager.js.map b/lib/commonjs/web/NodeManager.js.map new file mode 100644 index 0000000000..aa1e8ab0ba --- /dev/null +++ b/lib/commonjs/web/NodeManager.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["NodeManager.ts"],"names":["gestures","getHandler","tag","Error","createGestureHandler","handlerTag","handler","dropGestureHandler","destroy","getNodes"],"mappings":";;;;;;;;;AAGA,MAAMA,QAAgE,GAAG,EAAzE;;AAEO,SAASC,UAAT,CAAoBC,GAApB,EAAiC;AACtC,MAAIA,GAAG,IAAIF,QAAX,EAAqB,OAAOA,QAAQ,CAACE,GAAD,CAAf;AAErB,QAAM,IAAIC,KAAJ,CAAW,sBAAqBD,GAAI,EAApC,CAAN;AACD;;AAEM,SAASE,oBAAT,CACLC,UADK,EAELC,OAFK,EAGL;AACA,MAAID,UAAU,IAAIL,QAAlB,EAA4B;AAC1B,UAAM,IAAIG,KAAJ,CAAW,oBAAmBE,UAAW,iBAAzC,CAAN;AACD;;AACDL,EAAAA,QAAQ,CAACK,UAAD,CAAR,GAAuBC,OAAvB,CAJA,CAKA;;AACAN,EAAAA,QAAQ,CAACK,UAAD,CAAR,CAAqBA,UAArB,GAAkCA,UAAlC;AACD;;AAEM,SAASE,kBAAT,CAA4BF,UAA5B,EAAgD;AACrD;AACA;AACA,MAAI,EAAEA,UAAU,IAAIL,QAAhB,CAAJ,EAA+B;AAC7B;AACD;;AACDC,EAAAA,UAAU,CAACI,UAAD,CAAV,CAAuBG,OAAvB,GANqD,CAOrD;;AACA,SAAOR,QAAQ,CAACK,UAAD,CAAf;AACD;;AAEM,SAASI,QAAT,GAAoB;AACzB,SAAO,EAAE,GAAGT;AAAL,GAAP;AACD","sourcesContent":["import { ValueOf } from '../typeUtils';\nimport { Gestures } from '../RNGestureHandlerModule.web';\n\nconst gestures: Record>> = {};\n\nexport function getHandler(tag: number) {\n if (tag in gestures) return gestures[tag];\n\n throw new Error(`No handler for tag ${tag}`);\n}\n\nexport function createGestureHandler(\n handlerTag: number,\n handler: InstanceType>\n) {\n if (handlerTag in gestures) {\n throw new Error(`Handler with tag ${handlerTag} already exists`);\n }\n gestures[handlerTag] = handler;\n // @ts-ignore no types for web handlers yet\n gestures[handlerTag].handlerTag = handlerTag;\n}\n\nexport function dropGestureHandler(handlerTag: number) {\n // Since React 18, there are cases where componentWillUnmount gets called twice in a row\n // so skip this if the tag was already removed.\n if (!(handlerTag in gestures)) {\n return;\n }\n getHandler(handlerTag).destroy();\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete gestures[handlerTag];\n}\n\nexport function getNodes() {\n return { ...gestures };\n}\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/PanGestureHandler.js b/lib/commonjs/web/PanGestureHandler.js new file mode 100644 index 0000000000..7d2f9291cc --- /dev/null +++ b/lib/commonjs/web/PanGestureHandler.js @@ -0,0 +1,189 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _hammerjs = _interopRequireDefault(require("@egjs/hammerjs")); + +var _constants = require("./constants"); + +var _DraggingGestureHandler = _interopRequireDefault(require("./DraggingGestureHandler")); + +var _utils = require("./utils"); + +var _State = require("../State"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +class PanGestureHandler extends _DraggingGestureHandler.default { + get name() { + return 'pan'; + } + + get NativeGestureClass() { + return _hammerjs.default.Pan; + } + + getHammerConfig() { + return { ...super.getHammerConfig(), + direction: this.getDirection() + }; + } + + getState(type) { + const nextState = super.getState(type); // Ensure that the first state sent is `BEGAN` and not `ACTIVE` + + if (this.previousState === _State.State.UNDETERMINED && nextState === _State.State.ACTIVE) { + return _State.State.BEGAN; + } + + return nextState; + } + + getDirection() { + const config = this.getConfig(); + const { + activeOffsetXStart, + activeOffsetXEnd, + activeOffsetYStart, + activeOffsetYEnd, + minDist + } = config; + let directions = []; + let horizontalDirections = []; + + if (!(0, _utils.isnan)(minDist)) { + return _hammerjs.default.DIRECTION_ALL; + } + + if (!(0, _utils.isnan)(activeOffsetXStart)) horizontalDirections.push(_hammerjs.default.DIRECTION_LEFT); + if (!(0, _utils.isnan)(activeOffsetXEnd)) horizontalDirections.push(_hammerjs.default.DIRECTION_RIGHT); + if (horizontalDirections.length === 2) horizontalDirections = [_hammerjs.default.DIRECTION_HORIZONTAL]; + directions = directions.concat(horizontalDirections); + let verticalDirections = []; + if (!(0, _utils.isnan)(activeOffsetYStart)) verticalDirections.push(_hammerjs.default.DIRECTION_UP); + if (!(0, _utils.isnan)(activeOffsetYEnd)) verticalDirections.push(_hammerjs.default.DIRECTION_DOWN); + if (verticalDirections.length === 2) verticalDirections = [_hammerjs.default.DIRECTION_VERTICAL]; + directions = directions.concat(verticalDirections); + + if (!directions.length) { + return _hammerjs.default.DIRECTION_NONE; + } + + if (directions[0] === _hammerjs.default.DIRECTION_HORIZONTAL && directions[1] === _hammerjs.default.DIRECTION_VERTICAL) { + return _hammerjs.default.DIRECTION_ALL; + } + + if (horizontalDirections.length && verticalDirections.length) { + return _hammerjs.default.DIRECTION_ALL; + } + + return directions[0]; + } + + getConfig() { + if (!this.hasCustomActivationCriteria) { + // Default config + // If no params have been defined then this config should emulate the native gesture as closely as possible. + return { + minDistSq: 10 + }; + } + + return this.config; + } + + shouldFailUnderCustomCriteria({ + deltaX, + deltaY + }, criteria) { + return !(0, _utils.isnan)(criteria.failOffsetXStart) && deltaX < criteria.failOffsetXStart || !(0, _utils.isnan)(criteria.failOffsetXEnd) && deltaX > criteria.failOffsetXEnd || !(0, _utils.isnan)(criteria.failOffsetYStart) && deltaY < criteria.failOffsetYStart || !(0, _utils.isnan)(criteria.failOffsetYEnd) && deltaY > criteria.failOffsetYEnd; + } + + shouldActivateUnderCustomCriteria({ + deltaX, + deltaY, + velocity + }, criteria) { + return !(0, _utils.isnan)(criteria.activeOffsetXStart) && deltaX < criteria.activeOffsetXStart || !(0, _utils.isnan)(criteria.activeOffsetXEnd) && deltaX > criteria.activeOffsetXEnd || !(0, _utils.isnan)(criteria.activeOffsetYStart) && deltaY < criteria.activeOffsetYStart || !(0, _utils.isnan)(criteria.activeOffsetYEnd) && deltaY > criteria.activeOffsetYEnd || (0, _utils.TEST_MIN_IF_NOT_NAN)((0, _utils.VEC_LEN_SQ)({ + x: deltaX, + y: deltaY + }), criteria.minDistSq) || (0, _utils.TEST_MIN_IF_NOT_NAN)(velocity.x, criteria.minVelocityX) || (0, _utils.TEST_MIN_IF_NOT_NAN)(velocity.y, criteria.minVelocityY) || (0, _utils.TEST_MIN_IF_NOT_NAN)((0, _utils.VEC_LEN_SQ)(velocity), criteria.minVelocitySq); + } + + shouldMultiFingerPanFail({ + pointerLength, + scale, + deltaRotation + }) { + if (pointerLength <= 1) { + return false; + } // Test if the pan had too much pinching or rotating. + + + const deltaScale = Math.abs(scale - 1); + const absDeltaRotation = Math.abs(deltaRotation); + + if (deltaScale > _constants.MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD) { + // > If the threshold doesn't seem right. + // You can log the value which it failed at here: + return true; + } + + if (absDeltaRotation > _constants.MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD) { + // > If the threshold doesn't seem right. + // You can log the value which it failed at here: + return true; + } + + return false; + } + + updateHasCustomActivationCriteria(criteria) { + return (0, _utils.isValidNumber)(criteria.minDistSq) || (0, _utils.isValidNumber)(criteria.minVelocityX) || (0, _utils.isValidNumber)(criteria.minVelocityY) || (0, _utils.isValidNumber)(criteria.minVelocitySq) || (0, _utils.isValidNumber)(criteria.activeOffsetXStart) || (0, _utils.isValidNumber)(criteria.activeOffsetXEnd) || (0, _utils.isValidNumber)(criteria.activeOffsetYStart) || (0, _utils.isValidNumber)(criteria.activeOffsetYEnd); + } + + isGestureEnabledForEvent(props, _recognizer, inputData) { + if (this.shouldFailUnderCustomCriteria(inputData, props)) { + return { + failed: true + }; + } + + const velocity = { + x: inputData.velocityX, + y: inputData.velocityY + }; + + if (this.hasCustomActivationCriteria && this.shouldActivateUnderCustomCriteria({ + deltaX: inputData.deltaX, + deltaY: inputData.deltaY, + velocity + }, props)) { + if (this.shouldMultiFingerPanFail({ + pointerLength: inputData.maxPointers, + scale: inputData.scale, + deltaRotation: inputData.deltaRotation + })) { + return { + failed: true + }; + } + + return { + success: true + }; + } + + return { + success: false + }; + } + +} + +var _default = PanGestureHandler; +exports.default = _default; +//# sourceMappingURL=PanGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/web/PanGestureHandler.js.map b/lib/commonjs/web/PanGestureHandler.js.map new file mode 100644 index 0000000000..2c21a8c3c7 --- /dev/null +++ b/lib/commonjs/web/PanGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PanGestureHandler.ts"],"names":["PanGestureHandler","DraggingGestureHandler","name","NativeGestureClass","Hammer","Pan","getHammerConfig","direction","getDirection","getState","type","nextState","previousState","State","UNDETERMINED","ACTIVE","BEGAN","config","getConfig","activeOffsetXStart","activeOffsetXEnd","activeOffsetYStart","activeOffsetYEnd","minDist","directions","horizontalDirections","DIRECTION_ALL","push","DIRECTION_LEFT","DIRECTION_RIGHT","length","DIRECTION_HORIZONTAL","concat","verticalDirections","DIRECTION_UP","DIRECTION_DOWN","DIRECTION_VERTICAL","DIRECTION_NONE","hasCustomActivationCriteria","minDistSq","shouldFailUnderCustomCriteria","deltaX","deltaY","criteria","failOffsetXStart","failOffsetXEnd","failOffsetYStart","failOffsetYEnd","shouldActivateUnderCustomCriteria","velocity","x","y","minVelocityX","minVelocityY","minVelocitySq","shouldMultiFingerPanFail","pointerLength","scale","deltaRotation","deltaScale","Math","abs","absDeltaRotation","MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD","MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD","updateHasCustomActivationCriteria","isGestureEnabledForEvent","props","_recognizer","inputData","failed","velocityX","velocityY","maxPointers","success"],"mappings":";;;;;;;AAAA;;AAEA;;AAKA;;AACA;;AACA;;;;AAGA,MAAMA,iBAAN,SAAgCC,+BAAhC,CAAuD;AAC7C,MAAJC,IAAI,GAAG;AACT,WAAO,KAAP;AACD;;AAEqB,MAAlBC,kBAAkB,GAAG;AACvB,WAAOC,kBAAOC,GAAd;AACD;;AAEDC,EAAAA,eAAe,GAAG;AAChB,WAAO,EACL,GAAG,MAAMA,eAAN,EADE;AAELC,MAAAA,SAAS,EAAE,KAAKC,YAAL;AAFN,KAAP;AAID;;AAEDC,EAAAA,QAAQ,CAACC,IAAD,EAA8B;AACpC,UAAMC,SAAS,GAAG,MAAMF,QAAN,CAAeC,IAAf,CAAlB,CADoC,CAEpC;;AACA,QACE,KAAKE,aAAL,KAAuBC,aAAMC,YAA7B,IACAH,SAAS,KAAKE,aAAME,MAFtB,EAGE;AACA,aAAOF,aAAMG,KAAb;AACD;;AACD,WA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cX,QAAQ,CAACxB,kBAAvB,CAJA,IAKA,0BAAcwB,QAAQ,CAACvB,gBAAvB,CALA,IAMA,0BAAcuB,QAAQ,CAACtB,kBAAvB,CANA,IAOA,0BAAcsB,QAAQ,CAACrB,gBAAvB,CARF;AAUD;;AAED4C,EAAAA,wBAAwB,CACtBC,KADsB,EAEtBC,WAFsB,EAGtBC,SAHsB,EAItB;AACA,QAAI,KAAK7B,6BAAL,CAAmC6B,SAAnC,EAA8CF,KAA9C,CAAJ,EAA0D;AACxD,aAAO;AAAEG,QAAAA,MAAM,EAAE;AAAV,OAAP;AACD;;AAED,UAAMrB,QAAQ,GAAG;AAAEC,MAAAA,CAAC,EAAEmB,SAAS,CAACE,SAAf;AAA0BpB,MAAAA,CAAC,EAAEkB,SAAS,CAACG;AAAvC,KAAjB;;AACA,QACE,KAAKlC,2BAAL,IACA,KAAKU,iCAAL,CACE;AAAEP,MAAAA,MAAM,EAAE4B,SAAS,CAAC5B,MAApB;AAA4BC,MAAAA,MAAM,EAAE2B,SAAS,CAAC3B,MAA9C;AAAsDO,MAAAA;AAAtD,KADF,EAEEkB,KAFF,CAFF,EAME;AACA,UACE,KAAKZ,wBAAL,CAA8B;AAC5BC,QAAAA,aAAa,EAAEa,SAAS,CAACI,WADG;AAE5BhB,QAAAA,KAAK,EAAEY,SAAS,CAACZ,KAFW;AAG5BC,QAAAA,aAAa,EAAEW,SAAS,CAACX;AAHG,OAA9B,CADF,EAME;AACA,eAAO;AACLY,UAAAA,MAAM,EAAE;AADH,SAAP;AAGD;;AACD,aAAO;AAAEI,QAAAA,OAAO,EAAE;AAAX,OAAP;AACD;;AACD,WAAO;AAAEA,MAAAA,OAAO,EAAE;AAAX,KAAP;AACD;;AA5MoD;;eA+MxC1E,iB","sourcesContent":["import Hammer from '@egjs/hammerjs';\n\nimport {\n EventMap,\n MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD,\n MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD,\n} from './constants';\nimport DraggingGestureHandler from './DraggingGestureHandler';\nimport { isValidNumber, isnan, TEST_MIN_IF_NOT_NAN, VEC_LEN_SQ } from './utils';\nimport { State } from '../State';\n\nimport { Config, HammerInputExt } from './GestureHandler';\nclass PanGestureHandler extends DraggingGestureHandler {\n get name() {\n return 'pan';\n }\n\n get NativeGestureClass() {\n return Hammer.Pan;\n }\n\n getHammerConfig() {\n return {\n ...super.getHammerConfig(),\n direction: this.getDirection(),\n };\n }\n\n getState(type: keyof typeof EventMap) {\n const nextState = super.getState(type);\n // Ensure that the first state sent is `BEGAN` and not `ACTIVE`\n if (\n this.previousState === State.UNDETERMINED &&\n nextState === State.ACTIVE\n ) {\n return State.BEGAN;\n }\n return nextState;\n }\n\n getDirection() {\n const config = this.getConfig();\n const {\n activeOffsetXStart,\n activeOffsetXEnd,\n activeOffsetYStart,\n activeOffsetYEnd,\n minDist,\n } = config;\n let directions: number[] = [];\n let horizontalDirections = [];\n\n if (!isnan(minDist)) {\n return Hammer.DIRECTION_ALL;\n }\n\n if (!isnan(activeOffsetXStart))\n horizontalDirections.push(Hammer.DIRECTION_LEFT);\n if (!isnan(activeOffsetXEnd))\n horizontalDirections.push(Hammer.DIRECTION_RIGHT);\n if (horizontalDirections.length === 2)\n horizontalDirections = [Hammer.DIRECTION_HORIZONTAL];\n\n directions = directions.concat(horizontalDirections);\n let verticalDirections = [];\n\n if (!isnan(activeOffsetYStart))\n verticalDirections.push(Hammer.DIRECTION_UP);\n if (!isnan(activeOffsetYEnd))\n verticalDirections.push(Hammer.DIRECTION_DOWN);\n\n if (verticalDirections.length === 2)\n verticalDirections = [Hammer.DIRECTION_VERTICAL];\n\n directions = directions.concat(verticalDirections);\n\n if (!directions.length) {\n return Hammer.DIRECTION_NONE;\n }\n if (\n directions[0] === Hammer.DIRECTION_HORIZONTAL &&\n directions[1] === Hammer.DIRECTION_VERTICAL\n ) {\n return Hammer.DIRECTION_ALL;\n }\n if (horizontalDirections.length && verticalDirections.length) {\n return Hammer.DIRECTION_ALL;\n }\n\n return directions[0];\n }\n\n getConfig() {\n if (!this.hasCustomActivationCriteria) {\n // Default config\n // If no params have been defined then this config should emulate the native gesture as closely as possible.\n return {\n minDistSq: 10,\n };\n }\n return this.config;\n }\n\n shouldFailUnderCustomCriteria(\n { deltaX, deltaY }: HammerInputExt,\n criteria: any\n ) {\n return (\n (!isnan(criteria.failOffsetXStart) &&\n deltaX < criteria.failOffsetXStart) ||\n (!isnan(criteria.failOffsetXEnd) && deltaX > criteria.failOffsetXEnd) ||\n (!isnan(criteria.failOffsetYStart) &&\n deltaY < criteria.failOffsetYStart) ||\n (!isnan(criteria.failOffsetYEnd) && deltaY > criteria.failOffsetYEnd)\n );\n }\n\n shouldActivateUnderCustomCriteria(\n { deltaX, deltaY, velocity }: any,\n criteria: any\n ) {\n return (\n (!isnan(criteria.activeOffsetXStart) &&\n deltaX < criteria.activeOffsetXStart) ||\n (!isnan(criteria.activeOffsetXEnd) &&\n deltaX > criteria.activeOffsetXEnd) ||\n (!isnan(criteria.activeOffsetYStart) &&\n deltaY < criteria.activeOffsetYStart) ||\n (!isnan(criteria.activeOffsetYEnd) &&\n deltaY > criteria.activeOffsetYEnd) ||\n TEST_MIN_IF_NOT_NAN(\n VEC_LEN_SQ({ x: deltaX, y: deltaY }),\n criteria.minDistSq\n ) ||\n TEST_MIN_IF_NOT_NAN(velocity.x, criteria.minVelocityX) ||\n TEST_MIN_IF_NOT_NAN(velocity.y, criteria.minVelocityY) ||\n TEST_MIN_IF_NOT_NAN(VEC_LEN_SQ(velocity), criteria.minVelocitySq)\n );\n }\n\n shouldMultiFingerPanFail({\n pointerLength,\n scale,\n deltaRotation,\n }: {\n deltaRotation: number;\n pointerLength: number;\n scale: number;\n }) {\n if (pointerLength <= 1) {\n return false;\n }\n\n // Test if the pan had too much pinching or rotating.\n const deltaScale = Math.abs(scale - 1);\n const absDeltaRotation = Math.abs(deltaRotation);\n if (deltaScale > MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD) {\n // > If the threshold doesn't seem right.\n // You can log the value which it failed at here:\n return true;\n }\n if (absDeltaRotation > MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD) {\n // > If the threshold doesn't seem right.\n // You can log the value which it failed at here:\n return true;\n }\n\n return false;\n }\n\n updateHasCustomActivationCriteria(\n criteria: Config & { minVelocityX?: number; minVelocityY?: number }\n ) {\n return (\n isValidNumber(criteria.minDistSq) ||\n isValidNumber(criteria.minVelocityX) ||\n isValidNumber(criteria.minVelocityY) ||\n isValidNumber(criteria.minVelocitySq) ||\n isValidNumber(criteria.activeOffsetXStart) ||\n isValidNumber(criteria.activeOffsetXEnd) ||\n isValidNumber(criteria.activeOffsetYStart) ||\n isValidNumber(criteria.activeOffsetYEnd)\n );\n }\n\n isGestureEnabledForEvent(\n props: any,\n _recognizer: any,\n inputData: HammerInputExt & { deltaRotation: number }\n ) {\n if (this.shouldFailUnderCustomCriteria(inputData, props)) {\n return { failed: true };\n }\n\n const velocity = { x: inputData.velocityX, y: inputData.velocityY };\n if (\n this.hasCustomActivationCriteria &&\n this.shouldActivateUnderCustomCriteria(\n { deltaX: inputData.deltaX, deltaY: inputData.deltaY, velocity },\n props\n )\n ) {\n if (\n this.shouldMultiFingerPanFail({\n pointerLength: inputData.maxPointers,\n scale: inputData.scale,\n deltaRotation: inputData.deltaRotation,\n })\n ) {\n return {\n failed: true,\n };\n }\n return { success: true };\n }\n return { success: false };\n }\n}\n\nexport default PanGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/PinchGestureHandler.js b/lib/commonjs/web/PinchGestureHandler.js new file mode 100644 index 0000000000..915f9bd35d --- /dev/null +++ b/lib/commonjs/web/PinchGestureHandler.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _hammerjs = _interopRequireDefault(require("@egjs/hammerjs")); + +var _IndiscreteGestureHandler = _interopRequireDefault(require("./IndiscreteGestureHandler")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +class PinchGestureHandler extends _IndiscreteGestureHandler.default { + get name() { + return 'pinch'; + } + + get NativeGestureClass() { + return _hammerjs.default.Pinch; + } + + transformNativeEvent({ + scale, + velocity, + center + }) { + return { + focalX: center.x, + focalY: center.y, + velocity, + scale + }; + } + +} + +var _default = PinchGestureHandler; +exports.default = _default; +//# sourceMappingURL=PinchGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/web/PinchGestureHandler.js.map b/lib/commonjs/web/PinchGestureHandler.js.map new file mode 100644 index 0000000000..d4e5c35097 --- /dev/null +++ b/lib/commonjs/web/PinchGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PinchGestureHandler.ts"],"names":["PinchGestureHandler","IndiscreteGestureHandler","name","NativeGestureClass","Hammer","Pinch","transformNativeEvent","scale","velocity","center","focalX","x","focalY","y"],"mappings":";;;;;;;AAAA;;AAGA;;;;AAEA,MAAMA,mBAAN,SAAkCC,iCAAlC,CAA2D;AACjD,MAAJC,IAAI,GAAG;AACT,WAAO,OAAP;AACD;;AAEqB,MAAlBC,kBAAkB,GAAG;AACvB,WAAOC,kBAAOC,KAAd;AACD;;AAEDC,EAAAA,oBAAoB,CAAC;AAAEC,IAAAA,KAAF;AAASC,IAAAA,QAAT;AAAmBC,IAAAA;AAAnB,GAAD,EAA8C;AAChE,WAAO;AACLC,MAAAA,MAAM,EAAED,MAAM,CAACE,CADV;AAELC,MAAAA,MAAM,EAAEH,MAAM,CAACI,CAFV;AAGLL,MAAAA,QAHK;AAILD,MAAAA;AAJK,KAAP;AAMD;;AAhBwD;;eAmB5CP,mB","sourcesContent":["import Hammer from '@egjs/hammerjs';\nimport { HammerInputExt } from './GestureHandler';\n\nimport IndiscreteGestureHandler from './IndiscreteGestureHandler';\n\nclass PinchGestureHandler extends IndiscreteGestureHandler {\n get name() {\n return 'pinch';\n }\n\n get NativeGestureClass() {\n return Hammer.Pinch;\n }\n\n transformNativeEvent({ scale, velocity, center }: HammerInputExt) {\n return {\n focalX: center.x,\n focalY: center.y,\n velocity,\n scale,\n };\n }\n}\n\nexport default PinchGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/PressGestureHandler.js b/lib/commonjs/web/PressGestureHandler.js new file mode 100644 index 0000000000..28a10074b7 --- /dev/null +++ b/lib/commonjs/web/PressGestureHandler.js @@ -0,0 +1,188 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _hammerjs = _interopRequireDefault(require("@egjs/hammerjs")); + +var _State = require("../State"); + +var _constants = require("./constants"); + +var _DiscreteGestureHandler = _interopRequireDefault(require("./DiscreteGestureHandler")); + +var _utils = require("./utils"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +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; } + +class PressGestureHandler extends _DiscreteGestureHandler.default { + constructor(...args) { + super(...args); + + _defineProperty(this, "visualFeedbackTimer", void 0); + + _defineProperty(this, "initialEvent", null); + + _defineProperty(this, "shouldDelayTouches", true); + } + + get name() { + return 'press'; + } + + get minDurationMs() { + // @ts-ignore FIXME(TS) + return (0, _utils.isnan)(this.config.minDurationMs) ? 5 : this.config.minDurationMs; + } + + get maxDist() { + return (0, _utils.isnan)(this.config.maxDist) ? 9 : this.config.maxDist; + } + + get NativeGestureClass() { + return _hammerjs.default.Press; + } + + simulateCancelEvent(inputData) { + // Long press never starts so we can't rely on the running event boolean. + this.hasGestureFailed = true; + this.cancelEvent(inputData); + } + + updateHasCustomActivationCriteria({ + shouldCancelWhenOutside, + maxDistSq + }) { + return shouldCancelWhenOutside || !(0, _utils.isValidNumber)(maxDistSq); + } + + getState(type) { + return { + [_hammerjs.default.INPUT_START]: _State.State.BEGAN, + [_hammerjs.default.INPUT_MOVE]: _State.State.ACTIVE, + [_hammerjs.default.INPUT_END]: _State.State.END, + [_hammerjs.default.INPUT_CANCEL]: _State.State.CANCELLED + }[type]; + } + + getConfig() { + if (!this.hasCustomActivationCriteria) { + // Default config + // If no params have been defined then this config should emulate the native gesture as closely as possible. + return { + shouldCancelWhenOutside: true, + maxDistSq: 10 + }; + } + + return this.config; + } + + getHammerConfig() { + return { ...super.getHammerConfig(), + // threshold: this.maxDist, + time: this.minDurationMs + }; + } + + onGestureActivated(ev) { + this.onGestureStart(ev); + } + + shouldDelayTouchForEvent({ + pointerType + }) { + // Don't disable event for mouse input + return this.shouldDelayTouches && pointerType === 'touch'; + } + + onGestureStart(ev) { + this.isGestureRunning = true; + clearTimeout(this.visualFeedbackTimer); + this.initialEvent = ev; + this.visualFeedbackTimer = (0, _utils.fireAfterInterval)(() => { + this.sendGestureStartedEvent(this.initialEvent); + this.initialEvent = null; + }, this.shouldDelayTouchForEvent(ev) && _constants.CONTENT_TOUCHES_DELAY); + } + + sendGestureStartedEvent(ev) { + clearTimeout(this.visualFeedbackTimer); + this.visualFeedbackTimer = null; + this.sendEvent({ ...ev, + eventType: _hammerjs.default.INPUT_MOVE, + isFirst: true + }); + } + + forceInvalidate(event) { + super.forceInvalidate(event); + clearTimeout(this.visualFeedbackTimer); + this.visualFeedbackTimer = null; + this.initialEvent = null; + } + + onRawEvent(ev) { + super.onRawEvent(ev); + + if (this.isGestureRunning) { + if (ev.isFinal) { + let timeout; + + if (this.visualFeedbackTimer) { + // Aesthetic timing for a quick tap. + // We haven't activated the tap right away to emulate iOS `delaysContentTouches` + // Now we must send the initial activation event and wait a set amount of time before firing the end event. + timeout = _constants.CONTENT_TOUCHES_QUICK_TAP_END_DELAY; + this.sendGestureStartedEvent(this.initialEvent); + this.initialEvent = null; + } + + (0, _utils.fireAfterInterval)(() => { + this.sendEvent({ ...ev, + eventType: _hammerjs.default.INPUT_END, + isFinal: true + }); // @ts-ignore -- this should explicitly support undefined + + this.onGestureEnded(); + }, timeout); + } else { + this.sendEvent({ ...ev, + eventType: _hammerjs.default.INPUT_MOVE, + isFinal: false + }); + } + } + } + + updateGestureConfig({ + shouldActivateOnStart = false, + disallowInterruption = false, + shouldCancelWhenOutside = true, + minDurationMs = Number.NaN, + maxDist = Number.NaN, + minPointers = 1, + maxPointers = 1, + ...props + }) { + return super.updateGestureConfig({ + shouldActivateOnStart, + disallowInterruption, + shouldCancelWhenOutside, + minDurationMs, + maxDist, + minPointers, + maxPointers, + ...props + }); + } + +} + +var _default = PressGestureHandler; +exports.default = _default; +//# sourceMappingURL=PressGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/web/PressGestureHandler.js.map b/lib/commonjs/web/PressGestureHandler.js.map new file mode 100644 index 0000000000..0ff9f87b2e --- /dev/null +++ b/lib/commonjs/web/PressGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PressGestureHandler.ts"],"names":["PressGestureHandler","DiscreteGestureHandler","name","minDurationMs","config","maxDist","NativeGestureClass","Hammer","Press","simulateCancelEvent","inputData","hasGestureFailed","cancelEvent","updateHasCustomActivationCriteria","shouldCancelWhenOutside","maxDistSq","getState","type","INPUT_START","State","BEGAN","INPUT_MOVE","ACTIVE","INPUT_END","END","INPUT_CANCEL","CANCELLED","getConfig","hasCustomActivationCriteria","getHammerConfig","time","onGestureActivated","ev","onGestureStart","shouldDelayTouchForEvent","pointerType","shouldDelayTouches","isGestureRunning","clearTimeout","visualFeedbackTimer","initialEvent","sendGestureStartedEvent","CONTENT_TOUCHES_DELAY","sendEvent","eventType","isFirst","forceInvalidate","event","onRawEvent","isFinal","timeout","CONTENT_TOUCHES_QUICK_TAP_END_DELAY","onGestureEnded","updateGestureConfig","shouldActivateOnStart","disallowInterruption","Number","NaN","minPointers","maxPointers","props"],"mappings":";;;;;;;AAAA;;AAEA;;AACA;;AAKA;;AAEA;;;;;;AAEA,MAAMA,mBAAN,SAAkCC,+BAAlC,CAAyD;AAAA;AAAA;;AAAA;;AAAA,0CAET,IAFS;;AAAA,gDAoBlC,IApBkC;AAAA;;AAG/C,MA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AW,UAAAA,OAAO,GAAGC,8CAAV;AACA,eAAKV,uBAAL,CAA6B,KAAKD,YAAlC;AACA,eAAKA,YAAL,GAAoB,IAApB;AACD;;AACD,sCAAkB,MAAM;AACtB,eAAKG,SAAL,CAAe,EACb,GAAGX,EADU;AAEbY,YAAAA,SAAS,EAAErC,kBAAOgB,SAFL;AAGb0B,YAAAA,OAAO,EAAE;AAHI,WAAf,EADsB,CAMtB;;AACA,eAAKG,cAAL;AACD,SARD,EAQGF,OARH;AASD,OAnBD,MAmBO;AACL,aAAKP,SAAL,CAAe,EACb,GAAGX,EADU;AAEbY,UAAAA,SAAS,EAAErC,kBAAOc,UAFL;AAGb4B,UAAAA,OAAO,EAAE;AAHI,SAAf;AAKD;AACF;AACF;;AAEDI,EAAAA,mBAAmB,CAAC;AAClBC,IAAAA,qBAAqB,GAAG,KADN;AAElBC,IAAAA,oBAAoB,GAAG,KAFL;AAGlBzC,IAAAA,uBAAuB,GAAG,IAHR;AAIlBX,IAAAA,aAAa,GAAGqD,MAAM,CAACC,GAJL;AAKlBpD,IAAAA,OAAO,GAAGmD,MAAM,CAACC,GALC;AAMlBC,IAAAA,WAAW,GAAG,CANI;AAOlBC,IAAAA,WAAW,GAAG,CAPI;AAQlB,OAAGC;AARe,GAAD,EAShB;AACD,WAAO,MAAMP,mBAAN,CAA0B;AAC/BC,MAAAA,qBAD+B;AAE/BC,MAAAA,oBAF+B;AAG/BzC,MAAAA,uBAH+B;AAI/BX,MAAAA,aAJ+B;AAK/BE,MAAAA,OAL+B;AAM/BqD,MAAAA,WAN+B;AAO/BC,MAAAA,WAP+B;AAQ/B,SAAGC;AAR4B,KAA1B,CAAP;AAUD;;AAxJsD;;eA0J1C5D,mB","sourcesContent":["import Hammer from '@egjs/hammerjs';\n\nimport { State } from '../State';\nimport {\n CONTENT_TOUCHES_DELAY,\n CONTENT_TOUCHES_QUICK_TAP_END_DELAY,\n HammerInputNames,\n} from './constants';\nimport DiscreteGestureHandler from './DiscreteGestureHandler';\nimport { Config, HammerInputExt } from './GestureHandler';\nimport { fireAfterInterval, isValidNumber, isnan } from './utils';\n\nclass PressGestureHandler extends DiscreteGestureHandler {\n private visualFeedbackTimer: any;\n private initialEvent: HammerInputExt | null = null;\n get name() {\n return 'press';\n }\n\n get minDurationMs() {\n // @ts-ignore FIXME(TS)\n return isnan(this.config.minDurationMs) ? 5 : this.config.minDurationMs;\n }\n\n get maxDist() {\n return isnan(this.config.maxDist) ? 9 : this.config.maxDist;\n }\n\n get NativeGestureClass() {\n return Hammer.Press;\n }\n\n shouldDelayTouches = true;\n\n simulateCancelEvent(inputData: HammerInputExt) {\n // Long press never starts so we can't rely on the running event boolean.\n this.hasGestureFailed = true;\n this.cancelEvent(inputData);\n }\n\n updateHasCustomActivationCriteria({\n shouldCancelWhenOutside,\n maxDistSq,\n }: Config & { shouldCancelWhenOutside: boolean }) {\n return shouldCancelWhenOutside || !isValidNumber(maxDistSq);\n }\n\n getState(type: keyof typeof HammerInputNames): State {\n return {\n [Hammer.INPUT_START]: State.BEGAN,\n [Hammer.INPUT_MOVE]: State.ACTIVE,\n [Hammer.INPUT_END]: State.END,\n [Hammer.INPUT_CANCEL]: State.CANCELLED,\n }[type];\n }\n\n getConfig() {\n if (!this.hasCustomActivationCriteria) {\n // Default config\n // If no params have been defined then this config should emulate the native gesture as closely as possible.\n return {\n shouldCancelWhenOutside: true,\n maxDistSq: 10,\n };\n }\n return this.config;\n }\n\n getHammerConfig() {\n return {\n ...super.getHammerConfig(),\n // threshold: this.maxDist,\n time: this.minDurationMs,\n };\n }\n\n onGestureActivated(ev: HammerInputExt) {\n this.onGestureStart(ev);\n }\n\n shouldDelayTouchForEvent({ pointerType }: HammerInputExt) {\n // Don't disable event for mouse input\n return this.shouldDelayTouches && pointerType === 'touch';\n }\n\n onGestureStart(ev: HammerInputExt) {\n this.isGestureRunning = true;\n clearTimeout(this.visualFeedbackTimer);\n this.initialEvent = ev;\n this.visualFeedbackTimer = fireAfterInterval(() => {\n this.sendGestureStartedEvent(this.initialEvent as HammerInputExt);\n this.initialEvent = null;\n }, this.shouldDelayTouchForEvent(ev) && CONTENT_TOUCHES_DELAY);\n }\n\n sendGestureStartedEvent(ev: HammerInputExt) {\n clearTimeout(this.visualFeedbackTimer);\n this.visualFeedbackTimer = null;\n this.sendEvent({\n ...ev,\n eventType: Hammer.INPUT_MOVE,\n isFirst: true,\n });\n }\n\n forceInvalidate(event: HammerInputExt) {\n super.forceInvalidate(event);\n clearTimeout(this.visualFeedbackTimer);\n this.visualFeedbackTimer = null;\n this.initialEvent = null;\n }\n\n onRawEvent(ev: HammerInputExt) {\n super.onRawEvent(ev);\n if (this.isGestureRunning) {\n if (ev.isFinal) {\n let timeout;\n if (this.visualFeedbackTimer) {\n // Aesthetic timing for a quick tap.\n // We haven't activated the tap right away to emulate iOS `delaysContentTouches`\n // Now we must send the initial activation event and wait a set amount of time before firing the end event.\n timeout = CONTENT_TOUCHES_QUICK_TAP_END_DELAY;\n this.sendGestureStartedEvent(this.initialEvent as HammerInputExt);\n this.initialEvent = null;\n }\n fireAfterInterval(() => {\n this.sendEvent({\n ...ev,\n eventType: Hammer.INPUT_END,\n isFinal: true,\n });\n // @ts-ignore -- this should explicitly support undefined\n this.onGestureEnded();\n }, timeout);\n } else {\n this.sendEvent({\n ...ev,\n eventType: Hammer.INPUT_MOVE,\n isFinal: false,\n });\n }\n }\n }\n\n updateGestureConfig({\n shouldActivateOnStart = false,\n disallowInterruption = false,\n shouldCancelWhenOutside = true,\n minDurationMs = Number.NaN,\n maxDist = Number.NaN,\n minPointers = 1,\n maxPointers = 1,\n ...props\n }) {\n return super.updateGestureConfig({\n shouldActivateOnStart,\n disallowInterruption,\n shouldCancelWhenOutside,\n minDurationMs,\n maxDist,\n minPointers,\n maxPointers,\n ...props,\n });\n }\n}\nexport default PressGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/RotationGestureHandler.js b/lib/commonjs/web/RotationGestureHandler.js new file mode 100644 index 0000000000..4d2da4d9eb --- /dev/null +++ b/lib/commonjs/web/RotationGestureHandler.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _hammerjs = _interopRequireDefault(require("@egjs/hammerjs")); + +var _constants = require("./constants"); + +var _IndiscreteGestureHandler = _interopRequireDefault(require("./IndiscreteGestureHandler")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +class RotationGestureHandler extends _IndiscreteGestureHandler.default { + get name() { + return 'rotate'; + } + + get NativeGestureClass() { + return _hammerjs.default.Rotate; + } + + transformNativeEvent({ + rotation, + velocity, + center + }) { + var _this$initialRotation; + + return { + rotation: (rotation - ((_this$initialRotation = this.initialRotation) !== null && _this$initialRotation !== void 0 ? _this$initialRotation : 0)) * _constants.DEG_RAD, + anchorX: center.x, + anchorY: center.y, + velocity + }; + } + +} + +var _default = RotationGestureHandler; +exports.default = _default; +//# sourceMappingURL=RotationGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/web/RotationGestureHandler.js.map b/lib/commonjs/web/RotationGestureHandler.js.map new file mode 100644 index 0000000000..3b08030c89 --- /dev/null +++ b/lib/commonjs/web/RotationGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["RotationGestureHandler.ts"],"names":["RotationGestureHandler","IndiscreteGestureHandler","name","NativeGestureClass","Hammer","Rotate","transformNativeEvent","rotation","velocity","center","initialRotation","DEG_RAD","anchorX","x","anchorY","y"],"mappings":";;;;;;;AAAA;;AAEA;;AAEA;;;;AAEA,MAAMA,sBAAN,SAAqCC,iCAArC,CAA8D;AACpD,MAAJC,IAAI,GAAG;AACT,WAAO,QAAP;AACD;;AAEqB,MAAlBC,kBAAkB,GAAG;AACvB,WAAOC,kBAAOC,MAAd;AACD;;AAEDC,EAAAA,oBAAoB,CAAC;AAAEC,IAAAA,QAAF;AAAYC,IAAAA,QAAZ;AAAsBC,IAAAA;AAAtB,GAAD,EAAiD;AAAA;;AACnE,WAAO;AACLF,MAAAA,QAAQ,EAAE,CAACA,QAAQ,6BAAI,KAAKG,eAAT,yEAA4B,CAA5B,CAAT,IAA2CC,kBADhD;AAELC,MAAAA,OAAO,EAAEH,MAAM,CAACI,CAFX;AAGLC,MAAAA,OAAO,EAAEL,MAAM,CAACM,CAHX;AAILP,MAAAA;AAJK,KAAP;AAMD;;AAhB2D;;eAkB/CR,sB","sourcesContent":["import Hammer from '@egjs/hammerjs';\n\nimport { DEG_RAD } from './constants';\nimport { HammerInputExt } from './GestureHandler';\nimport IndiscreteGestureHandler from './IndiscreteGestureHandler';\n\nclass RotationGestureHandler extends IndiscreteGestureHandler {\n get name() {\n return 'rotate';\n }\n\n get NativeGestureClass() {\n return Hammer.Rotate;\n }\n\n transformNativeEvent({ rotation, velocity, center }: HammerInputExt) {\n return {\n rotation: (rotation - (this.initialRotation ?? 0)) * DEG_RAD,\n anchorX: center.x,\n anchorY: center.y,\n velocity,\n };\n }\n}\nexport default RotationGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/TapGestureHandler.js b/lib/commonjs/web/TapGestureHandler.js new file mode 100644 index 0000000000..d73a2012ba --- /dev/null +++ b/lib/commonjs/web/TapGestureHandler.js @@ -0,0 +1,192 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _hammerjs = _interopRequireDefault(require("@egjs/hammerjs")); + +var _DiscreteGestureHandler = _interopRequireDefault(require("./DiscreteGestureHandler")); + +var _utils = require("./utils"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +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; } + +class TapGestureHandler extends _DiscreteGestureHandler.default { + constructor(...args) { + super(...args); + + _defineProperty(this, "_shouldFireEndEvent", null); + + _defineProperty(this, "_timer", void 0); + + _defineProperty(this, "_multiTapTimer", void 0); + + _defineProperty(this, "onSuccessfulTap", ev => { + if (this._getPendingGestures().length) { + this._shouldFireEndEvent = ev; + return; + } + + if (ev.eventType === _hammerjs.default.INPUT_END) { + this.sendEvent({ ...ev, + eventType: _hammerjs.default.INPUT_MOVE + }); + } // When handler gets activated it will turn into State.END immediately. + + + this.sendEvent({ ...ev, + isFinal: true + }); + this.onGestureEnded(ev); + }); + } + + // TODO unused? + get name() { + return 'tap'; + } + + get NativeGestureClass() { + return _hammerjs.default.Tap; + } + + get maxDelayMs() { + // @ts-ignore TODO(TS) trace down config + return (0, _utils.isnan)(this.config.maxDelayMs) ? 300 : this.config.maxDelayMs; + } + + simulateCancelEvent(inputData) { + if (this.isGestureRunning) { + this.cancelEvent(inputData); + } + } + + onGestureActivated(ev) { + if (this.isGestureRunning) { + this.onSuccessfulTap(ev); + } + } + + onRawEvent(ev) { + super.onRawEvent(ev); // Attempt to create a touch-down event by checking if a valid tap hasn't started yet, then validating the input. + + if (!this.hasGestureFailed && !this.isGestureRunning && // Prevent multi-pointer events from misfiring. + !ev.isFinal) { + // Tap Gesture start event + const gesture = this.hammer.get(this.name); // @ts-ignore TODO(TS) trace down config + + if (gesture.options.enable(gesture, ev)) { + clearTimeout(this._multiTapTimer); + this.onStart(ev); + this.sendEvent(ev); + } + } + + if (ev.isFinal && ev.maxPointers > 1) { + setTimeout(() => { + // Handle case where one finger presses slightly + // after the first finger on a multi-tap event + if (this.isGestureRunning) { + this.cancelEvent(ev); + } + }); + } + + if (this.hasGestureFailed) { + return; + } // Hammer doesn't send a `cancel` event for taps. + // Manually fail the event. + + + if (ev.isFinal) { + // Handle case where one finger presses slightly + // after the first finger on a multi-tap event + if (ev.maxPointers > 1) { + setTimeout(() => { + if (this.isGestureRunning) { + this.cancelEvent(ev); + } + }); + } // Clear last timer + + + clearTimeout(this._timer); // Create time out for multi-taps. + + this._timer = setTimeout(() => { + this.hasGestureFailed = true; + this.cancelEvent(ev); + }, this.maxDelayMs); + } else if (!this.hasGestureFailed && !this.isGestureRunning) { + // Tap Gesture start event + const gesture = this.hammer.get(this.name); // @ts-ignore TODO(TS) trace down config + + if (gesture.options.enable(gesture, ev)) { + clearTimeout(this._multiTapTimer); + this.onStart(ev); + this.sendEvent(ev); + } + } + } + + getHammerConfig() { + return { ...super.getHammerConfig(), + event: this.name, + // @ts-ignore TODO(TS) trace down config + taps: (0, _utils.isnan)(this.config.numberOfTaps) ? 1 : this.config.numberOfTaps, + interval: this.maxDelayMs, + time: // @ts-ignore TODO(TS) trace down config + (0, _utils.isnan)(this.config.maxDurationMs) || this.config.maxDurationMs == null ? 250 : // @ts-ignore TODO(TS) trace down config + this.config.maxDurationMs + }; + } + + updateGestureConfig({ + shouldCancelWhenOutside = true, + maxDeltaX = Number.NaN, + maxDeltaY = Number.NaN, + numberOfTaps = 1, + minDurationMs = 525, + maxDelayMs = Number.NaN, + // eslint-disable-next-line @typescript-eslint/no-unused-vars -- TODO possibly forgotten to use in updateGestureConfig? + maxDurationMs = Number.NaN, + maxDist = 2, + minPointers = 1, + maxPointers = 1, + ...props + }) { + return super.updateGestureConfig({ + shouldCancelWhenOutside, + numberOfTaps, + maxDeltaX, + maxDeltaY, + minDurationMs, + maxDelayMs, + maxDist, + minPointers, + maxPointers, + ...props + }); + } + + onGestureEnded(...props) { + clearTimeout(this._timer); // @ts-ignore TODO(TS) check how onGestureEnded works + + super.onGestureEnded(...props); + } + + onWaitingEnded(_gesture) { + if (this._shouldFireEndEvent) { + this.onSuccessfulTap(this._shouldFireEndEvent); + this._shouldFireEndEvent = null; + } + } + +} + +var _default = TapGestureHandler; +exports.default = _default; +//# sourceMappingURL=TapGestureHandler.js.map \ No newline at end of file diff --git a/lib/commonjs/web/TapGestureHandler.js.map b/lib/commonjs/web/TapGestureHandler.js.map new file mode 100644 index 0000000000..9a87f34660 --- /dev/null +++ b/lib/commonjs/web/TapGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TapGestureHandler.ts"],"names":["TapGestureHandler","DiscreteGestureHandler","ev","_getPendingGestures","length","_shouldFireEndEvent","eventType","Hammer","INPUT_END","sendEvent","INPUT_MOVE","isFinal","onGestureEnded","name","NativeGestureClass","Tap","maxDelayMs","config","simulateCancelEvent","inputData","isGestureRunning","cancelEvent","onGestureActivated","onSuccessfulTap","onRawEvent","hasGestureFailed","gesture","hammer","get","options","enable","clearTimeout","_multiTapTimer","onStart","maxPointers","setTimeout","_timer","getHammerConfig","event","taps","numberOfTaps","interval","time","maxDurationMs","updateGestureConfig","shouldCancelWhenOutside","maxDeltaX","Number","NaN","maxDeltaY","minDurationMs","maxDist","minPointers","props","onWaitingEnded","_gesture"],"mappings":";;;;;;;AAAA;;AAEA;;AAEA;;;;;;AAEA,MAAMA,iBAAN,SAAgCC,+BAAhC,CAAuD;AAAA;AAAA;;AAAA,iDACA,IADA;;AAAA;;AAAA;;AAAA,6CA6BlCC,EAAD,IAAwB;AACxC,UAAI,KAAKC,mBAAL,GAA2BC,MAA/B,EAAuC;AACrC,aAAKC,mBAAL,GAA2BH,EAA3B;AACA;AACD;;AACD,UAAIA,EAAE,CAACI,SAAH,KAAiBC,kBAAOC,SAA5B,EAAuC;AACrC,aAAKC,SAAL,CAAe,EAAE,GAAGP,EAAL;AAASI,UAAAA,SAAS,EAAEC,kBAAOG;AAA3B,SAAf;AACD,OAPuC,CAQxC;;;AACA,WAAKD,SAAL,CAAe,EAAE,GAAGP,EAAL;AAASS,QAAAA,OAAO,EAAE;AAAlB,OAAf;AACA,WAAKC,cAAL,CAAoBV,EAApB;AACD,KAxCoD;AAAA;;AAGxB;AACrB,MAAJW,IAAI,GAAG;AACT,WAAO,KAAP;AACD;;AAEqB,MAAlBC,kBAAkB,GAAG;AACvB,WAAOP,kBAAOQ,GAAd;AACD;;AAEa,MAAVC,UAAU,GAAG;AACf;AACA,WAAO,kBAAM,KAAKC,MAAL,CAAYD,UAAlB,IAAgC,GAAhC,GAAsC,KAAKC,MAAL,CAAYD,UAAzD;AACD;;AAEDE,EAAAA,mBAAmB,CAAC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AGF,MAAM,CAACC,GAHD;AAIlBR,IAAAA,YAAY,GAAG,CAJG;AAKlBU,IAAAA,aAAa,GAAG,GALE;AAMlBlC,IAAAA,UAAU,GAAG+B,MAAM,CAACC,GANF;AAOlB;AACAL,IAAAA,aAAa,GAAGI,MAAM,CAACC,GARL;AASlBG,IAAAA,OAAO,GAAG,CATQ;AAUlBC,IAAAA,WAAW,GAAG,CAVI;AAWlBlB,IAAAA,WAAW,GAAG,CAXI;AAYlB,OAAGmB;AAZe,GAAD,EAahB;AACD,WAAO,MAAMT,mBAAN,CAA0B;AAC/BC,MAAAA,uBAD+B;AAE/BL,MAAAA,YAF+B;AAG/BM,MAAAA,SAH+B;AAI/BG,MAAAA,SAJ+B;AAK/BC,MAAAA,aAL+B;AAM/BlC,MAAAA,UAN+B;AAO/BmC,MAAAA,OAP+B;AAQ/BC,MAAAA,WAR+B;AAS/BlB,MAAAA,WAT+B;AAU/B,SAAGmB;AAV4B,KAA1B,CAAP;AAYD;;AAEDzC,EAAAA,cAAc,CAAC,GAAGyC,KAAJ,EAAgB;AAC5BtB,IAAAA,YAAY,CAAC,KAAKK,MAAN,CAAZ,CAD4B,CAE5B;;AACA,UAAMxB,cAAN,CAAqB,GAAGyC,KAAxB;AACD;;AAEDC,EAAAA,cAAc,CAACC,QAAD,EAAgB;AAC5B,QAAI,KAAKlD,mBAAT,EAA8B;AAC5B,WAAKkB,eAAL,CAAqB,KAAKlB,mBAA1B;AACA,WAAKA,mBAAL,GAA2B,IAA3B;AACD;AACF;;AAnKoD;;eAqKxCL,iB","sourcesContent":["import Hammer from '@egjs/hammerjs';\n\nimport DiscreteGestureHandler from './DiscreteGestureHandler';\nimport { HammerInputExt } from './GestureHandler';\nimport { isnan } from './utils';\n\nclass TapGestureHandler extends DiscreteGestureHandler {\n private _shouldFireEndEvent: HammerInputExt | null = null;\n private _timer: any;\n private _multiTapTimer: any; // TODO unused?\n get name() {\n return 'tap';\n }\n\n get NativeGestureClass() {\n return Hammer.Tap;\n }\n\n get maxDelayMs() {\n // @ts-ignore TODO(TS) trace down config\n return isnan(this.config.maxDelayMs) ? 300 : this.config.maxDelayMs;\n }\n\n simulateCancelEvent(inputData: HammerInputExt) {\n if (this.isGestureRunning) {\n this.cancelEvent(inputData);\n }\n }\n\n onGestureActivated(ev: HammerInputExt) {\n if (this.isGestureRunning) {\n this.onSuccessfulTap(ev);\n }\n }\n\n onSuccessfulTap = (ev: HammerInputExt) => {\n if (this._getPendingGestures().length) {\n this._shouldFireEndEvent = ev;\n return;\n }\n if (ev.eventType === Hammer.INPUT_END) {\n this.sendEvent({ ...ev, eventType: Hammer.INPUT_MOVE });\n }\n // When handler gets activated it will turn into State.END immediately.\n this.sendEvent({ ...ev, isFinal: true });\n this.onGestureEnded(ev);\n };\n\n onRawEvent(ev: HammerInput) {\n super.onRawEvent(ev);\n\n // Attempt to create a touch-down event by checking if a valid tap hasn't started yet, then validating the input.\n if (\n !this.hasGestureFailed &&\n !this.isGestureRunning &&\n // Prevent multi-pointer events from misfiring.\n !ev.isFinal\n ) {\n // Tap Gesture start event\n const gesture = this.hammer!.get(this.name);\n // @ts-ignore TODO(TS) trace down config\n if (gesture.options.enable(gesture, ev)) {\n clearTimeout(this._multiTapTimer);\n\n this.onStart(ev);\n this.sendEvent(ev);\n }\n }\n if (ev.isFinal && ev.maxPointers > 1) {\n setTimeout(() => {\n // Handle case where one finger presses slightly\n // after the first finger on a multi-tap event\n if (this.isGestureRunning) {\n this.cancelEvent(ev);\n }\n });\n }\n\n if (this.hasGestureFailed) {\n return;\n }\n // Hammer doesn't send a `cancel` event for taps.\n // Manually fail the event.\n if (ev.isFinal) {\n // Handle case where one finger presses slightly\n // after the first finger on a multi-tap event\n if (ev.maxPointers > 1) {\n setTimeout(() => {\n if (this.isGestureRunning) {\n this.cancelEvent(ev);\n }\n });\n }\n\n // Clear last timer\n clearTimeout(this._timer);\n // Create time out for multi-taps.\n this._timer = setTimeout(() => {\n this.hasGestureFailed = true;\n this.cancelEvent(ev);\n }, this.maxDelayMs);\n } else if (!this.hasGestureFailed && !this.isGestureRunning) {\n // Tap Gesture start event\n const gesture = this.hammer!.get(this.name);\n // @ts-ignore TODO(TS) trace down config\n if (gesture.options.enable(gesture, ev)) {\n clearTimeout(this._multiTapTimer);\n\n this.onStart(ev);\n this.sendEvent(ev);\n }\n }\n }\n\n getHammerConfig() {\n return {\n ...super.getHammerConfig(),\n event: this.name,\n // @ts-ignore TODO(TS) trace down config\n taps: isnan(this.config.numberOfTaps) ? 1 : this.config.numberOfTaps,\n interval: this.maxDelayMs,\n time:\n // @ts-ignore TODO(TS) trace down config\n isnan(this.config.maxDurationMs) || this.config.maxDurationMs == null\n ? 250\n : // @ts-ignore TODO(TS) trace down config\n this.config.maxDurationMs,\n };\n }\n\n updateGestureConfig({\n shouldCancelWhenOutside = true,\n maxDeltaX = Number.NaN,\n maxDeltaY = Number.NaN,\n numberOfTaps = 1,\n minDurationMs = 525,\n maxDelayMs = Number.NaN,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- TODO possibly forgotten to use in updateGestureConfig?\n maxDurationMs = Number.NaN,\n maxDist = 2,\n minPointers = 1,\n maxPointers = 1,\n ...props\n }) {\n return super.updateGestureConfig({\n shouldCancelWhenOutside,\n numberOfTaps,\n maxDeltaX,\n maxDeltaY,\n minDurationMs,\n maxDelayMs,\n maxDist,\n minPointers,\n maxPointers,\n ...props,\n });\n }\n\n onGestureEnded(...props: any) {\n clearTimeout(this._timer);\n // @ts-ignore TODO(TS) check how onGestureEnded works\n super.onGestureEnded(...props);\n }\n\n onWaitingEnded(_gesture: any) {\n if (this._shouldFireEndEvent) {\n this.onSuccessfulTap(this._shouldFireEndEvent);\n this._shouldFireEndEvent = null;\n }\n }\n}\nexport default TapGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/constants.js b/lib/commonjs/web/constants.js new file mode 100644 index 0000000000..f9ee37a5f0 --- /dev/null +++ b/lib/commonjs/web/constants.js @@ -0,0 +1,64 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.HammerDirectionNames = exports.HammerInputNames = exports.DirectionMap = exports.Direction = exports.EventMap = exports.DEG_RAD = exports.MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD = exports.MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD = exports.CONTENT_TOUCHES_QUICK_TAP_END_DELAY = exports.CONTENT_TOUCHES_DELAY = void 0; + +var _hammerjs = _interopRequireDefault(require("@egjs/hammerjs")); + +var _State = require("../State"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const CONTENT_TOUCHES_DELAY = 240; +exports.CONTENT_TOUCHES_DELAY = CONTENT_TOUCHES_DELAY; +const CONTENT_TOUCHES_QUICK_TAP_END_DELAY = 50; +exports.CONTENT_TOUCHES_QUICK_TAP_END_DELAY = CONTENT_TOUCHES_QUICK_TAP_END_DELAY; +const MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD = 0.1; +exports.MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD = MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD; +const MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD = 7; +exports.MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD = MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD; +const DEG_RAD = Math.PI / 180; // Map Hammer values to RNGH + +exports.DEG_RAD = DEG_RAD; +const EventMap = { + [_hammerjs.default.INPUT_START]: _State.State.BEGAN, + [_hammerjs.default.INPUT_MOVE]: _State.State.ACTIVE, + [_hammerjs.default.INPUT_END]: _State.State.END, + [_hammerjs.default.INPUT_CANCEL]: _State.State.FAILED +}; +exports.EventMap = EventMap; +const Direction = { + RIGHT: 1, + LEFT: 2, + UP: 4, + DOWN: 8 +}; +exports.Direction = Direction; +const DirectionMap = { + [_hammerjs.default.DIRECTION_RIGHT]: Direction.RIGHT, + [_hammerjs.default.DIRECTION_LEFT]: Direction.LEFT, + [_hammerjs.default.DIRECTION_UP]: Direction.UP, + [_hammerjs.default.DIRECTION_DOWN]: Direction.DOWN +}; +exports.DirectionMap = DirectionMap; +const HammerInputNames = { + [_hammerjs.default.INPUT_START]: 'START', + [_hammerjs.default.INPUT_MOVE]: 'MOVE', + [_hammerjs.default.INPUT_END]: 'END', + [_hammerjs.default.INPUT_CANCEL]: 'CANCEL' +}; +exports.HammerInputNames = HammerInputNames; +const HammerDirectionNames = { + [_hammerjs.default.DIRECTION_HORIZONTAL]: 'HORIZONTAL', + [_hammerjs.default.DIRECTION_UP]: 'UP', + [_hammerjs.default.DIRECTION_DOWN]: 'DOWN', + [_hammerjs.default.DIRECTION_VERTICAL]: 'VERTICAL', + [_hammerjs.default.DIRECTION_NONE]: 'NONE', + [_hammerjs.default.DIRECTION_ALL]: 'ALL', + [_hammerjs.default.DIRECTION_RIGHT]: 'RIGHT', + [_hammerjs.default.DIRECTION_LEFT]: 'LEFT' +}; +exports.HammerDirectionNames = HammerDirectionNames; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/lib/commonjs/web/constants.js.map b/lib/commonjs/web/constants.js.map new file mode 100644 index 0000000000..b2bd4f2ed2 --- /dev/null +++ b/lib/commonjs/web/constants.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["constants.ts"],"names":["CONTENT_TOUCHES_DELAY","CONTENT_TOUCHES_QUICK_TAP_END_DELAY","MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD","MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD","DEG_RAD","Math","PI","EventMap","Hammer","INPUT_START","State","BEGAN","INPUT_MOVE","ACTIVE","INPUT_END","END","INPUT_CANCEL","FAILED","Direction","RIGHT","LEFT","UP","DOWN","DirectionMap","DIRECTION_RIGHT","DIRECTION_LEFT","DIRECTION_UP","DIRECTION_DOWN","HammerInputNames","HammerDirectionNames","DIRECTION_HORIZONTAL","DIRECTION_VERTICAL","DIRECTION_NONE","DIRECTION_ALL"],"mappings":";;;;;;;AAAA;;AAEA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C,GAACnB,kBAAOuB,kBAAR,GAA6B,UAJK;AAKlC,GAACvB,kBAAOwB,cAAR,GAAyB,MALS;AAMlC,GAACxB,kBAAOyB,aAAR,GAAwB,KANU;AAOlC,GAACzB,kBAAOgB,eAAR,GAA0B,OAPQ;AAQlC,GAAChB,kBAAOiB,cAAR,GAAyB;AARS,CAA7B","sourcesContent":["import Hammer from '@egjs/hammerjs';\n\nimport { State } from '../State';\n\nexport const CONTENT_TOUCHES_DELAY = 240;\nexport const CONTENT_TOUCHES_QUICK_TAP_END_DELAY = 50;\nexport const MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD = 0.1;\nexport const MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD = 7;\nexport const DEG_RAD = Math.PI / 180;\n\n// Map Hammer values to RNGH\nexport const EventMap = {\n [Hammer.INPUT_START]: State.BEGAN,\n [Hammer.INPUT_MOVE]: State.ACTIVE,\n [Hammer.INPUT_END]: State.END,\n [Hammer.INPUT_CANCEL]: State.FAILED,\n} as const;\n\nexport const Direction = {\n RIGHT: 1,\n LEFT: 2,\n UP: 4,\n DOWN: 8,\n};\n\nexport const DirectionMap = {\n [Hammer.DIRECTION_RIGHT]: Direction.RIGHT,\n [Hammer.DIRECTION_LEFT]: Direction.LEFT,\n [Hammer.DIRECTION_UP]: Direction.UP,\n [Hammer.DIRECTION_DOWN]: Direction.DOWN,\n};\n\nexport const HammerInputNames = {\n [Hammer.INPUT_START]: 'START',\n [Hammer.INPUT_MOVE]: 'MOVE',\n [Hammer.INPUT_END]: 'END',\n [Hammer.INPUT_CANCEL]: 'CANCEL',\n};\nexport const HammerDirectionNames = {\n [Hammer.DIRECTION_HORIZONTAL]: 'HORIZONTAL',\n [Hammer.DIRECTION_UP]: 'UP',\n [Hammer.DIRECTION_DOWN]: 'DOWN',\n [Hammer.DIRECTION_VERTICAL]: 'VERTICAL',\n [Hammer.DIRECTION_NONE]: 'NONE',\n [Hammer.DIRECTION_ALL]: 'ALL',\n [Hammer.DIRECTION_RIGHT]: 'RIGHT',\n [Hammer.DIRECTION_LEFT]: 'LEFT',\n};\n"]} \ No newline at end of file diff --git a/lib/commonjs/web/utils.js b/lib/commonjs/web/utils.js new file mode 100644 index 0000000000..15f4a5c4ab --- /dev/null +++ b/lib/commonjs/web/utils.js @@ -0,0 +1,42 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.fireAfterInterval = fireAfterInterval; +exports.TEST_MAX_IF_NOT_NAN = exports.VEC_LEN_SQ = exports.TEST_MIN_IF_NOT_NAN = exports.isValidNumber = exports.isnan = void 0; + +// TODO(TS) remove if not necessary after rewrite +const isnan = v => Number.isNaN(v); // TODO(TS) remove if not necessary after rewrite + + +exports.isnan = isnan; + +const isValidNumber = v => typeof v === 'number' && !Number.isNaN(v); + +exports.isValidNumber = isValidNumber; + +const TEST_MIN_IF_NOT_NAN = (value, limit) => !isnan(limit) && (limit < 0 && value <= limit || limit >= 0 && value >= limit); + +exports.TEST_MIN_IF_NOT_NAN = TEST_MIN_IF_NOT_NAN; + +const VEC_LEN_SQ = ({ + x = 0, + y = 0 +} = {}) => x * x + y * y; + +exports.VEC_LEN_SQ = VEC_LEN_SQ; + +const TEST_MAX_IF_NOT_NAN = (value, max) => !isnan(max) && (max < 0 && value < max || max >= 0 && value > max); + +exports.TEST_MAX_IF_NOT_NAN = TEST_MAX_IF_NOT_NAN; + +function fireAfterInterval(method, interval) { + if (!interval) { + method(); + return null; + } + + return setTimeout(() => method(), interval); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/lib/commonjs/web/utils.js.map b/lib/commonjs/web/utils.js.map new file mode 100644 index 0000000000..405560aae2 --- /dev/null +++ b/lib/commonjs/web/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["utils.ts"],"names":["isnan","v","Number","isNaN","isValidNumber","TEST_MIN_IF_NOT_NAN","value","limit","VEC_LEN_SQ","x","y","TEST_MAX_IF_NOT_NAN","max","fireAfterInterval","method","interval","setTimeout"],"mappings":";;;;;;;;AAAA;AACO,MAAMA,KAAK,GAAIC,CAAD,IAAgBC,MAAM,CAACC,KAAP,CAAaF,CAAb,CAA9B,C,CAEP;;;;;AACO,MAAMG,aAAa,GAAIH,CAAD,IAC3B,OAAOA,CAAP,KAAa,QAAb,IAAyB,CAACC,MAAM,CAACC,KAAP,CAAaF,CAAb,CADrB;;;;AAGA,MAAMI,mBAAmB,GAAG,CAACC,KAAD,EAAgBC,KAAhB,KACjC,CAACP,KAAK,CAACO,KAAD,CAAN,KACEA,KAAK,GAAG,CAAR,IAAaD,KAAK,IAAIC,KAAvB,IAAkCA,KAAK,IAAI,CAAT,IAAcD,KAAK,IAAIC,KAD1D,CADK;;;;AAGA,MAAMC,UAAU,GAAG,CAAC;AAAEC,EAAAA,CAAC,GAAG,CAAN;AAASC,EAAAA,CAAC,GAAG;AAAb,IAAmB,EAApB,KAA2BD,CAAC,GAAGA,CAAJ,GAAQC,CAAC,GAAGA,CAA1D;;;;AACA,MAAMC,mBAAmB,GAAG,CAACL,KAAD,EAAgBM,GAAhB,KACjC,CAACZ,KAAK,CAACY,GAAD,CAAN,KAAiBA,GAAG,GAAG,CAAN,IAAWN,KAAK,GAAGM,GAApB,IAA6BA,GAAG,IAAI,CAAP,IAAYN,KAAK,GAAGM,GAAjE,CADK;;;;AAGA,SAASC,iBAAT,CACLC,MADK,EAELC,QAFK,EAGL;AACA,MAAI,CAACA,QAAL,EAAe;AACbD,IAAAA,MAAM;AACN,WAAO,IAAP;AACD;;AACD,SAAOE,UAAU,CAAC,MAAMF,MAAM,EAAb,EAAiBC,QAAjB,CAAjB;AACD","sourcesContent":["// TODO(TS) remove if not necessary after rewrite\nexport const isnan = (v: unknown) => Number.isNaN(v);\n\n// TODO(TS) remove if not necessary after rewrite\nexport const isValidNumber = (v: unknown) =>\n typeof v === 'number' && !Number.isNaN(v);\n\nexport const TEST_MIN_IF_NOT_NAN = (value: number, limit: number): boolean =>\n !isnan(limit) &&\n ((limit < 0 && value <= limit) || (limit >= 0 && value >= limit));\nexport const VEC_LEN_SQ = ({ x = 0, y = 0 } = {}) => x * x + y * y;\nexport const TEST_MAX_IF_NOT_NAN = (value: number, max: number) =>\n !isnan(max) && ((max < 0 && value < max) || (max >= 0 && value > max));\n\nexport function fireAfterInterval(\n method: () => void,\n interval?: number | boolean\n) {\n if (!interval) {\n method();\n return null;\n }\n return setTimeout(() => method(), interval);\n}\n"]} \ No newline at end of file diff --git a/lib/module/Directions.js b/lib/module/Directions.js new file mode 100644 index 0000000000..4856fd6e62 --- /dev/null +++ b/lib/module/Directions.js @@ -0,0 +1,7 @@ +export const Directions = { + RIGHT: 1, + LEFT: 2, + UP: 4, + DOWN: 8 +}; // eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; it can be used as a type and as a value +//# sourceMappingURL=Directions.js.map \ No newline at end of file diff --git a/lib/module/Directions.js.map b/lib/module/Directions.js.map new file mode 100644 index 0000000000..0d1a3e05b1 --- /dev/null +++ b/lib/module/Directions.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["Directions.ts"],"names":["Directions","RIGHT","LEFT","UP","DOWN"],"mappings":"AAAA,OAAO,MAAMA,UAAU,GAAG;AACxBC,EAAAA,KAAK,EAAE,CADiB;AAExBC,EAAAA,IAAI,EAAE,CAFkB;AAGxBC,EAAAA,EAAE,EAAE,CAHoB;AAIxBC,EAAAA,IAAI,EAAE;AAJkB,CAAnB,C,CAOP","sourcesContent":["export const Directions = {\n RIGHT: 1,\n LEFT: 2,\n UP: 4,\n DOWN: 8,\n} as const;\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; it can be used as a type and as a value\nexport type Directions = typeof Directions[keyof typeof Directions];\n"]} \ No newline at end of file diff --git a/lib/module/EventType.js b/lib/module/EventType.js new file mode 100644 index 0000000000..6884d64b44 --- /dev/null +++ b/lib/module/EventType.js @@ -0,0 +1,8 @@ +export const EventType = { + UNDETERMINED: 0, + TOUCHES_DOWN: 1, + TOUCHES_MOVE: 2, + TOUCHES_UP: 3, + TOUCHES_CANCELLED: 4 +}; // eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; it can be used as a type and as a value +//# sourceMappingURL=EventType.js.map \ No newline at end of file diff --git a/lib/module/EventType.js.map b/lib/module/EventType.js.map new file mode 100644 index 0000000000..88bb13d66b --- /dev/null +++ b/lib/module/EventType.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["EventType.ts"],"names":["EventType","UNDETERMINED","TOUCHES_DOWN","TOUCHES_MOVE","TOUCHES_UP","TOUCHES_CANCELLED"],"mappings":"AAAA,OAAO,MAAMA,SAAS,GAAG;AACvBC,EAAAA,YAAY,EAAE,CADS;AAEvBC,EAAAA,YAAY,EAAE,CAFS;AAGvBC,EAAAA,YAAY,EAAE,CAHS;AAIvBC,EAAAA,UAAU,EAAE,CAJW;AAKvBC,EAAAA,iBAAiB,EAAE;AALI,CAAlB,C,CAQP","sourcesContent":["export const EventType = {\n UNDETERMINED: 0,\n TOUCHES_DOWN: 1,\n TOUCHES_MOVE: 2,\n TOUCHES_UP: 3,\n TOUCHES_CANCELLED: 4,\n} as const;\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; it can be used as a type and as a value\nexport type EventType = typeof EventType[keyof typeof EventType];\n"]} \ No newline at end of file diff --git a/lib/module/GestureHandlerRootView.android.js b/lib/module/GestureHandlerRootView.android.js new file mode 100644 index 0000000000..d4c4dd98b6 --- /dev/null +++ b/lib/module/GestureHandlerRootView.android.js @@ -0,0 +1,10 @@ +import * as React from 'react'; +import { requireNativeComponent } from 'react-native'; +const GestureHandlerRootViewNative = requireNativeComponent('GestureHandlerRootView'); +export default function GestureHandlerRootView({ + children, + ...rest +}) { + return /*#__PURE__*/React.createElement(GestureHandlerRootViewNative, rest, children); +} +//# sourceMappingURL=GestureHandlerRootView.android.js.map \ No newline at end of file diff --git a/lib/module/GestureHandlerRootView.android.js.map b/lib/module/GestureHandlerRootView.android.js.map new file mode 100644 index 0000000000..8f1075c585 --- /dev/null +++ b/lib/module/GestureHandlerRootView.android.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureHandlerRootView.android.tsx"],"names":["React","requireNativeComponent","GestureHandlerRootViewNative","GestureHandlerRootView","children","rest"],"mappings":"AAAA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AACA,SAASC,sBAAT,QAAuC,cAAvC;AAGA,MAAMC,4BAA4B,GAAGD,sBAAsB,CACzD,wBADyD,CAA3D;AAIA,eAAe,SAASE,sBAAT,CAAgC;AAC7CC,EAAAA,QAD6C;AAE7C,KAAGC;AAF0C,CAAhC,EAGiB;AAC9B,sBACE,oBAAC,4BAAD,EAAkCA,IAAlC,EACGD,QADH,CADF;AAKD","sourcesContent":["import * as React from 'react';\nimport { requireNativeComponent } from 'react-native';\nimport { GestureHandlerRootViewProps } from './GestureHandlerRootView';\n\nconst GestureHandlerRootViewNative = requireNativeComponent(\n 'GestureHandlerRootView'\n);\n\nexport default function GestureHandlerRootView({\n children,\n ...rest\n}: GestureHandlerRootViewProps) {\n return (\n \n {children}\n \n );\n}\n"]} \ No newline at end of file diff --git a/lib/module/GestureHandlerRootView.js b/lib/module/GestureHandlerRootView.js new file mode 100644 index 0000000000..f6522df474 --- /dev/null +++ b/lib/module/GestureHandlerRootView.js @@ -0,0 +1,7 @@ +import * as React from 'react'; +import { View } from 'react-native'; +export default function GestureHandlerRootView({ ...rest +}) { + return /*#__PURE__*/React.createElement(View, rest); +} +//# sourceMappingURL=GestureHandlerRootView.js.map \ No newline at end of file diff --git a/lib/module/GestureHandlerRootView.js.map b/lib/module/GestureHandlerRootView.js.map new file mode 100644 index 0000000000..a27fa70b4c --- /dev/null +++ b/lib/module/GestureHandlerRootView.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureHandlerRootView.tsx"],"names":["React","View","GestureHandlerRootView","rest"],"mappings":"AAAA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AAEA,SAASC,IAAT,QAAgC,cAAhC;AAKA,eAAe,SAASC,sBAAT,CAAgC,EAC7C,GAAGC;AAD0C,CAAhC,EAEiB;AAC9B,sBAAO,oBAAC,IAAD,EAAUA,IAAV,CAAP;AACD","sourcesContent":["import * as React from 'react';\nimport { PropsWithChildren } from 'react';\nimport { View, ViewProps } from 'react-native';\n\nexport interface GestureHandlerRootViewProps\n extends PropsWithChildren {}\n\nexport default function GestureHandlerRootView({\n ...rest\n}: GestureHandlerRootViewProps) {\n return ;\n}\n"]} \ No newline at end of file diff --git a/lib/module/PlatformConstants.js b/lib/module/PlatformConstants.js new file mode 100644 index 0000000000..9fc64f26b0 --- /dev/null +++ b/lib/module/PlatformConstants.js @@ -0,0 +1,5 @@ +var _NativeModules$Platfo; + +import { NativeModules, Platform } from 'react-native'; +export default (_NativeModules$Platfo = NativeModules === null || NativeModules === void 0 ? void 0 : NativeModules.PlatformConstants) !== null && _NativeModules$Platfo !== void 0 ? _NativeModules$Platfo : Platform.constants; +//# sourceMappingURL=PlatformConstants.js.map \ No newline at end of file diff --git a/lib/module/PlatformConstants.js.map b/lib/module/PlatformConstants.js.map new file mode 100644 index 0000000000..dab8e80704 --- /dev/null +++ b/lib/module/PlatformConstants.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PlatformConstants.ts"],"names":["NativeModules","Platform","PlatformConstants","constants"],"mappings":";;AAAA,SAASA,aAAT,EAAwBC,QAAxB,QAAwC,cAAxC;AAMA,wCAAgBD,aAAhB,aAAgBA,aAAhB,uBAAgBA,aAAa,CAAEE,iBAA/B,yEACED,QAAQ,CAACE,SADX","sourcesContent":["import { NativeModules, Platform } from 'react-native';\n\ntype PlatformConstants = {\n forceTouchAvailable: boolean;\n};\n\nexport default (NativeModules?.PlatformConstants ??\n Platform.constants) as PlatformConstants;\n"]} \ No newline at end of file diff --git a/lib/module/PlatformConstants.web.js b/lib/module/PlatformConstants.web.js new file mode 100644 index 0000000000..d48b0dade9 --- /dev/null +++ b/lib/module/PlatformConstants.web.js @@ -0,0 +1,7 @@ +export default { + get forceTouchAvailable() { + return false; + } + +}; +//# sourceMappingURL=PlatformConstants.web.js.map \ No newline at end of file diff --git a/lib/module/PlatformConstants.web.js.map b/lib/module/PlatformConstants.web.js.map new file mode 100644 index 0000000000..dd00b47d57 --- /dev/null +++ b/lib/module/PlatformConstants.web.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PlatformConstants.web.ts"],"names":["forceTouchAvailable"],"mappings":"AAAA,eAAe;AACb,MAAIA,mBAAJ,GAA0B;AACxB,WAAO,KAAP;AACD;;AAHY,CAAf","sourcesContent":["export default {\n get forceTouchAvailable() {\n return false;\n },\n};\n"]} \ No newline at end of file diff --git a/lib/module/RNGestureHandlerModule.js b/lib/module/RNGestureHandlerModule.js new file mode 100644 index 0000000000..7a78bdf574 --- /dev/null +++ b/lib/module/RNGestureHandlerModule.js @@ -0,0 +1,13 @@ +import { NativeModules } from 'react-native'; +const { + RNGestureHandlerModule +} = NativeModules; + +if (RNGestureHandlerModule == null) { + console.error(`react-native-gesture-handler module was not found. Make sure you're running your app on the native platform and your code is linked properly (cd ios && pod install && cd ..). + + For installation instructions, please refer to https://docs.swmansion.com/react-native-gesture-handler/docs/#installation`.split('\n').map(line => line.trim()).join('\n')); +} + +export default RNGestureHandlerModule; +//# sourceMappingURL=RNGestureHandlerModule.js.map \ No newline at end of file diff --git a/lib/module/RNGestureHandlerModule.js.map b/lib/module/RNGestureHandlerModule.js.map new file mode 100644 index 0000000000..8c9d1da13c --- /dev/null +++ b/lib/module/RNGestureHandlerModule.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["RNGestureHandlerModule.ts"],"names":["NativeModules","RNGestureHandlerModule","console","error","split","map","line","trim","join"],"mappings":"AAAA,SAASA,aAAT,QAA8B,cAA9B;AACA,MAAM;AAAEC,EAAAA;AAAF,IAA6BD,aAAnC;;AAEA,IAAIC,sBAAsB,IAAI,IAA9B,EAAoC;AAClCC,EAAAA,OAAO,CAACC,KAAR,CACG;AACL;AACA,8HAFI,CAGGC,KAHH,CAGS,IAHT,EAIGC,GAJH,CAIQC,IAAD,IAAUA,IAAI,CAACC,IAAL,EAJjB,EAKGC,IALH,CAKQ,IALR,CADF;AAQD;;AAsBD,eAAeP,sBAAf","sourcesContent":["import { NativeModules } from 'react-native';\nconst { RNGestureHandlerModule } = NativeModules;\n\nif (RNGestureHandlerModule == null) {\n console.error(\n `react-native-gesture-handler module was not found. Make sure you're running your app on the native platform and your code is linked properly (cd ios && pod install && cd ..).\n\n For installation instructions, please refer to https://docs.swmansion.com/react-native-gesture-handler/docs/#installation`\n .split('\\n')\n .map((line) => line.trim())\n .join('\\n')\n );\n}\n\nexport type RNGestureHandlerModuleProps = {\n handleSetJSResponder: (tag: number, blockNativeResponder: boolean) => void;\n handleClearJSResponder: () => void;\n createGestureHandler: (\n handlerName: string,\n handlerTag: number,\n config: Readonly>\n ) => void;\n attachGestureHandler: (\n handlerTag: number,\n newView: number,\n usingDeviceEvents: boolean\n ) => void;\n updateGestureHandler: (\n handlerTag: number,\n newConfig: Readonly>\n ) => void;\n dropGestureHandler: (handlerTag: number) => void;\n};\n\nexport default RNGestureHandlerModule as RNGestureHandlerModuleProps;\n"]} \ No newline at end of file diff --git a/lib/module/RNGestureHandlerModule.web.js b/lib/module/RNGestureHandlerModule.web.js new file mode 100644 index 0000000000..b47f69c2f2 --- /dev/null +++ b/lib/module/RNGestureHandlerModule.web.js @@ -0,0 +1,56 @@ +import { Direction } from './web/constants'; +import FlingGestureHandler from './web/FlingGestureHandler'; +import LongPressGestureHandler from './web/LongPressGestureHandler'; +import NativeViewGestureHandler from './web/NativeViewGestureHandler'; +import * as NodeManager from './web/NodeManager'; +import PanGestureHandler from './web/PanGestureHandler'; +import PinchGestureHandler from './web/PinchGestureHandler'; +import RotationGestureHandler from './web/RotationGestureHandler'; +import TapGestureHandler from './web/TapGestureHandler'; +export const Gestures = { + PanGestureHandler, + RotationGestureHandler, + PinchGestureHandler, + TapGestureHandler, + NativeViewGestureHandler, + LongPressGestureHandler, + FlingGestureHandler // ForceTouchGestureHandler, + +}; +export default { + Direction, + + handleSetJSResponder(tag, blockNativeResponder) { + console.warn('handleSetJSResponder: ', tag, blockNativeResponder); + }, + + handleClearJSResponder() { + console.warn('handleClearJSResponder: '); + }, + + createGestureHandler(handlerName, handlerTag, config) { + //TODO(TS) extends config + if (!(handlerName in Gestures)) throw new Error(`react-native-gesture-handler: ${handlerName} is not supported on web.`); + const GestureClass = Gestures[handlerName]; + NodeManager.createGestureHandler(handlerTag, new GestureClass()); + this.updateGestureHandler(handlerTag, config); + }, + + attachGestureHandler(handlerTag, newView, _usingDeviceEvents, propsRef) { + NodeManager.getHandler(handlerTag).setView(newView, propsRef); + }, + + updateGestureHandler(handlerTag, newConfig) { + NodeManager.getHandler(handlerTag).updateGestureConfig(newConfig); + }, + + getGestureHandlerNode(handlerTag) { + return NodeManager.getHandler(handlerTag); + }, + + dropGestureHandler(handlerTag) { + NodeManager.dropGestureHandler(handlerTag); + } + +}; +//# sourceMappingURL=RNGestureHandlerModule.web.js.map \ No newline at end of file diff --git a/lib/module/RNGestureHandlerModule.web.js.map b/lib/module/RNGestureHandlerModule.web.js.map new file mode 100644 index 0000000000..4a43b87aae --- /dev/null +++ b/lib/module/RNGestureHandlerModule.web.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["RNGestureHandlerModule.web.ts"],"names":["Direction","FlingGestureHandler","LongPressGestureHandler","NativeViewGestureHandler","NodeManager","PanGestureHandler","PinchGestureHandler","RotationGestureHandler","TapGestureHandler","Gestures","handleSetJSResponder","tag","blockNativeResponder","console","warn","handleClearJSResponder","createGestureHandler","handlerName","handlerTag","config","Error","GestureClass","updateGestureHandler","attachGestureHandler","newView","_usingDeviceEvents","propsRef","getHandler","setView","newConfig","updateGestureConfig","getGestureHandlerNode","dropGestureHandler"],"mappings":"AAAA,SAASA,SAAT,QAA0B,iBAA1B;AACA,OAAOC,mBAAP,MAAgC,2BAAhC;AACA,OAAOC,uBAAP,MAAoC,+BAApC;AACA,OAA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CJ,OAA3C,EAAoDE,QAApD;AACD,GA7BY;;AA8BbJ,EAAAA,oBAAoB,CAACJ,UAAD,EAAqBW,SAArB,EAAqC;AACvDzB,IAAAA,WAAW,CAACuB,UAAZ,CAAuBT,UAAvB,EAAmCY,mBAAnC,CAAuDD,SAAvD;AACD,GAhCY;;AAiCbE,EAAAA,qBAAqB,CAACb,UAAD,EAAqB;AACxC,WAAOd,WAAW,CAACuB,UAAZ,CAAuBT,UAAvB,CAAP;AACD,GAnCY;;AAoCbc,EAAAA,kBAAkB,CAACd,UAAD,EAAqB;AACrCd,IAAAA,WAAW,CAAC4B,kBAAZ,CAA+Bd,UAA/B;AACD;;AAtCY,CAAf","sourcesContent":["import { Direction } from './web/constants';\nimport FlingGestureHandler from './web/FlingGestureHandler';\nimport LongPressGestureHandler from './web/LongPressGestureHandler';\nimport NativeViewGestureHandler from './web/NativeViewGestureHandler';\nimport * as NodeManager from './web/NodeManager';\nimport PanGestureHandler from './web/PanGestureHandler';\nimport PinchGestureHandler from './web/PinchGestureHandler';\nimport RotationGestureHandler from './web/RotationGestureHandler';\nimport TapGestureHandler from './web/TapGestureHandler';\n\nexport const Gestures = {\n PanGestureHandler,\n RotationGestureHandler,\n PinchGestureHandler,\n TapGestureHandler,\n NativeViewGestureHandler,\n LongPressGestureHandler,\n FlingGestureHandler,\n // ForceTouchGestureHandler,\n};\n\nexport default {\n Direction,\n handleSetJSResponder(tag: number, blockNativeResponder: boolean) {\n console.warn('handleSetJSResponder: ', tag, blockNativeResponder);\n },\n handleClearJSResponder() {\n console.warn('handleClearJSResponder: ');\n },\n createGestureHandler(\n handlerName: keyof typeof Gestures,\n handlerTag: number,\n config: T\n ) {\n //TODO(TS) extends config\n if (!(handlerName in Gestures))\n throw new Error(\n `react-native-gesture-handler: ${handlerName} is not supported on web.`\n );\n const GestureClass = Gestures[handlerName];\n NodeManager.createGestureHandler(handlerTag, new GestureClass());\n this.updateGestureHandler(handlerTag, config);\n },\n attachGestureHandler(\n handlerTag: number,\n newView: number,\n _usingDeviceEvents: boolean,\n propsRef: React.RefObject\n ) {\n NodeManager.getHandler(handlerTag).setView(newView, propsRef);\n },\n updateGestureHandler(handlerTag: number, newConfig: any) {\n NodeManager.getHandler(handlerTag).updateGestureConfig(newConfig);\n },\n getGestureHandlerNode(handlerTag: number) {\n return NodeManager.getHandler(handlerTag);\n },\n dropGestureHandler(handlerTag: number) {\n NodeManager.dropGestureHandler(handlerTag);\n },\n};\n"]} \ No newline at end of file diff --git a/lib/module/State.js b/lib/module/State.js new file mode 100644 index 0000000000..3b1605de25 --- /dev/null +++ b/lib/module/State.js @@ -0,0 +1,10 @@ +// TODO use State from RNModule +export const State = { + UNDETERMINED: 0, + FAILED: 1, + BEGAN: 2, + CANCELLED: 3, + ACTIVE: 4, + END: 5 +}; // eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; it can be used as a type and as a value +//# sourceMappingURL=State.js.map \ No newline at end of file diff --git a/lib/module/State.js.map b/lib/module/State.js.map new file mode 100644 index 0000000000..26d79d35a4 --- /dev/null +++ b/lib/module/State.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["State.ts"],"names":["State","UNDETERMINED","FAILED","BEGAN","CANCELLED","ACTIVE","END"],"mappings":"AAAA;AAEA,OAAO,MAAMA,KAAK,GAAG;AACnBC,EAAAA,YAAY,EAAE,CADK;AAEnBC,EAAAA,MAAM,EAAE,CAFW;AAGnBC,EAAAA,KAAK,EAAE,CAHY;AAInBC,EAAAA,SAAS,EAAE,CAJQ;AAKnBC,EAAAA,MAAM,EAAE,CALW;AAMnBC,EAAAA,GAAG,EAAE;AANc,CAAd,C,CASP","sourcesContent":["// TODO use State from RNModule\n\nexport const State = {\n UNDETERMINED: 0,\n FAILED: 1,\n BEGAN: 2,\n CANCELLED: 3,\n ACTIVE: 4,\n END: 5,\n} as const;\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; it can be used as a type and as a value\nexport type State = typeof State[keyof typeof State];\n"]} \ No newline at end of file diff --git a/lib/module/components/DrawerLayout.js b/lib/module/components/DrawerLayout.js new file mode 100644 index 0000000000..167a8ed5e7 --- /dev/null +++ b/lib/module/components/DrawerLayout.js @@ -0,0 +1,520 @@ +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; } + +// This component is based on RN's DrawerLayoutAndroid API +// +// It perhaps deserves to be put in a separate repo, but since it relies on +// react-native-gesture-handler library which isn't very popular at the moment I +// decided to keep it here for the time being. It will allow us to move faster +// and fix issues that may arise in gesture handler library that could be found +// when using the drawer component +import * as React from 'react'; +import { Component } from 'react'; +import invariant from 'invariant'; +import { Animated, StyleSheet, View, Keyboard, StatusBar, I18nManager } from 'react-native'; +import { PanGestureHandler } from '../handlers/PanGestureHandler'; +import { TapGestureHandler } from '../handlers/TapGestureHandler'; +import { State } from '../State'; +const DRAG_TOSS = 0.05; +const IDLE = 'Idle'; +const DRAGGING = 'Dragging'; +const SETTLING = 'Settling'; +export default class DrawerLayout extends Component { + constructor(_props) { + super(_props); + + _defineProperty(this, "openValue", void 0); + + _defineProperty(this, "onGestureEvent", void 0); + + _defineProperty(this, "accessibilityIsModalView", /*#__PURE__*/React.createRef()); + + _defineProperty(this, "pointerEventsView", /*#__PURE__*/React.createRef()); + + _defineProperty(this, "panGestureHandler", /*#__PURE__*/React.createRef()); + + _defineProperty(this, "drawerShown", false); + + _defineProperty(this, "updateAnimatedEvent", (props, state) => { + // Event definition is based on + const { + drawerPosition, + drawerWidth, + drawerType + } = props; + const { + dragX: dragXValue, + touchX: touchXValue, + drawerTranslation, + containerWidth + } = state; + let dragX = dragXValue; + let touchX = touchXValue; + + if (drawerPosition !== 'left') { + // Most of the code is written in a way to handle left-side drawer. In + // order to handle right-side drawer the only thing we need to do is to + // reverse events coming from gesture handler in a way they emulate + // left-side drawer gestures. E.g. dragX is simply -dragX, and touchX is + // calulcated by subtracing real touchX from the width of the container + // (such that when touch happens at the right edge the value is simply 0) + dragX = Animated.multiply(new Animated.Value(-1), dragXValue); // TODO(TS): (for all "as" in this file) make sure we can map this + + touchX = Animated.add(new Animated.Value(containerWidth), Animated.multiply(new Animated.Value(-1), touchXValue)); // TODO(TS): make sure we can map this; + + touchXValue.setValue(containerWidth); + } else { + touchXValue.setValue(0); + } // While closing the drawer when user starts gesture outside of its area (in greyed + // out part of the window), we want the drawer to follow only once finger reaches the + // edge of the drawer. + // E.g. on the diagram below drawer is illustrate by X signs and the greyed out area by + // dots. The touch gesture starts at '*' and moves left, touch path is indicated by + // an arrow pointing left + // 1) +---------------+ 2) +---------------+ 3) +---------------+ 4) +---------------+ + // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| + // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| + // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| + // |XXXXXXXX|......| |XXXXXXXX|.<-*..| |XXXXXXXX|<--*..| |XXXXX|<-----*..| + // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| + // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| + // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| + // +---------------+ +---------------+ +---------------+ +---------------+ + // + // For the above to work properly we define animated value that will keep + // start position of the gesture. Then we use that value to calculate how + // much we need to subtract from the dragX. If the gesture started on the + // greyed out area we take the distance from the edge of the drawer to the + // start position. Otherwise we don't subtract at all and the drawer be + // pulled back as soon as you start the pan. + // + // This is used only when drawerType is "front" + // + + + let translationX = dragX; + + if (drawerType === 'front') { + const startPositionX = Animated.add(touchX, Animated.multiply(new Animated.Value(-1), dragX)); + const dragOffsetFromOnStartPosition = startPositionX.interpolate({ + inputRange: [drawerWidth - 1, drawerWidth, drawerWidth + 1], + outputRange: [0, 0, 1] + }); + translationX = Animated.add(dragX, dragOffsetFromOnStartPosition); // TODO: as above + } + + this.openValue = Animated.add(translationX, drawerTranslation).interpolate({ + inputRange: [0, drawerWidth], + outputRange: [0, 1], + extrapolate: 'clamp' + }); + const gestureOptions = { + useNativeDriver: props.useNativeAnimations + }; + + if (this.props.onDrawerSlide) { + gestureOptions.listener = ev => { + var _this$props$onDrawerS, _this$props; + + const translationX = Math.floor(Math.abs(ev.nativeEvent.translationX)); + const position = translationX / this.state.containerWidth; + (_this$props$onDrawerS = (_this$props = this.props).onDrawerSlide) === null || _this$props$onDrawerS === void 0 ? void 0 : _this$props$onDrawerS.call(_this$props, position); + }; + } + + this.onGestureEvent = Animated.event([{ + nativeEvent: { + translationX: dragXValue, + x: touchXValue + } + }], gestureOptions); + }); + + _defineProperty(this, "handleContainerLayout", ({ + nativeEvent + }) => { + this.setState({ + containerWidth: nativeEvent.layout.width + }); + }); + + _defineProperty(this, "emitStateChanged", (newState, drawerWillShow) => { + var _this$props$onDrawerS2, _this$props2; + + (_this$props$onDrawerS2 = (_this$props2 = this.props).onDrawerStateChanged) === null || _this$props$onDrawerS2 === void 0 ? void 0 : _this$props$onDrawerS2.call(_this$props2, newState, drawerWillShow); + }); + + _defineProperty(this, "openingHandlerStateChange", ({ + nativeEvent + }) => { + if (nativeEvent.oldState === State.ACTIVE) { + this.handleRelease({ + nativeEvent + }); + } else if (nativeEvent.state === State.ACTIVE) { + this.emitStateChanged(DRAGGING, false); + + if (this.props.keyboardDismissMode === 'on-drag') { + Keyboard.dismiss(); + } + + if (this.props.hideStatusBar) { + StatusBar.setHidden(true, this.props.statusBarAnimation || 'slide'); + } + } + }); + + _defineProperty(this, "onTapHandlerStateChange", ({ + nativeEvent + }) => { + if (this.drawerShown && nativeEvent.oldState === State.ACTIVE && this.props.drawerLockMode !== 'locked-open') { + this.closeDrawer(); + } + }); + + _defineProperty(this, "handleRelease", ({ + nativeEvent + }) => { + const { + drawerWidth, + drawerPosition, + drawerType + } = this.props; + const { + containerWidth + } = this.state; + let { + translationX: dragX, + velocityX, + x: touchX + } = nativeEvent; + + if (drawerPosition !== 'left') { + // See description in _updateAnimatedEvent about why events are flipped + // for right-side drawer + dragX = -dragX; + touchX = containerWidth - touchX; + velocityX = -velocityX; + } + + const gestureStartX = touchX - dragX; + let dragOffsetBasedOnStart = 0; + + if (drawerType === 'front') { + dragOffsetBasedOnStart = gestureStartX > drawerWidth ? gestureStartX - drawerWidth : 0; + } + + const startOffsetX = dragX + dragOffsetBasedOnStart + (this.drawerShown ? drawerWidth : 0); + const projOffsetX = startOffsetX + DRAG_TOSS * velocityX; + const shouldOpen = projOffsetX > drawerWidth / 2; + + if (shouldOpen) { + this.animateDrawer(startOffsetX, drawerWidth, velocityX); + } else { + this.animateDrawer(startOffsetX, 0, velocityX); + } + }); + + _defineProperty(this, "updateShowing", showing => { + var _this$accessibilityIs, _this$pointerEventsVi, _this$panGestureHandl; + + this.drawerShown = showing; + (_this$accessibilityIs = this.accessibilityIsModalView.current) === null || _this$accessibilityIs === void 0 ? void 0 : _this$accessibilityIs.setNativeProps({ + accessibilityViewIsModal: showing + }); + (_this$pointerEventsVi = this.pointerEventsView.current) === null || _this$pointerEventsVi === void 0 ? void 0 : _this$pointerEventsVi.setNativeProps({ + pointerEvents: showing ? 'auto' : 'none' + }); + const { + drawerPosition, + minSwipeDistance, + edgeWidth + } = this.props; + const fromLeft = drawerPosition === 'left'; // gestureOrientation is 1 if the expected gesture is from left to right and + // -1 otherwise e.g. when drawer is on the left and is closed we expect left + // to right gesture, thus orientation will be 1. + + const gestureOrientation = (fromLeft ? 1 : -1) * (this.drawerShown ? -1 : 1); // When drawer is closed we want the hitSlop to be horizontally shorter than + // the container size by the value of SLOP. This will make it only activate + // when gesture happens not further than SLOP away from the edge + + const hitSlop = fromLeft ? { + left: 0, + width: showing ? undefined : edgeWidth + } : { + right: 0, + width: showing ? undefined : edgeWidth + }; // @ts-ignore internal API, maybe could be fixed in handler types + + (_this$panGestureHandl = this.panGestureHandler.current) === null || _this$panGestureHandl === void 0 ? void 0 : _this$panGestureHandl.setNativeProps({ + hitSlop, + activeOffsetX: gestureOrientation * minSwipeDistance + }); + }); + + _defineProperty(this, "animateDrawer", (fromValue, toValue, velocity, speed) => { + this.state.dragX.setValue(0); + this.state.touchX.setValue(this.props.drawerPosition === 'left' ? 0 : this.state.containerWidth); + + if (fromValue != null) { + let nextFramePosition = fromValue; + + if (this.props.useNativeAnimations) { + // When using native driver, we predict the next position of the + // animation because it takes one frame of a roundtrip to pass RELEASE + // event from native driver to JS before we can start animating. Without + // it, it is more noticable that the frame is dropped. + if (fromValue < toValue && velocity > 0) { + nextFramePosition = Math.min(fromValue + velocity / 60.0, toValue); + } else if (fromValue > toValue && velocity < 0) { + nextFramePosition = Math.max(fromValue + velocity / 60.0, toValue); + } + } + + this.state.drawerTranslation.setValue(nextFramePosition); + } + + const willShow = toValue !== 0; + this.updateShowing(willShow); + this.emitStateChanged(SETTLING, willShow); + + if (this.props.hideStatusBar) { + StatusBar.setHidden(willShow, this.props.statusBarAnimation || 'slide'); + } + + Animated.spring(this.state.drawerTranslation, { + velocity, + bounciness: 0, + toValue, + useNativeDriver: this.props.useNativeAnimations, + speed: speed !== null && speed !== void 0 ? speed : undefined + }).start(({ + finished + }) => { + if (finished) { + this.emitStateChanged(IDLE, willShow); + + if (willShow) { + var _this$props$onDrawerO, _this$props3; + + (_this$props$onDrawerO = (_this$props3 = this.props).onDrawerOpen) === null || _this$props$onDrawerO === void 0 ? void 0 : _this$props$onDrawerO.call(_this$props3); + } else { + var _this$props$onDrawerC, _this$props4; + + (_this$props$onDrawerC = (_this$props4 = this.props).onDrawerClose) === null || _this$props$onDrawerC === void 0 ? void 0 : _this$props$onDrawerC.call(_this$props4); + } + } + }); + }); + + _defineProperty(this, "openDrawer", (options = {}) => { + this.animateDrawer( // TODO: decide if it should be null or undefined is the proper value + undefined, this.props.drawerWidth, options.velocity ? options.velocity : 0); // We need to force the update, otherwise the overlay is not rerendered and + // it would not be clickable + + this.forceUpdate(); + }); + + _defineProperty(this, "closeDrawer", (options = {}) => { + // TODO: decide if it should be null or undefined is the proper value + this.animateDrawer(undefined, 0, options.velocity ? options.velocity : 0); // We need to force the update, otherwise the overlay is not rerendered and + // it would be still clickable + + this.forceUpdate(); + }); + + _defineProperty(this, "renderOverlay", () => { + /* Overlay styles */ + invariant(this.openValue, 'should be set'); + const overlayOpacity = this.openValue.interpolate({ + inputRange: [0, 1], + outputRange: [0, 1], + extrapolate: 'clamp' + }); + const dynamicOverlayStyles = { + opacity: overlayOpacity, + backgroundColor: this.props.overlayColor + }; + return /*#__PURE__*/React.createElement(TapGestureHandler, { + onHandlerStateChange: this.onTapHandlerStateChange + }, /*#__PURE__*/React.createElement(Animated.View, { + pointerEvents: this.drawerShown ? 'auto' : 'none', + ref: this.pointerEventsView, + style: [styles.overlay, dynamicOverlayStyles] + })); + }); + + _defineProperty(this, "renderDrawer", () => { + const { + drawerBackgroundColor, + drawerWidth, + drawerPosition, + drawerType, + drawerContainerStyle, + contentContainerStyle + } = this.props; + const fromLeft = drawerPosition === 'left'; + const drawerSlide = drawerType !== 'back'; + const containerSlide = drawerType !== 'front'; // we rely on row and row-reverse flex directions to position the drawer + // properly. Apparently for RTL these are flipped which requires us to use + // the opposite setting for the drawer to appear from left or right + // according to the drawerPosition prop + + const reverseContentDirection = I18nManager.isRTL ? fromLeft : !fromLeft; + const dynamicDrawerStyles = { + backgroundColor: drawerBackgroundColor, + width: drawerWidth + }; + const openValue = this.openValue; + invariant(openValue, 'should be set'); + let containerStyles; + + if (containerSlide) { + const containerTranslateX = openValue.interpolate({ + inputRange: [0, 1], + outputRange: fromLeft ? [0, drawerWidth] : [0, -drawerWidth], + extrapolate: 'clamp' + }); + containerStyles = { + transform: [{ + translateX: containerTranslateX + }] + }; + } + + let drawerTranslateX = 0; + + if (drawerSlide) { + const closedDrawerOffset = fromLeft ? -drawerWidth : drawerWidth; + drawerTranslateX = openValue.interpolate({ + inputRange: [0, 1], + outputRange: [closedDrawerOffset, 0], + extrapolate: 'clamp' + }); + } + + const drawerStyles = { + transform: [{ + translateX: drawerTranslateX + }], + flexDirection: reverseContentDirection ? 'row-reverse' : 'row' + }; + return /*#__PURE__*/React.createElement(Animated.View, { + style: styles.main, + onLayout: this.handleContainerLayout + }, /*#__PURE__*/React.createElement(Animated.View, { + style: [drawerType === 'front' ? styles.containerOnBack : styles.containerInFront, containerStyles, contentContainerStyle], + importantForAccessibility: this.drawerShown ? 'no-hide-descendants' : 'yes' + }, typeof this.props.children === 'function' ? this.props.children(this.openValue) : this.props.children, this.renderOverlay()), /*#__PURE__*/React.createElement(Animated.View, { + pointerEvents: "box-none", + ref: this.accessibilityIsModalView, + accessibilityViewIsModal: this.drawerShown, + style: [styles.drawerContainer, drawerStyles, drawerContainerStyle] + }, /*#__PURE__*/React.createElement(View, { + style: dynamicDrawerStyles + }, this.props.renderNavigationView(this.openValue)))); + }); + + _defineProperty(this, "setPanGestureRef", ref => { + var _this$props$onGesture, _this$props5; + + // TODO(TS): make sure it is OK taken from + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31065#issuecomment-596081842 + this.panGestureHandler.current = ref; + (_this$props$onGesture = (_this$props5 = this.props).onGestureRef) === null || _this$props$onGesture === void 0 ? void 0 : _this$props$onGesture.call(_this$props5, ref); + }); + + const _dragX = new Animated.Value(0); + + const _touchX = new Animated.Value(0); + + const _drawerTranslation = new Animated.Value(0); + + this.state = { + dragX: _dragX, + touchX: _touchX, + drawerTranslation: _drawerTranslation, + containerWidth: 0 + }; + this.updateAnimatedEvent(_props, this.state); + } + + UNSAFE_componentWillUpdate(props, state) { + if (this.props.drawerPosition !== props.drawerPosition || this.props.drawerWidth !== props.drawerWidth || this.props.drawerType !== props.drawerType || this.state.containerWidth !== state.containerWidth) { + this.updateAnimatedEvent(props, state); + } + } + + render() { + const { + drawerPosition, + drawerLockMode, + edgeWidth, + minSwipeDistance + } = this.props; + const fromLeft = drawerPosition === 'left'; // gestureOrientation is 1 if the expected gesture is from left to right and + // -1 otherwise e.g. when drawer is on the left and is closed we expect left + // to right gesture, thus orientation will be 1. + + const gestureOrientation = (fromLeft ? 1 : -1) * (this.drawerShown ? -1 : 1); // When drawer is closed we want the hitSlop to be horizontally shorter than + // the container size by the value of SLOP. This will make it only activate + // when gesture happens not further than SLOP away from the edge + + const hitSlop = fromLeft ? { + left: 0, + width: this.drawerShown ? undefined : edgeWidth + } : { + right: 0, + width: this.drawerShown ? undefined : edgeWidth + }; + return /*#__PURE__*/React.createElement(PanGestureHandler // @ts-ignore could be fixed in handler types + , { + ref: this.setPanGestureRef, + hitSlop: hitSlop, + activeOffsetX: gestureOrientation * minSwipeDistance, + failOffsetY: [-15, 15], + onGestureEvent: this.onGestureEvent, + onHandlerStateChange: this.openingHandlerStateChange, + enableTrackpadTwoFingerGesture: this.props.enableTrackpadTwoFingerGesture, + enabled: drawerLockMode !== 'locked-closed' && drawerLockMode !== 'locked-open' + }, this.renderDrawer()); + } + +} + +_defineProperty(DrawerLayout, "defaultProps", { + drawerWidth: 200, + drawerPosition: 'left', + useNativeAnimations: true, + drawerType: 'front', + edgeWidth: 20, + minSwipeDistance: 3, + overlayColor: 'rgba(0, 0, 0, 0.7)', + drawerLockMode: 'unlocked', + enableTrackpadTwoFingerGesture: false +}); + +_defineProperty(DrawerLayout, "positions", { + Left: 'left', + Right: 'right' +}); + +const styles = StyleSheet.create({ + drawerContainer: { ...StyleSheet.absoluteFillObject, + zIndex: 1001, + flexDirection: 'row' + }, + containerInFront: { ...StyleSheet.absoluteFillObject, + zIndex: 1002 + }, + containerOnBack: { ...StyleSheet.absoluteFillObject + }, + main: { + flex: 1, + zIndex: 0, + overflow: 'hidden' + }, + overlay: { ...StyleSheet.absoluteFillObject, + zIndex: 1000 + } +}); +//# sourceMappingURL=DrawerLayout.js.map \ No newline at end of file diff --git a/lib/module/components/DrawerLayout.js.map b/lib/module/components/DrawerLayout.js.map new file mode 100644 index 0000000000..15a41391e5 --- /dev/null +++ b/lib/module/components/DrawerLayout.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["DrawerLayout.tsx"],"names":["React","Component","invariant","Animated","StyleSheet","View","Keyboard","StatusBar","I18nManager","PanGestureHandler","TapGestureHandler","State","DRAG_TOSS","IDLE","DRAGGING","SETTLING","DrawerLayout","constructor","props","createRef","state","drawerPosition","drawerWidth","drawerType","dragX","dragXValue","touchX","touchXValue","drawerTranslation","containerWidth","multiply","Value","add","setValue","translationX","startPositionX","dragOffsetFromOnStartPosition","interpolate","inputRange","outputRange","openValue","extrapolate","gestureOptions","useNativeDriver","useNativeAnimations","onDrawerSlide","listener","ev","Math","floor","abs","nativeEvent","position","onGestureEvent","event","x","setState","layout","width","newState","drawerWillShow","onDrawerStateChanged","oldState","ACTIVE","handleRelease","emitStateChanged","keyboardDismissMode","dismiss","hideStatusBar","setHidden","statusBarAnimation","drawerShown","drawerLockMode","closeDrawer","velocityX","gestureStartX","dragOffsetBasedOnStart","startOffsetX","projOffsetX","shouldOpen","animateDrawer","showing","accessibilityIsModalView","current","setNativeProps","accessibilityViewIsModal","pointerEventsView","pointerEvents","minSwipeDistance","edgeWidth","fromLeft","gestureOrientation","hitSlop","left","undefined","right","panGestureHandler","activeOffsetX","fromValue","toValue","velocity","speed","nextFramePosition","min","max","willShow","updateShowing","spring","bounciness","start","finished","onDrawerOpen","onDrawerClose","options","forceUpdate","overlayOpacity","dynamicOverlayStyles","opacity","backgroundColor","overlayColor","onTapHandlerStateChange","styles","overlay","drawerBackgroundColor","drawerContainerStyle","contentContainerStyle","drawerSlide","containerSlide","reverseContentDirection","isRTL","dynamicDrawerStyles","containerStyles","containerTranslateX","transform","translateX","drawerTranslateX","closedDrawerOffset","drawerStyles","flexDirection","main","handleContainerLayout","containerOnBack","containerInFront","children","renderOverlay","drawerContainer","renderNavigationView","ref","onGestureRef","updateAnimatedEvent","UNSAFE_componentWillUpdate","render","setPanGestureRef","openingHandlerStateChange","enableTrackpadTwoFingerGesture","renderDrawer","Left","Right","create","absoluteFill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AA,IAAI,EAAE,MADW;AAEjBC,EAAAA,KAAK,EAAE;AAFU,C;;AAqcrB,MAAMpC,MAAM,GAAGrH,UAAU,CAAC0J,MAAX,CAAkB;AAC/Bb,EAAAA,eAAe,EAAE,EACf,GAAG7I,UAAU,CAAC2J,kBADC;AAEfC,IAAAA,MAAM,EAAE,IAFO;AAGftB,IAAAA,aAAa,EAAE;AAHA,GADc;AAM/BI,EAAAA,gBAAgB,EAAE,EAChB,GAAG1I,UAAU,CAAC2J,kBADE;AAEhBC,IAAAA,MAAM,EAAE;AAFQ,GANa;AAU/BnB,EAAAA,eAAe,EAAE,EACf,GAAGzI,UAAU,CAAC2J;AADC,GAVc;AAa/BpB,EAAAA,IAAI,EAAE;AACJsB,IAAAA,IAAI,EAAE,CADF;AAEJD,IAAAA,MAAM,EAAE,CAFJ;AAGJE,IAAAA,QAAQ,EAAE;AAHN,GAbyB;AAkB/BxC,EAAAA,OAAO,EAAE,EACP,GAAGtH,UAAU,CAAC2J,kBADP;AAEPC,IAAAA,MAAM,EAAE;AAFD;AAlBsB,CAAlB,CAAf","sourcesContent":["// This component is based on RN's DrawerLayoutAndroid API\n//\n// It perhaps deserves to be put in a separate repo, but since it relies on\n// react-native-gesture-handler library which isn't very popular at the moment I\n// decided to keep it here for the time being. It will allow us to move faster\n// and fix issues that may arise in gesture handler library that could be found\n// when using the drawer component\n\nimport * as React from 'react';\nimport { Component } from 'react';\nimport invariant from 'invariant';\nimport {\n Animated,\n StyleSheet,\n View,\n Keyboard,\n StatusBar,\n I18nManager,\n StatusBarAnimation,\n StyleProp,\n ViewStyle,\n LayoutChangeEvent,\n NativeSyntheticEvent,\n} from 'react-native';\n\nimport {\n GestureEvent,\n HandlerStateChangeEvent,\n} from '../handlers/gestureHandlerCommon';\nimport {\n PanGestureHandler,\n PanGestureHandlerEventPayload,\n} from '../handlers/PanGestureHandler';\nimport {\n TapGestureHandler,\n TapGestureHandlerEventPayload,\n} from '../handlers/TapGestureHandler';\nimport { State } from '../State';\n\nconst DRAG_TOSS = 0.05;\n\nconst IDLE: DrawerState = 'Idle';\nconst DRAGGING: DrawerState = 'Dragging';\nconst SETTLING: DrawerState = 'Settling';\n\nexport type DrawerPosition = 'left' | 'right';\n\nexport type DrawerState = 'Idle' | 'Dragging' | 'Settling';\n\nexport type DrawerType = 'front' | 'back' | 'slide';\n\nexport type DrawerLockMode = 'unlocked' | 'locked-closed' | 'locked-open';\n\nexport type DrawerKeyboardDismissMode = 'none' | 'on-drag';\n\nexport interface DrawerLayoutProps {\n /**\n * This attribute is present in the standard implementation already and is one\n * of the required params. Gesture handler version of DrawerLayout make it\n * possible for the function passed as `renderNavigationView` to take an\n * Animated value as a parameter that indicates the progress of drawer\n * opening/closing animation (progress value is 0 when closed and 1 when\n * opened). This can be used by the drawer component to animated its children\n * while the drawer is opening or closing.\n */\n renderNavigationView: (\n progressAnimatedValue: Animated.Value\n ) => React.ReactNode;\n\n drawerPosition?: DrawerPosition;\n\n drawerWidth?: number;\n\n drawerBackgroundColor?: string;\n\n drawerLockMode?: DrawerLockMode;\n\n keyboardDismissMode?: DrawerKeyboardDismissMode;\n\n /**\n * Called when the drawer is closed.\n */\n onDrawerClose?: () => void;\n\n /**\n * Called when the drawer is opened.\n */\n onDrawerOpen?: () => void;\n\n /**\n * Called when the status of the drawer changes.\n */\n onDrawerStateChanged?: (\n newState: DrawerState,\n drawerWillShow: boolean\n ) => void;\n useNativeAnimations?: boolean;\n\n drawerType?: DrawerType;\n\n /**\n * Defines how far from the edge of the content view the gesture should\n * activate.\n */\n edgeWidth?: number;\n\n minSwipeDistance?: number;\n\n /**\n * When set to true Drawer component will use\n * {@link https://reactnative.dev/docs/statusbar StatusBar} API to hide the OS\n * status bar whenever the drawer is pulled or when its in an \"open\" state.\n */\n hideStatusBar?: boolean;\n\n /**\n * @default 'slide'\n *\n * Can be used when hideStatusBar is set to true and will select the animation\n * used for hiding/showing the status bar. See\n * {@link https://reactnative.dev/docs/statusbar StatusBar} documentation for\n * more details\n */\n statusBarAnimation?: StatusBarAnimation;\n\n /**\n * @default black\n *\n * Color of a semi-transparent overlay to be displayed on top of the content\n * view when drawer gets open. A solid color should be used as the opacity is\n * added by the Drawer itself and the opacity of the overlay is animated (from\n * 0% to 70%).\n */\n overlayColor?: string;\n\n contentContainerStyle?: StyleProp;\n\n drawerContainerStyle?: StyleProp;\n\n /**\n * Enables two-finger gestures on supported devices, for example iPads with\n * trackpads. If not enabled the gesture will require click + drag, with\n * `enableTrackpadTwoFingerGesture` swiping with two fingers will also trigger\n * the gesture.\n */\n enableTrackpadTwoFingerGesture?: boolean;\n\n onDrawerSlide?: (position: number) => void;\n\n onGestureRef?: (ref: PanGestureHandler) => void;\n}\n\nexport type DrawerLayoutState = {\n dragX: Animated.Value;\n touchX: Animated.Value;\n drawerTranslation: Animated.Value;\n containerWidth: number;\n};\n\nexport type DrawerMovementOption = {\n velocity?: number;\n speed?: number;\n};\nexport default class DrawerLayout extends Component<\n DrawerLayoutProps,\n DrawerLayoutState\n> {\n static defaultProps = {\n drawerWidth: 200,\n drawerPosition: 'left',\n useNativeAnimations: true,\n drawerType: 'front',\n edgeWidth: 20,\n minSwipeDistance: 3,\n overlayColor: 'rgba(0, 0, 0, 0.7)',\n drawerLockMode: 'unlocked',\n enableTrackpadTwoFingerGesture: false,\n };\n\n constructor(props: DrawerLayoutProps) {\n super(props);\n\n const dragX = new Animated.Value(0);\n const touchX = new Animated.Value(0);\n const drawerTranslation = new Animated.Value(0);\n\n this.state = {\n dragX,\n touchX,\n drawerTranslation,\n containerWidth: 0,\n };\n\n this.updateAnimatedEvent(props, this.state);\n }\n\n UNSAFE_componentWillUpdate(\n props: DrawerLayoutProps,\n state: DrawerLayoutState\n ) {\n if (\n this.props.drawerPosition !== props.drawerPosition ||\n this.props.drawerWidth !== props.drawerWidth ||\n this.props.drawerType !== props.drawerType ||\n this.state.containerWidth !== state.containerWidth\n ) {\n this.updateAnimatedEvent(props, state);\n }\n }\n\n private openValue?: Animated.AnimatedInterpolation;\n private onGestureEvent?: (\n event: GestureEvent\n ) => void;\n private accessibilityIsModalView = React.createRef();\n private pointerEventsView = React.createRef();\n private panGestureHandler = React.createRef();\n private drawerShown = false;\n\n static positions = {\n Left: 'left',\n Right: 'right',\n };\n\n private updateAnimatedEvent = (\n props: DrawerLayoutProps,\n state: DrawerLayoutState\n ) => {\n // Event definition is based on\n const { drawerPosition, drawerWidth, drawerType } = props;\n const {\n dragX: dragXValue,\n touchX: touchXValue,\n drawerTranslation,\n containerWidth,\n } = state;\n\n let dragX = dragXValue;\n let touchX = touchXValue;\n\n if (drawerPosition !== 'left') {\n // Most of the code is written in a way to handle left-side drawer. In\n // order to handle right-side drawer the only thing we need to do is to\n // reverse events coming from gesture handler in a way they emulate\n // left-side drawer gestures. E.g. dragX is simply -dragX, and touchX is\n // calulcated by subtracing real touchX from the width of the container\n // (such that when touch happens at the right edge the value is simply 0)\n dragX = Animated.multiply(\n new Animated.Value(-1),\n dragXValue\n ) as Animated.Value; // TODO(TS): (for all \"as\" in this file) make sure we can map this\n touchX = Animated.add(\n new Animated.Value(containerWidth),\n Animated.multiply(new Animated.Value(-1), touchXValue)\n ) as Animated.Value; // TODO(TS): make sure we can map this;\n touchXValue.setValue(containerWidth);\n } else {\n touchXValue.setValue(0);\n }\n\n // While closing the drawer when user starts gesture outside of its area (in greyed\n // out part of the window), we want the drawer to follow only once finger reaches the\n // edge of the drawer.\n // E.g. on the diagram below drawer is illustrate by X signs and the greyed out area by\n // dots. The touch gesture starts at '*' and moves left, touch path is indicated by\n // an arrow pointing left\n // 1) +---------------+ 2) +---------------+ 3) +---------------+ 4) +---------------+\n // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|\n // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|\n // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|\n // |XXXXXXXX|......| |XXXXXXXX|.<-*..| |XXXXXXXX|<--*..| |XXXXX|<-----*..|\n // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|\n // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|\n // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|\n // +---------------+ +---------------+ +---------------+ +---------------+\n //\n // For the above to work properly we define animated value that will keep\n // start position of the gesture. Then we use that value to calculate how\n // much we need to subtract from the dragX. If the gesture started on the\n // greyed out area we take the distance from the edge of the drawer to the\n // start position. Otherwise we don't subtract at all and the drawer be\n // pulled back as soon as you start the pan.\n //\n // This is used only when drawerType is \"front\"\n //\n let translationX = dragX;\n if (drawerType === 'front') {\n const startPositionX = Animated.add(\n touchX,\n Animated.multiply(new Animated.Value(-1), dragX)\n );\n\n const dragOffsetFromOnStartPosition = startPositionX.interpolate({\n inputRange: [drawerWidth! - 1, drawerWidth!, drawerWidth! + 1],\n outputRange: [0, 0, 1],\n });\n translationX = Animated.add(\n dragX,\n dragOffsetFromOnStartPosition\n ) as Animated.Value; // TODO: as above\n }\n\n this.openValue = Animated.add(translationX, drawerTranslation).interpolate({\n inputRange: [0, drawerWidth!],\n outputRange: [0, 1],\n extrapolate: 'clamp',\n });\n\n const gestureOptions: {\n useNativeDriver: boolean;\n // TODO: make sure it is correct\n listener?: (\n ev: NativeSyntheticEvent\n ) => void;\n } = {\n useNativeDriver: props.useNativeAnimations!,\n };\n\n if (this.props.onDrawerSlide) {\n gestureOptions.listener = (ev) => {\n const translationX = Math.floor(Math.abs(ev.nativeEvent.translationX));\n const position = translationX / this.state.containerWidth;\n\n this.props.onDrawerSlide?.(position);\n };\n }\n\n this.onGestureEvent = Animated.event(\n [{ nativeEvent: { translationX: dragXValue, x: touchXValue } }],\n gestureOptions\n );\n };\n\n private handleContainerLayout = ({ nativeEvent }: LayoutChangeEvent) => {\n this.setState({ containerWidth: nativeEvent.layout.width });\n };\n\n private emitStateChanged = (\n newState: DrawerState,\n drawerWillShow: boolean\n ) => {\n this.props.onDrawerStateChanged?.(newState, drawerWillShow);\n };\n\n private openingHandlerStateChange = ({\n nativeEvent,\n }: HandlerStateChangeEvent) => {\n if (nativeEvent.oldState === State.ACTIVE) {\n this.handleRelease({ nativeEvent });\n } else if (nativeEvent.state === State.ACTIVE) {\n this.emitStateChanged(DRAGGING, false);\n if (this.props.keyboardDismissMode === 'on-drag') {\n Keyboard.dismiss();\n }\n if (this.props.hideStatusBar) {\n StatusBar.setHidden(true, this.props.statusBarAnimation || 'slide');\n }\n }\n };\n\n private onTapHandlerStateChange = ({\n nativeEvent,\n }: HandlerStateChangeEvent) => {\n if (\n this.drawerShown &&\n nativeEvent.oldState === State.ACTIVE &&\n this.props.drawerLockMode !== 'locked-open'\n ) {\n this.closeDrawer();\n }\n };\n\n private handleRelease = ({\n nativeEvent,\n }: HandlerStateChangeEvent) => {\n const { drawerWidth, drawerPosition, drawerType } = this.props;\n const { containerWidth } = this.state;\n let { translationX: dragX, velocityX, x: touchX } = nativeEvent;\n\n if (drawerPosition !== 'left') {\n // See description in _updateAnimatedEvent about why events are flipped\n // for right-side drawer\n dragX = -dragX;\n touchX = containerWidth - touchX;\n velocityX = -velocityX;\n }\n\n const gestureStartX = touchX - dragX;\n let dragOffsetBasedOnStart = 0;\n\n if (drawerType === 'front') {\n dragOffsetBasedOnStart =\n gestureStartX > drawerWidth! ? gestureStartX - drawerWidth! : 0;\n }\n\n const startOffsetX =\n dragX + dragOffsetBasedOnStart + (this.drawerShown ? drawerWidth! : 0);\n const projOffsetX = startOffsetX + DRAG_TOSS * velocityX;\n\n const shouldOpen = projOffsetX > drawerWidth! / 2;\n\n if (shouldOpen) {\n this.animateDrawer(startOffsetX, drawerWidth!, velocityX);\n } else {\n this.animateDrawer(startOffsetX, 0, velocityX);\n }\n };\n\n private updateShowing = (showing: boolean) => {\n this.drawerShown = showing;\n this.accessibilityIsModalView.current?.setNativeProps({\n accessibilityViewIsModal: showing,\n });\n this.pointerEventsView.current?.setNativeProps({\n pointerEvents: showing ? 'auto' : 'none',\n });\n const { drawerPosition, minSwipeDistance, edgeWidth } = this.props;\n const fromLeft = drawerPosition === 'left';\n // gestureOrientation is 1 if the expected gesture is from left to right and\n // -1 otherwise e.g. when drawer is on the left and is closed we expect left\n // to right gesture, thus orientation will be 1.\n const gestureOrientation =\n (fromLeft ? 1 : -1) * (this.drawerShown ? -1 : 1);\n // When drawer is closed we want the hitSlop to be horizontally shorter than\n // the container size by the value of SLOP. This will make it only activate\n // when gesture happens not further than SLOP away from the edge\n const hitSlop = fromLeft\n ? { left: 0, width: showing ? undefined : edgeWidth }\n : { right: 0, width: showing ? undefined : edgeWidth };\n // @ts-ignore internal API, maybe could be fixed in handler types\n this.panGestureHandler.current?.setNativeProps({\n hitSlop,\n activeOffsetX: gestureOrientation * minSwipeDistance!,\n });\n };\n\n private animateDrawer = (\n fromValue: number | null | undefined,\n toValue: number,\n velocity: number,\n speed?: number\n ) => {\n this.state.dragX.setValue(0);\n this.state.touchX.setValue(\n this.props.drawerPosition === 'left' ? 0 : this.state.containerWidth\n );\n\n if (fromValue != null) {\n let nextFramePosition = fromValue;\n if (this.props.useNativeAnimations) {\n // When using native driver, we predict the next position of the\n // animation because it takes one frame of a roundtrip to pass RELEASE\n // event from native driver to JS before we can start animating. Without\n // it, it is more noticable that the frame is dropped.\n if (fromValue < toValue && velocity > 0) {\n nextFramePosition = Math.min(fromValue + velocity / 60.0, toValue);\n } else if (fromValue > toValue && velocity < 0) {\n nextFramePosition = Math.max(fromValue + velocity / 60.0, toValue);\n }\n }\n this.state.drawerTranslation.setValue(nextFramePosition);\n }\n\n const willShow = toValue !== 0;\n this.updateShowing(willShow);\n this.emitStateChanged(SETTLING, willShow);\n if (this.props.hideStatusBar) {\n StatusBar.setHidden(willShow, this.props.statusBarAnimation || 'slide');\n }\n Animated.spring(this.state.drawerTranslation, {\n velocity,\n bounciness: 0,\n toValue,\n useNativeDriver: this.props.useNativeAnimations!,\n speed: speed ?? undefined,\n }).start(({ finished }) => {\n if (finished) {\n this.emitStateChanged(IDLE, willShow);\n if (willShow) {\n this.props.onDrawerOpen?.();\n } else {\n this.props.onDrawerClose?.();\n }\n }\n });\n };\n\n openDrawer = (options: DrawerMovementOption = {}) => {\n this.animateDrawer(\n // TODO: decide if it should be null or undefined is the proper value\n undefined,\n this.props.drawerWidth!,\n options.velocity ? options.velocity : 0\n );\n\n // We need to force the update, otherwise the overlay is not rerendered and\n // it would not be clickable\n this.forceUpdate();\n };\n\n closeDrawer = (options: DrawerMovementOption = {}) => {\n // TODO: decide if it should be null or undefined is the proper value\n this.animateDrawer(undefined, 0, options.velocity ? options.velocity : 0);\n\n // We need to force the update, otherwise the overlay is not rerendered and\n // it would be still clickable\n this.forceUpdate();\n };\n\n private renderOverlay = () => {\n /* Overlay styles */\n invariant(this.openValue, 'should be set');\n const overlayOpacity = this.openValue.interpolate({\n inputRange: [0, 1],\n outputRange: [0, 1],\n extrapolate: 'clamp',\n });\n const dynamicOverlayStyles = {\n opacity: overlayOpacity,\n backgroundColor: this.props.overlayColor,\n };\n\n return (\n \n \n \n );\n };\n\n private renderDrawer = () => {\n const {\n drawerBackgroundColor,\n drawerWidth,\n drawerPosition,\n drawerType,\n drawerContainerStyle,\n contentContainerStyle,\n } = this.props;\n\n const fromLeft = drawerPosition === 'left';\n const drawerSlide = drawerType !== 'back';\n const containerSlide = drawerType !== 'front';\n\n // we rely on row and row-reverse flex directions to position the drawer\n // properly. Apparently for RTL these are flipped which requires us to use\n // the opposite setting for the drawer to appear from left or right\n // according to the drawerPosition prop\n const reverseContentDirection = I18nManager.isRTL ? fromLeft : !fromLeft;\n\n const dynamicDrawerStyles = {\n backgroundColor: drawerBackgroundColor,\n width: drawerWidth,\n };\n const openValue = this.openValue;\n invariant(openValue, 'should be set');\n\n let containerStyles;\n if (containerSlide) {\n const containerTranslateX = openValue.interpolate({\n inputRange: [0, 1],\n outputRange: fromLeft ? [0, drawerWidth!] : [0, -drawerWidth!],\n extrapolate: 'clamp',\n });\n containerStyles = {\n transform: [{ translateX: containerTranslateX }],\n };\n }\n\n let drawerTranslateX: number | Animated.AnimatedInterpolation = 0;\n if (drawerSlide) {\n const closedDrawerOffset = fromLeft ? -drawerWidth! : drawerWidth!;\n drawerTranslateX = openValue.interpolate({\n inputRange: [0, 1],\n outputRange: [closedDrawerOffset, 0],\n extrapolate: 'clamp',\n });\n }\n const drawerStyles: {\n transform: { translateX: number | Animated.AnimatedInterpolation }[];\n flexDirection: 'row-reverse' | 'row';\n } = {\n transform: [{ translateX: drawerTranslateX }],\n flexDirection: reverseContentDirection ? 'row-reverse' : 'row',\n };\n\n return (\n \n \n {typeof this.props.children === 'function'\n ? this.props.children(this.openValue)\n : this.props.children}\n {this.renderOverlay()}\n \n \n \n {this.props.renderNavigationView(this.openValue as Animated.Value)}\n \n \n \n );\n };\n\n private setPanGestureRef = (ref: PanGestureHandler) => {\n // TODO(TS): make sure it is OK taken from\n // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31065#issuecomment-596081842\n (this\n .panGestureHandler as React.MutableRefObject).current = ref;\n this.props.onGestureRef?.(ref);\n };\n\n render() {\n const {\n drawerPosition,\n drawerLockMode,\n edgeWidth,\n minSwipeDistance,\n } = this.props;\n\n const fromLeft = drawerPosition === 'left';\n\n // gestureOrientation is 1 if the expected gesture is from left to right and\n // -1 otherwise e.g. when drawer is on the left and is closed we expect left\n // to right gesture, thus orientation will be 1.\n const gestureOrientation =\n (fromLeft ? 1 : -1) * (this.drawerShown ? -1 : 1);\n\n // When drawer is closed we want the hitSlop to be horizontally shorter than\n // the container size by the value of SLOP. This will make it only activate\n // when gesture happens not further than SLOP away from the edge\n const hitSlop = fromLeft\n ? { left: 0, width: this.drawerShown ? undefined : edgeWidth }\n : { right: 0, width: this.drawerShown ? undefined : edgeWidth };\n\n return (\n \n {this.renderDrawer()}\n \n );\n }\n}\n\nconst styles = StyleSheet.create({\n drawerContainer: {\n ...StyleSheet.absoluteFillObject,\n zIndex: 1001,\n flexDirection: 'row',\n },\n containerInFront: {\n ...StyleSheet.absoluteFillObject,\n zIndex: 1002,\n },\n containerOnBack: {\n ...StyleSheet.absoluteFillObject,\n },\n main: {\n flex: 1,\n zIndex: 0,\n overflow: 'hidden',\n },\n overlay: {\n ...StyleSheet.absoluteFillObject,\n zIndex: 1000,\n },\n});\n"]} \ No newline at end of file diff --git a/lib/module/components/GestureButtons.js b/lib/module/components/GestureButtons.js new file mode 100644 index 0000000000..a806bcd466 --- /dev/null +++ b/lib/module/components/GestureButtons.js @@ -0,0 +1,172 @@ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +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; } + +import * as React from 'react'; +import { Animated, Platform, processColor, StyleSheet } from 'react-native'; +import createNativeWrapper from '../handlers/createNativeWrapper'; +import GestureHandlerButton from './GestureHandlerButton'; +import { State } from '../State'; +export const RawButton = createNativeWrapper(GestureHandlerButton, { + shouldCancelWhenOutside: false, + shouldActivateOnStart: false +}); +export class BaseButton extends React.Component { + constructor(props) { + super(props); + + _defineProperty(this, "lastActive", void 0); + + _defineProperty(this, "handleEvent", ({ + nativeEvent + }) => { + const { + state, + oldState, + pointerInside + } = nativeEvent; + const active = pointerInside && state === State.ACTIVE; + + if (active !== this.lastActive && this.props.onActiveStateChange) { + this.props.onActiveStateChange(active); + } + + if (oldState === State.ACTIVE && state !== State.CANCELLED && this.lastActive && this.props.onPress) { + this.props.onPress(active); + } + + this.lastActive = active; + }); + + _defineProperty(this, "onHandlerStateChange", e => { + var _this$props$onHandler, _this$props; + + (_this$props$onHandler = (_this$props = this.props).onHandlerStateChange) === null || _this$props$onHandler === void 0 ? void 0 : _this$props$onHandler.call(_this$props, e); + this.handleEvent(e); + }); + + _defineProperty(this, "onGestureEvent", e => { + var _this$props$onGesture, _this$props2; + + (_this$props$onGesture = (_this$props2 = this.props).onGestureEvent) === null || _this$props$onGesture === void 0 ? void 0 : _this$props$onGesture.call(_this$props2, e); + this.handleEvent(e); // TODO: maybe it is not correct + }); + + this.lastActive = false; + } + + render() { + const { + rippleColor, + ...rest + } = this.props; + return /*#__PURE__*/React.createElement(RawButton, _extends({ + rippleColor: processColor(rippleColor) + }, rest, { + onGestureEvent: this.onGestureEvent, + onHandlerStateChange: this.onHandlerStateChange + })); + } + +} +const AnimatedBaseButton = Animated.createAnimatedComponent(BaseButton); +const btnStyles = StyleSheet.create({ + underlay: { + position: 'absolute', + left: 0, + right: 0, + bottom: 0, + top: 0 + } +}); +export class RectButton extends React.Component { + constructor(props) { + super(props); + + _defineProperty(this, "opacity", void 0); + + _defineProperty(this, "onActiveStateChange", active => { + var _this$props$onActiveS, _this$props3; + + if (Platform.OS !== 'android') { + this.opacity.setValue(active ? this.props.activeOpacity : 0); + } + + (_this$props$onActiveS = (_this$props3 = this.props).onActiveStateChange) === null || _this$props$onActiveS === void 0 ? void 0 : _this$props$onActiveS.call(_this$props3, active); + }); + + this.opacity = new Animated.Value(0); + } + + render() { + const { + children, + style, + ...rest + } = this.props; + const resolvedStyle = StyleSheet.flatten(style !== null && style !== void 0 ? style : {}); + return /*#__PURE__*/React.createElement(BaseButton, _extends({}, rest, { + style: resolvedStyle, + onActiveStateChange: this.onActiveStateChange + }), /*#__PURE__*/React.createElement(Animated.View, { + style: [btnStyles.underlay, { + opacity: this.opacity, + backgroundColor: this.props.underlayColor, + borderRadius: resolvedStyle.borderRadius, + borderTopLeftRadius: resolvedStyle.borderTopLeftRadius, + borderTopRightRadius: resolvedStyle.borderTopRightRadius, + borderBottomLeftRadius: resolvedStyle.borderBottomLeftRadius, + borderBottomRightRadius: resolvedStyle.borderBottomRightRadius + }] + }), children); + } + +} + +_defineProperty(RectButton, "defaultProps", { + activeOpacity: 0.105, + underlayColor: 'black' +}); + +export class BorderlessButton extends React.Component { + constructor(props) { + super(props); + + _defineProperty(this, "opacity", void 0); + + _defineProperty(this, "onActiveStateChange", active => { + var _this$props$onActiveS2, _this$props4; + + if (Platform.OS !== 'android') { + this.opacity.setValue(active ? this.props.activeOpacity : 1); + } + + (_this$props$onActiveS2 = (_this$props4 = this.props).onActiveStateChange) === null || _this$props$onActiveS2 === void 0 ? void 0 : _this$props$onActiveS2.call(_this$props4, active); + }); + + this.opacity = new Animated.Value(1); + } + + render() { + const { + children, + style, + ...rest + } = this.props; + return /*#__PURE__*/React.createElement(AnimatedBaseButton, _extends({}, rest, { + onActiveStateChange: this.onActiveStateChange, + style: [style, Platform.OS === 'ios' && { + opacity: this.opacity + }] + }), children); + } + +} + +_defineProperty(BorderlessButton, "defaultProps", { + activeOpacity: 0.3, + borderless: true +}); + +export { default as PureNativeButton } from './GestureHandlerButton'; +//# sourceMappingURL=GestureButtons.js.map \ No newline at end of file diff --git a/lib/module/components/GestureButtons.js.map b/lib/module/components/GestureButtons.js.map new file mode 100644 index 0000000000..5b9832f524 --- /dev/null +++ b/lib/module/components/GestureButtons.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureButtons.tsx"],"names":["React","Animated","Platform","processColor","StyleSheet","createNativeWrapper","GestureHandlerButton","State","RawButton","shouldCancelWhenOutside","shouldActivateOnStart","BaseButton","Component","constructor","props","nativeEvent","state","oldState","pointerInside","active","ACTIVE","lastActive","onActiveStateChange","CANCELLED","onPress","e","onHandlerStateChange","handleEvent","onGestureEvent","render","rippleColor","rest","AnimatedBaseButton","createAnimatedComponent","btnStyles","create","underlay","position","left","right","bottom","top","RectButton","OS","opacity","setValue","activeOpacity","Value","children","style","resolvedStyle","flatten","backgroundColor","underlayColor","borderRadius","borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius","BorderlessButton","borderless","default","PureNativeButton"],"mappings":";;;;AAAA,OAAO,KAAKA,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AG,KAAKL,KAAL,CAAWgC,aAAd,GAA+B,CAA3D;AACD;;AAED,qDAAKhC,KAAL,EAAWQ,mBAAX,qGAAiCH,MAAjC;AACD,KAXyC;;AAExC,SAAKyB,OAAL,GAAe,IAAI3C,QAAQ,CAAC8C,KAAb,CAAmB,CAAnB,CAAf;AACD;;AAUDlB,EAAAA,MAAM,GAAG;AACP,UAAM;AAAEmB,MAAAA,QAAF;AAAYC,MAAAA,KAAZ;AAAmB,SAAGlB;AAAtB,QAA+B,KAAKjB,KAA1C;AAEA,wBACE,oBAAC,kBAAD,eACMiB,IADN;AAEE,MAAA,mBAAmB,EAAE,KAAKT,mBAF5B;AAGE,MAAA,KAAK,EAAE,CAAC2B,KAAD,EAAQ/C,QAAQ,CAACyC,EAAT,KAAgB,KAAhB,IAAyB;AAAEC,QAAAA,OAAO,EAAE,KAAKA;AAAhB,OAAjC;AAHT,QAIGI,QAJH,CADF;AAQD;;AAhC0E;;gBAAhEW,gB,kBACW;AACpBb,EAAAA,aAAa,EAAE,GADK;AAEpBc,EAAAA,UAAU,EAAE;AAFQ,C;;AAkCxB,SAASC,OAAO,IAAIC,gBAApB,QAA4C,wBAA5C","sourcesContent":["import * as React from 'react';\nimport {\n Animated,\n Platform,\n processColor,\n StyleSheet,\n StyleProp,\n ViewStyle,\n} from 'react-native';\n\nimport createNativeWrapper from '../handlers/createNativeWrapper';\nimport GestureHandlerButton from './GestureHandlerButton';\nimport { State } from '../State';\n\nimport {\n GestureEvent,\n HandlerStateChangeEvent,\n} from '../handlers/gestureHandlerCommon';\nimport {\n NativeViewGestureHandlerPayload,\n NativeViewGestureHandlerProps,\n} from '../handlers/NativeViewGestureHandler';\n\nexport interface RawButtonProps extends NativeViewGestureHandlerProps {\n /**\n * Defines if more than one button could be pressed simultaneously. By default\n * set true.\n */\n exclusive?: boolean;\n // TODO: we should transform props in `createNativeWrapper`\n\n /**\n * Android only.\n *\n * Defines color of native ripple animation used since API level 21.\n */\n rippleColor?: any; // it was present in BaseButtonProps before but is used here in code\n}\n\nexport interface BaseButtonProps extends RawButtonProps {\n /**\n * Called when the button gets pressed (analogous to `onPress` in\n * `TouchableHighlight` from RN core).\n */\n onPress?: (pointerInside: boolean) => void;\n\n /**\n * Called when button changes from inactive to active and vice versa. It\n * passes active state as a boolean variable as a first parameter for that\n * method.\n */\n onActiveStateChange?: (active: boolean) => void;\n style?: StyleProp;\n testID?: string;\n}\n\nexport interface RectButtonProps extends BaseButtonProps {\n /**\n * Background color that will be dimmed when button is in active state.\n */\n underlayColor?: string;\n\n /**\n * iOS only.\n *\n * Opacity applied to the underlay when button is in active state.\n */\n activeOpacity?: number;\n}\n\nexport interface BorderlessButtonProps extends BaseButtonProps {\n /**\n * Android only.\n *\n * Set this to false if you want the ripple animation to render only within view bounds.\n */\n borderless?: boolean;\n\n /**\n * iOS only.\n *\n * Opacity applied to the button when it is in an active state.\n */\n activeOpacity?: number;\n}\n\nexport const RawButton = createNativeWrapper(GestureHandlerButton, {\n shouldCancelWhenOutside: false,\n shouldActivateOnStart: false,\n});\n\nexport class BaseButton extends React.Component {\n private lastActive: boolean;\n\n constructor(props: BaseButtonProps) {\n super(props);\n this.lastActive = false;\n }\n\n private handleEvent = ({\n nativeEvent,\n }: HandlerStateChangeEvent) => {\n const { state, oldState, pointerInside } = nativeEvent;\n const active = pointerInside && state === State.ACTIVE;\n\n if (active !== this.lastActive && this.props.onActiveStateChange) {\n this.props.onActiveStateChange(active);\n }\n\n if (\n oldState === State.ACTIVE &&\n state !== State.CANCELLED &&\n this.lastActive &&\n this.props.onPress\n ) {\n this.props.onPress(active);\n }\n\n this.lastActive = active;\n };\n\n // Normally, the parent would execute it's handler first, then forward the\n // event to listeners. However, here our handler is virtually only forwarding\n // events to listeners, so we reverse the order to keep the proper order of\n // the callbacks (from \"raw\" ones to \"processed\").\n private onHandlerStateChange = (\n e: HandlerStateChangeEvent\n ) => {\n this.props.onHandlerStateChange?.(e);\n this.handleEvent(e);\n };\n\n private onGestureEvent = (\n e: GestureEvent\n ) => {\n this.props.onGestureEvent?.(e);\n this.handleEvent(\n e as HandlerStateChangeEvent\n ); // TODO: maybe it is not correct\n };\n\n render() {\n const { rippleColor, ...rest } = this.props;\n\n return (\n \n );\n }\n}\n\nconst AnimatedBaseButton = Animated.createAnimatedComponent(BaseButton);\n\nconst btnStyles = StyleSheet.create({\n underlay: {\n position: 'absolute',\n left: 0,\n right: 0,\n bottom: 0,\n top: 0,\n },\n});\n\nexport class RectButton extends React.Component {\n static defaultProps = {\n activeOpacity: 0.105,\n underlayColor: 'black',\n };\n\n private opacity: Animated.Value;\n\n constructor(props: RectButtonProps) {\n super(props);\n this.opacity = new Animated.Value(0);\n }\n\n private onActiveStateChange = (active: boolean) => {\n if (Platform.OS !== 'android') {\n this.opacity.setValue(active ? this.props.activeOpacity! : 0);\n }\n\n this.props.onActiveStateChange?.(active);\n };\n\n render() {\n const { children, style, ...rest } = this.props;\n\n const resolvedStyle = StyleSheet.flatten(style ?? {});\n\n return (\n \n \n {children}\n \n );\n }\n}\n\nexport class BorderlessButton extends React.Component {\n static defaultProps = {\n activeOpacity: 0.3,\n borderless: true,\n };\n\n private opacity: Animated.Value;\n\n constructor(props: BorderlessButtonProps) {\n super(props);\n this.opacity = new Animated.Value(1);\n }\n\n private onActiveStateChange = (active: boolean) => {\n if (Platform.OS !== 'android') {\n this.opacity.setValue(active ? this.props.activeOpacity! : 1);\n }\n\n this.props.onActiveStateChange?.(active);\n };\n\n render() {\n const { children, style, ...rest } = this.props;\n\n return (\n \n {children}\n \n );\n }\n}\n\nexport { default as PureNativeButton } from './GestureHandlerButton';\n"]} \ No newline at end of file diff --git a/lib/module/components/GestureComponents.js b/lib/module/components/GestureComponents.js new file mode 100644 index 0000000000..fa887c2b33 --- /dev/null +++ b/lib/module/components/GestureComponents.js @@ -0,0 +1,53 @@ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +import * as React from 'react'; +import { ScrollView as RNScrollView, Switch as RNSwitch, TextInput as RNTextInput, DrawerLayoutAndroid as RNDrawerLayoutAndroid, FlatList as RNFlatList } from 'react-native'; +import createNativeWrapper from '../handlers/createNativeWrapper'; +import { nativeViewProps } from '../handlers/NativeViewGestureHandler'; +export const ScrollView = createNativeWrapper(RNScrollView, { + disallowInterruption: true, + shouldCancelWhenOutside: false +}); // backward type compatibility with https://github.com/software-mansion/react-native-gesture-handler/blob/db78d3ca7d48e8ba57482d3fe9b0a15aa79d9932/react-native-gesture-handler.d.ts#L440-L457 +// include methods of wrapped components by creating an intersection type with the RN component instead of duplicating them. +// eslint-disable-next-line @typescript-eslint/no-redeclare + +export const Switch = createNativeWrapper(RNSwitch, { + shouldCancelWhenOutside: false, + shouldActivateOnStart: true, + disallowInterruption: true +}); // eslint-disable-next-line @typescript-eslint/no-redeclare + +export const TextInput = createNativeWrapper(RNTextInput); // eslint-disable-next-line @typescript-eslint/no-redeclare + +export const DrawerLayoutAndroid = createNativeWrapper(RNDrawerLayoutAndroid, { + disallowInterruption: true +}); // eslint-disable-next-line @typescript-eslint/no-redeclare + +export const FlatList = /*#__PURE__*/React.forwardRef((props, ref) => { + const flatListProps = {}; + const scrollViewProps = {}; + + for (const [propName, value] of Object.entries(props)) { + // https://github.com/microsoft/TypeScript/issues/26255 + if (nativeViewProps.includes(propName)) { + // @ts-ignore - this function cannot have generic type so we have to ignore this error + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + scrollViewProps[propName] = value; + } else { + // @ts-ignore - this function cannot have generic type so we have to ignore this error + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + flatListProps[propName] = value; + } + } + + return ( + /*#__PURE__*/ + // @ts-ignore - this function cannot have generic type so we have to ignore this error + React.createElement(RNFlatList, _extends({ + ref: ref + }, flatListProps, { + renderScrollComponent: scrollProps => /*#__PURE__*/React.createElement(ScrollView, _extends({}, scrollProps, scrollViewProps)) + })) + ); +}); // eslint-disable-next-line @typescript-eslint/no-redeclare +//# sourceMappingURL=GestureComponents.js.map \ No newline at end of file diff --git a/lib/module/components/GestureComponents.js.map b/lib/module/components/GestureComponents.js.map new file mode 100644 index 0000000000..ccd5bf3e05 --- /dev/null +++ b/lib/module/components/GestureComponents.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureComponents.tsx"],"names":["React","ScrollView","RNScrollView","Switch","RNSwitch","TextInput","RNTextInput","DrawerLayoutAndroid","RNDrawerLayoutAndroid","FlatList","RNFlatList","createNativeWrapper","nativeViewProps","disallowInterruption","shouldCancelWhenOutside","shouldActivateOnStart","forwardRef","props","ref","flatListProps","scrollViewProps","propName","value","Object","entries","includes","scrollProps"],"mappings":";;AAAA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AAOA,SACEC,UAAU,IAAIC,YADhB,EAGEC,MAAM,IAAIC,QAHZ,EAKEC,SAAS,IAAIC,WALf,EAOEC,mBAAmB,IAAIC,qBAPzB,EASEC,QAAQ,IAAIC,UATd,QAWO,cAXP;AAaA,OAAOC,mBAAP,MAAgC,iCAAhC;AAEA,SAEEC,eAFF,QAGO,sCAHP;AAKA,OAAO,MAAMX,UAAU,GAAGU,mBAAmB,CAE3CT,YAF2C,EAE7B;AACdW,EAAAA,oBAAoB,EAAE,IADR;AAEdC,EAAAA,uBAAuB,EAAE;AAFX,CAF6B,CAAtC,C,CAMP;AACA;AACA;;AAGA,OAAO,MAAMX,MAAM,GAAGQ,mBAAmB,CAAgBP,QAAhB,EAA0B;AACjEU,EAAAA,uBAAuB,EAAE,KADwC;AAEjEC,EAAAA,qBAAqB,EAAE,IAF0C;AAGjEF,EAAAA,oBAAoB,EAAE;AAH2C,CAA1B,CAAlC,C,CAKP;;AAGA,OAAO,MAAMR,SAAS,GAAGM,mBAAmB,CAAmBL,WAAnB,CAArC,C,CACP;;AAGA,OAAO,MAAMC,mBAAmB,GAAGI,mBAAmB,CAEpDH,qBAFoD,EAE7B;AAAEK,EAAAA,oBAAoB,EAAE;AAAxB,CAF6B,CAA/C,C,CAGP;;AAIA,OAAO,MAAMJ,QAAQ,gBAAGT,KAAK,CAACgB,UAAN,CAAiB,CAACC,KAAD,EAAQC,GAAR,KAAgB;AACvD,QAAMC,aAAa,GAAG,EAAtB;AACA,QAAMC,eAAe,GAAG,EAAxB;;AACA,OAAK,MAAM,CAACC,QAAD,EAAWC,KAAX,CAAX,IAAgCC,MAAM,CAACC,OAAP,CAAeP,KAAf,CAAhC,EAAuD;AACrD;AACA,QAAKL,eAAD,CAAuCa,QAAvC,CAAgDJ,QAAhD,CAAJ,EAA+D;AAC7D;AACA;AACAD,MAAAA,eAAe,CAACC,QAAD,CAAf,GAA4BC,KAA5B;AACD,KAJD,MAIO;AACL;AACA;AACAH,MAAAA,aAAa,CAACE,QAAD,CAAb,GAA0BC,KAA1B;AACD;AACF;;AACD;AAAA;AACE;AACA,wBAAC,UAAD;AACE,MAAA,GAAG,EAAEJ;AADP,OAEMC,aAFN;AAGE,MAAA,qBAAqB,EAAGO,WAAD,iBACrB,oBAAC,UAAD,eAAqBA,WAArB,EAAqCN,eAArC;AAJJ;AAFF;AAUD,CAzBuB,CAAjB,C,CAiCP","sourcesContent":["import * as React from 'react';\nimport {\n PropsWithChildren,\n ForwardedRef,\n RefAttributes,\n ReactElement,\n} from 'react';\nimport {\n ScrollView as RNScrollView,\n ScrollViewProps as RNScrollViewProps,\n Switch as RNSwitch,\n SwitchProps as RNSwitchProps,\n TextInput as RNTextInput,\n TextInputProps as RNTextInputProps,\n DrawerLayoutAndroid as RNDrawerLayoutAndroid,\n DrawerLayoutAndroidProps as RNDrawerLayoutAndroidProps,\n FlatList as RNFlatList,\n FlatListProps as RNFlatListProps,\n} from 'react-native';\n\nimport createNativeWrapper from '../handlers/createNativeWrapper';\n\nimport {\n NativeViewGestureHandlerProps,\n nativeViewProps,\n} from '../handlers/NativeViewGestureHandler';\n\nexport const ScrollView = createNativeWrapper<\n PropsWithChildren\n>(RNScrollView, {\n disallowInterruption: true,\n shouldCancelWhenOutside: false,\n});\n// backward type compatibility with https://github.com/software-mansion/react-native-gesture-handler/blob/db78d3ca7d48e8ba57482d3fe9b0a15aa79d9932/react-native-gesture-handler.d.ts#L440-L457\n// include methods of wrapped components by creating an intersection type with the RN component instead of duplicating them.\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type ScrollView = typeof ScrollView & RNScrollView;\n\nexport const Switch = createNativeWrapper(RNSwitch, {\n shouldCancelWhenOutside: false,\n shouldActivateOnStart: true,\n disallowInterruption: true,\n});\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type Switch = typeof Switch & RNSwitch;\n\nexport const TextInput = createNativeWrapper(RNTextInput);\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type TextInput = typeof TextInput & RNTextInput;\n\nexport const DrawerLayoutAndroid = createNativeWrapper<\n PropsWithChildren\n>(RNDrawerLayoutAndroid, { disallowInterruption: true });\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type DrawerLayoutAndroid = typeof DrawerLayoutAndroid &\n RNDrawerLayoutAndroid;\n\nexport const FlatList = React.forwardRef((props, ref) => {\n const flatListProps = {};\n const scrollViewProps = {};\n for (const [propName, value] of Object.entries(props)) {\n // https://github.com/microsoft/TypeScript/issues/26255\n if ((nativeViewProps as readonly string[]).includes(propName)) {\n // @ts-ignore - this function cannot have generic type so we have to ignore this error\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n scrollViewProps[propName] = value;\n } else {\n // @ts-ignore - this function cannot have generic type so we have to ignore this error\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n flatListProps[propName] = value;\n }\n }\n return (\n // @ts-ignore - this function cannot have generic type so we have to ignore this error\n (\n \n )}\n />\n );\n}) as (\n props: PropsWithChildren<\n RNFlatListProps &\n RefAttributes> &\n NativeViewGestureHandlerProps\n >,\n ref: ForwardedRef>\n) => ReactElement | null;\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type FlatList = typeof FlatList & RNFlatList;\n"]} \ No newline at end of file diff --git a/lib/module/components/GestureComponents.web.js b/lib/module/components/GestureComponents.web.js new file mode 100644 index 0000000000..1d1b06afc8 --- /dev/null +++ b/lib/module/components/GestureComponents.web.js @@ -0,0 +1,25 @@ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +import * as React from 'react'; +import { DrawerLayoutAndroid as RNDrawerLayoutAndroid, FlatList as RNFlatList, Switch as RNSwitch, TextInput as RNTextInput, ScrollView as RNScrollView } from 'react-native'; +import createNativeWrapper from '../handlers/createNativeWrapper'; +export const ScrollView = createNativeWrapper(RNScrollView, { + disallowInterruption: true +}); +export const Switch = createNativeWrapper(RNSwitch, { + shouldCancelWhenOutside: false, + shouldActivateOnStart: true, + disallowInterruption: true +}); +export const TextInput = createNativeWrapper(RNTextInput); +export const DrawerLayoutAndroid = createNativeWrapper(RNDrawerLayoutAndroid, { + disallowInterruption: true +}); // @ts-ignore -- TODO(TS) to investigate if it's needed + +DrawerLayoutAndroid.positions = RNDrawerLayoutAndroid.positions; +export const FlatList = /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/React.createElement(RNFlatList, _extends({ + ref: ref +}, props, { + renderScrollComponent: scrollProps => /*#__PURE__*/React.createElement(ScrollView, scrollProps) +}))); +//# sourceMappingURL=GestureComponents.web.js.map \ No newline at end of file diff --git a/lib/module/components/GestureComponents.web.js.map b/lib/module/components/GestureComponents.web.js.map new file mode 100644 index 0000000000..535b691ac1 --- /dev/null +++ b/lib/module/components/GestureComponents.web.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureComponents.web.tsx"],"names":["React","DrawerLayoutAndroid","RNDrawerLayoutAndroid","FlatList","RNFlatList","Switch","RNSwitch","TextInput","RNTextInput","ScrollView","RNScrollView","createNativeWrapper","disallowInterruption","shouldCancelWhenOutside","shouldActivateOnStart","positions","forwardRef","props","ref","scrollProps"],"mappings":";;AAAA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AACA,SACEC,mBAAmB,IAAIC,qBADzB,EAEEC,QAAQ,IAAIC,UAFd,EAGEC,MAAM,IAAIC,QAHZ,EAIEC,SAAS,IAAIC,WAJf,EAKEC,UAAU,IAAIC,YALhB,QAOO,cAPP;AASA,OAAOC,mBAAP,MAAgC,iCAAhC;AAEA,OAAO,MAAMF,UAAU,GAAGE,mBAAmB,CAACD,YAAD,EAAe;AAC1DE,EAAAA,oBAAoB,EAAE;AADoC,CAAf,CAAtC;AAIP,OAAO,MAAMP,MAAM,GAAGM,mBAAmB,CAACL,QAAD,EAAW;AAClDO,EAAAA,uBAAuB,EAAE,KADyB;AAElDC,EAAAA,qBAAqB,EAAE,IAF2B;AAGlDF,EAAAA,oBAAoB,EAAE;AAH4B,CAAX,CAAlC;AAKP,OAAO,MAAML,SAAS,GAAGI,mBAAmB,CAACH,WAAD,CAArC;AACP,OAAO,MAAMP,mBAAmB,GAAGU,mBAAmB,CAACT,qBAAD,EAAwB;AAC5EU,EAAAA,oBAAoB,EAAE;AADsD,CAAxB,CAA/C,C,CAGP;;AACAX,mBAAmB,CAACc,SAApB,GAAgCb,qBAAqB,CAACa,SAAtD;AAEA,OAAO,MAAMZ,QAAQ,gBAAGH,KAAK,CAACgB,UAAN,CACtB,CAAoBC,KAApB,EAAiDC,GAAjD,kBACE,oBAAC,UAAD;AACE,EAAA,GAAG,EAAEA;AADP,GAEMD,KAFN;AAGE,EAAA,qBAAqB,EAAGE,WAAD,iBAAiB,oBAAC,UAAD,EAAgBA,WAAhB;AAH1C,GAFoB,CAAjB","sourcesContent":["import * as React from 'react';\nimport {\n DrawerLayoutAndroid as RNDrawerLayoutAndroid,\n FlatList as RNFlatList,\n Switch as RNSwitch,\n TextInput as RNTextInput,\n ScrollView as RNScrollView,\n FlatListProps,\n} from 'react-native';\n\nimport createNativeWrapper from '../handlers/createNativeWrapper';\n\nexport const ScrollView = createNativeWrapper(RNScrollView, {\n disallowInterruption: true,\n});\n\nexport const Switch = createNativeWrapper(RNSwitch, {\n shouldCancelWhenOutside: false,\n shouldActivateOnStart: true,\n disallowInterruption: true,\n});\nexport const TextInput = createNativeWrapper(RNTextInput);\nexport const DrawerLayoutAndroid = createNativeWrapper(RNDrawerLayoutAndroid, {\n disallowInterruption: true,\n});\n// @ts-ignore -- TODO(TS) to investigate if it's needed\nDrawerLayoutAndroid.positions = RNDrawerLayoutAndroid.positions;\n\nexport const FlatList = React.forwardRef(\n (props: FlatListProps, ref: any) => (\n }\n />\n )\n);\n"]} \ No newline at end of file diff --git a/lib/module/components/GestureHandlerButton.js b/lib/module/components/GestureHandlerButton.js new file mode 100644 index 0000000000..a0af96bedd --- /dev/null +++ b/lib/module/components/GestureHandlerButton.js @@ -0,0 +1,4 @@ +import { requireNativeComponent } from 'react-native'; +const RNGestureHandlerButton = requireNativeComponent('RNGestureHandlerButton'); +export default RNGestureHandlerButton; +//# sourceMappingURL=GestureHandlerButton.js.map \ No newline at end of file diff --git a/lib/module/components/GestureHandlerButton.js.map b/lib/module/components/GestureHandlerButton.js.map new file mode 100644 index 0000000000..1bc9f58caa --- /dev/null +++ b/lib/module/components/GestureHandlerButton.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureHandlerButton.tsx"],"names":["requireNativeComponent","RNGestureHandlerButton"],"mappings":"AAAA,SAAwBA,sBAAxB,QAAsD,cAAtD;AAEA,MAAMC,sBAAqD,GAAGD,sBAAsB,CAClF,wBADkF,CAApF;AAIA,eAAeC,sBAAf","sourcesContent":["import { HostComponent, requireNativeComponent } from 'react-native';\nimport { RawButtonProps } from './GestureButtons';\nconst RNGestureHandlerButton: HostComponent = requireNativeComponent(\n 'RNGestureHandlerButton'\n);\n\nexport default RNGestureHandlerButton;\n"]} \ No newline at end of file diff --git a/lib/module/components/GestureHandlerButton.web.js b/lib/module/components/GestureHandlerButton.web.js new file mode 100644 index 0000000000..59099baa46 --- /dev/null +++ b/lib/module/components/GestureHandlerButton.web.js @@ -0,0 +1,9 @@ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +import * as React from 'react'; +import { View } from 'react-native'; +export default /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/React.createElement(View, _extends({ + ref: ref, + accessibilityRole: "button" +}, props))); +//# sourceMappingURL=GestureHandlerButton.web.js.map \ No newline at end of file diff --git a/lib/module/components/GestureHandlerButton.web.js.map b/lib/module/components/GestureHandlerButton.web.js.map new file mode 100644 index 0000000000..0ad4288783 --- /dev/null +++ b/lib/module/components/GestureHandlerButton.web.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureHandlerButton.web.tsx"],"names":["React","View","forwardRef","props","ref"],"mappings":";;AAAA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AACA,SAASC,IAAT,QAAqB,cAArB;AAEA,4BAAeD,KAAK,CAACE,UAAN,CAAuB,CAACC,KAAD,EAAQC,GAAR,kBACpC,oBAAC,IAAD;AAAM,EAAA,GAAG,EAAEA,GAAX;AAAgB,EAAA,iBAAiB,EAAC;AAAlC,GAA+CD,KAA/C,EADa,CAAf","sourcesContent":["import * as React from 'react';\nimport { View } from 'react-native';\n\nexport default React.forwardRef((props, ref) => (\n \n));\n"]} \ No newline at end of file diff --git a/lib/module/components/Swipeable.js b/lib/module/components/Swipeable.js new file mode 100644 index 0000000000..e2172be2ae --- /dev/null +++ b/lib/module/components/Swipeable.js @@ -0,0 +1,347 @@ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +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; } + +// Similarily to the DrawerLayout component this deserves to be put in a +// separate repo. Although, keeping it here for the time being will allow us to +// move faster and fix possible issues quicker +import * as React from 'react'; +import { Component } from 'react'; +import { Animated, StyleSheet, View, I18nManager } from 'react-native'; +import { PanGestureHandler } from '../handlers/PanGestureHandler'; +import { TapGestureHandler } from '../handlers/TapGestureHandler'; +import { State } from '../State'; +const DRAG_TOSS = 0.05; +export default class Swipeable extends Component { + constructor(_props) { + super(_props); + + _defineProperty(this, "onGestureEvent", void 0); + + _defineProperty(this, "transX", void 0); + + _defineProperty(this, "showLeftAction", void 0); + + _defineProperty(this, "leftActionTranslate", void 0); + + _defineProperty(this, "showRightAction", void 0); + + _defineProperty(this, "rightActionTranslate", void 0); + + _defineProperty(this, "updateAnimatedEvent", (props, state) => { + const { + friction, + overshootFriction + } = props; + const { + dragX, + rowTranslation, + leftWidth = 0, + rowWidth = 0 + } = state; + const { + rightOffset = rowWidth + } = state; + const rightWidth = Math.max(0, rowWidth - rightOffset); + const { + overshootLeft = leftWidth > 0, + overshootRight = rightWidth > 0 + } = props; + const transX = Animated.add(rowTranslation, dragX.interpolate({ + inputRange: [0, friction], + outputRange: [0, 1] + })).interpolate({ + inputRange: [-rightWidth - 1, -rightWidth, leftWidth, leftWidth + 1], + outputRange: [-rightWidth - (overshootRight ? 1 / overshootFriction : 0), -rightWidth, leftWidth, leftWidth + (overshootLeft ? 1 / overshootFriction : 0)] + }); + this.transX = transX; + this.showLeftAction = leftWidth > 0 ? transX.interpolate({ + inputRange: [-1, 0, leftWidth], + outputRange: [0, 0, 1] + }) : new Animated.Value(0); + this.leftActionTranslate = this.showLeftAction.interpolate({ + inputRange: [0, Number.MIN_VALUE], + outputRange: [-10000, 0], + extrapolate: 'clamp' + }); + this.showRightAction = rightWidth > 0 ? transX.interpolate({ + inputRange: [-rightWidth, 0, 1], + outputRange: [1, 0, 0] + }) : new Animated.Value(0); + this.rightActionTranslate = this.showRightAction.interpolate({ + inputRange: [0, Number.MIN_VALUE], + outputRange: [-10000, 0], + extrapolate: 'clamp' + }); + }); + + _defineProperty(this, "onTapHandlerStateChange", ({ + nativeEvent + }) => { + if (nativeEvent.oldState === State.ACTIVE) { + this.close(); + } + }); + + _defineProperty(this, "onHandlerStateChange", ev => { + if (ev.nativeEvent.oldState === State.ACTIVE) { + this.handleRelease(ev); + } + }); + + _defineProperty(this, "handleRelease", ev => { + const { + velocityX, + translationX: dragX + } = ev.nativeEvent; + const { + leftWidth = 0, + rowWidth = 0, + rowState + } = this.state; + const { + rightOffset = rowWidth + } = this.state; + const rightWidth = rowWidth - rightOffset; + const { + friction, + leftThreshold = leftWidth / 2, + rightThreshold = rightWidth / 2 + } = this.props; + const startOffsetX = this.currentOffset() + dragX / friction; + const translationX = (dragX + DRAG_TOSS * velocityX) / friction; + let toValue = 0; + + if (rowState === 0) { + if (translationX > leftThreshold) { + toValue = leftWidth; + } else if (translationX < -rightThreshold) { + toValue = -rightWidth; + } + } else if (rowState === 1) { + // swiped to left + if (translationX > -leftThreshold) { + toValue = leftWidth; + } + } else { + // swiped to right + if (translationX < rightThreshold) { + toValue = -rightWidth; + } + } + + this.animateRow(startOffsetX, toValue, velocityX / friction); + }); + + _defineProperty(this, "animateRow", (fromValue, toValue, velocityX) => { + const { + dragX, + rowTranslation + } = this.state; + dragX.setValue(0); + rowTranslation.setValue(fromValue); + this.setState({ + rowState: Math.sign(toValue) + }); + Animated.spring(rowTranslation, { + restSpeedThreshold: 1.7, + restDisplacementThreshold: 0.4, + velocity: velocityX, + bounciness: 0, + toValue, + useNativeDriver: this.props.useNativeAnimations, + ...this.props.animationOptions + }).start(({ + finished + }) => { + if (finished) { + if (toValue > 0 && this.props.onSwipeableLeftOpen) { + this.props.onSwipeableLeftOpen(); + } else if (toValue < 0 && this.props.onSwipeableRightOpen) { + this.props.onSwipeableRightOpen(); + } + + if (toValue === 0) { + var _this$props$onSwipeab, _this$props; + + (_this$props$onSwipeab = (_this$props = this.props).onSwipeableClose) === null || _this$props$onSwipeab === void 0 ? void 0 : _this$props$onSwipeab.call(_this$props); + } else { + var _this$props$onSwipeab2, _this$props2; + + (_this$props$onSwipeab2 = (_this$props2 = this.props).onSwipeableOpen) === null || _this$props$onSwipeab2 === void 0 ? void 0 : _this$props$onSwipeab2.call(_this$props2); + } + } + }); + + if (toValue > 0 && this.props.onSwipeableLeftWillOpen) { + this.props.onSwipeableLeftWillOpen(); + } else if (toValue < 0 && this.props.onSwipeableRightWillOpen) { + this.props.onSwipeableRightWillOpen(); + } + + if (toValue === 0) { + var _this$props$onSwipeab3, _this$props3; + + (_this$props$onSwipeab3 = (_this$props3 = this.props).onSwipeableWillClose) === null || _this$props$onSwipeab3 === void 0 ? void 0 : _this$props$onSwipeab3.call(_this$props3); + } else { + var _this$props$onSwipeab4, _this$props4; + + (_this$props$onSwipeab4 = (_this$props4 = this.props).onSwipeableWillOpen) === null || _this$props$onSwipeab4 === void 0 ? void 0 : _this$props$onSwipeab4.call(_this$props4); + } + }); + + _defineProperty(this, "onRowLayout", ({ + nativeEvent + }) => { + this.setState({ + rowWidth: nativeEvent.layout.width + }); + }); + + _defineProperty(this, "currentOffset", () => { + const { + leftWidth = 0, + rowWidth = 0, + rowState + } = this.state; + const { + rightOffset = rowWidth + } = this.state; + const rightWidth = rowWidth - rightOffset; + + if (rowState === 1) { + return leftWidth; + } else if (rowState === -1) { + return -rightWidth; + } + + return 0; + }); + + _defineProperty(this, "close", () => { + this.animateRow(this.currentOffset(), 0); + }); + + _defineProperty(this, "openLeft", () => { + const { + leftWidth = 0 + } = this.state; + this.animateRow(this.currentOffset(), leftWidth); + }); + + _defineProperty(this, "openRight", () => { + const { + rowWidth = 0 + } = this.state; + const { + rightOffset = rowWidth + } = this.state; + const rightWidth = rowWidth - rightOffset; + this.animateRow(this.currentOffset(), -rightWidth); + }); + + const _dragX = new Animated.Value(0); + + this.state = { + dragX: _dragX, + rowTranslation: new Animated.Value(0), + rowState: 0, + leftWidth: undefined, + rightOffset: undefined, + rowWidth: undefined + }; + this.updateAnimatedEvent(_props, this.state); + this.onGestureEvent = Animated.event([{ + nativeEvent: { + translationX: _dragX + } + }], { + useNativeDriver: _props.useNativeAnimations + }); + } + + UNSAFE_componentWillUpdate(props, state) { + if (this.props.friction !== props.friction || this.props.overshootLeft !== props.overshootLeft || this.props.overshootRight !== props.overshootRight || this.props.overshootFriction !== props.overshootFriction || this.state.leftWidth !== state.leftWidth || this.state.rightOffset !== state.rightOffset || this.state.rowWidth !== state.rowWidth) { + this.updateAnimatedEvent(props, state); + } + } + + render() { + const { + rowState + } = this.state; + const { + children, + renderLeftActions, + renderRightActions + } = this.props; + const left = renderLeftActions && /*#__PURE__*/React.createElement(Animated.View, { + style: [styles.leftActions, // all those and below parameters can have ! since they are all + // asigned in constructor in `updateAnimatedEvent` but TS cannot spot + // it for some reason + { + transform: [{ + translateX: this.leftActionTranslate + }] + }] + }, renderLeftActions(this.showLeftAction, this.transX), /*#__PURE__*/React.createElement(View, { + onLayout: ({ + nativeEvent + }) => this.setState({ + leftWidth: nativeEvent.layout.x + }) + })); + const right = renderRightActions && /*#__PURE__*/React.createElement(Animated.View, { + style: [styles.rightActions, { + transform: [{ + translateX: this.rightActionTranslate + }] + }] + }, renderRightActions(this.showRightAction, this.transX), /*#__PURE__*/React.createElement(View, { + onLayout: ({ + nativeEvent + }) => this.setState({ + rightOffset: nativeEvent.layout.x + }) + })); + return /*#__PURE__*/React.createElement(PanGestureHandler, _extends({ + activeOffsetX: [-10, 10] + }, this.props, { + onGestureEvent: this.onGestureEvent, + onHandlerStateChange: this.onHandlerStateChange + }), /*#__PURE__*/React.createElement(Animated.View, { + onLayout: this.onRowLayout, + style: [styles.container, this.props.containerStyle] + }, left, right, /*#__PURE__*/React.createElement(TapGestureHandler, { + enabled: rowState !== 0, + onHandlerStateChange: this.onTapHandlerStateChange + }, /*#__PURE__*/React.createElement(Animated.View, { + pointerEvents: rowState === 0 ? 'auto' : 'box-only', + style: [{ + transform: [{ + translateX: this.transX + }] + }, this.props.childrenContainerStyle] + }, children)))); + } + +} + +_defineProperty(Swipeable, "defaultProps", { + friction: 1, + overshootFriction: 1, + useNativeAnimations: true +}); + +const styles = StyleSheet.create({ + container: { + overflow: 'hidden' + }, + leftActions: { ...StyleSheet.absoluteFillObject, + flexDirection: I18nManager.isRTL ? 'row-reverse' : 'row' + }, + rightActions: { ...StyleSheet.absoluteFillObject, + flexDirection: I18nManager.isRTL ? 'row' : 'row-reverse' + } +}); +//# sourceMappingURL=Swipeable.js.map \ No newline at end of file diff --git a/lib/module/components/Swipeable.js.map b/lib/module/components/Swipeable.js.map new file mode 100644 index 0000000000..9c89a67fb0 --- /dev/null +++ b/lib/module/components/Swipeable.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["Swipeable.tsx"],"names":["React","Component","Animated","StyleSheet","View","I18nManager","PanGestureHandler","TapGestureHandler","State","DRAG_TOSS","Swipeable","constructor","props","state","friction","overshootFriction","dragX","rowTranslation","leftWidth","rowWidth","rightOffset","rightWidth","Math","max","overshootLeft","overshootRight","transX","add","interpolate","inputRange","outputRange","showLeftAction","Value","leftActionTranslate","Number","MIN_VALUE","extrapolate","showRightAction","rightActionTranslate","nativeEvent","oldState","ACTIVE","close","ev","handleRelease","velocityX","translationX","rowState","leftThreshold","rightThreshold","startOffsetX","currentOffset","toValue","animateRow","fromValue","setValue","setState","sign","spring","restSpeedThreshold","restDisplacementThreshold","velocity","bounciness","useNativeDriver","useNativeAnimations","animationOptions","start","finished","onSwipeableLeftOpen","onSwipeableRightOpen","onSwipeableClose","onSwipeableOpen","onSwipeableLeftWillOpen","onSwipeableRightWillOpen","onSwipeableWillClose","onSwipeableWillOpen","layout","width","undefined","updateAnimatedEvent","onGestureEvent","event","UNSAFE_componentWillUpdate","render","children","renderLeftActions","renderRightActions","left","styles","leftActions","transform","translateX","x","right","rightActions","onHandlerStateChange","onRowLayout","container","containerStyle","onTapHandlerStateChange","childrenContainerStyle","create","overflow","absoluteFillObject","flexDirection","isRTL"],"mappings":";;;;AAAA;AACA;AACA;AAEA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AACA,SAASC,SAAT,QAA0B,OAA1B;AACA,SACEC,QADF,EAEEC,UAFF,EAGEC,IAHF,EAIEC,WAJF,QAQO,cARP;AAcA,SACEC,iBADF,QAIO,+BAJP;AAKA,SACEC,iBADF,QAGO,+BAHP;AAIA,SAASC,KAAT,QAAsB,UAAtB;AAEA,MAAMC,SAAS,GAAG,IAAlB;AAyJA,eAAe,MAAMC,SAAN,SAAwBT,SAAxB,CAGb;AAOAU,EAAAA,WAAW,CAACC,MAAD,EAAwB;AACjC,UAAMA,MAAN;;AADiC;;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;;AAAA,iDA0CL,CAC5BA,KAD4B,EAE5BC,KAF4B,KAGzB;AACH,YAAM;AAAEC,QAAAA,QAAF;AAAYC,QAAAA;AAAZ,UAAkCH,KAAxC;AACA,YAAM;AAAEI,QAAAA,KAAF;AAASC,QAAAA,cAAT;AAAyBC,QAAAA,SAAS,GAAG,CAArC;AAAwCC,QAAAA,QAAQ,GAAG;AAAnD,UAAyDN,KAA/D;AACA,YAAM;AAAEO,QAAAA,WAAW,GAAGD;AAAhB,UAA6BN,KAAnC;AACA,YAAMQ,UAAU,GAAGC,IAAI,CAACC,GAAL,CAAS,CAAT,EAAYJ,QAAQ,GAAGC,WAAvB,CAAnB;AAEA,YAAM;AACJI,QAAAA,aAAa,GAAGN,SAAS,GAAG,CADxB;AAEJO,QAAAA,cAAc,GAAGJ,UAAU,GAAG;AAF1B,UAGFT,KAHJ;AAKA,YAAMc,MAAM,GAAGxB,QAAQ,CAACyB,GAAT,CACbV,cADa,EAEbD,KAAK,CAACY,WAAN,CAAkB;AAChBC,QAAAA,UAAU,EAAE,CAAC,CAAD,EAAIf,QAAJ,CADI;AAEhBgB,QAAAA,WAAW,EAAE,C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,EAAE9C,QAAQ,KAAK,CADxB;AAEE,MAAA,oBAAoB,EAAE,KAAKoD;AAF7B,oBAGE,oBAAC,QAAD,CAAU,IAAV;AACE,MAAA,aAAa,EAAEpD,QAAQ,KAAK,CAAb,GAAiB,MAAjB,GAA0B,UAD3C;AAEE,MAAA,KAAK,EAAE,CACL;AACE2C,QAAAA,SAAS,EAAE,CAAC;AAAEC,UAAAA,UAAU,EAAE,KAAKjE;AAAnB,SAAD;AADb,OADK,EAIL,KAAKd,KAAL,CAAWwF,sBAJN;AAFT,OAQGhB,QARH,CAHF,CALF,CALF,CADF;AA4BD;;AAnTD;;gBAHmB1E,S,kBAIG;AACpBI,EAAAA,QAAQ,EAAE,CADU;AAEpBC,EAAAA,iBAAiB,EAAE,CAFC;AAGpBiD,EAAAA,mBAAmB,EAAE;AAHD,C;;AAqTxB,MAAMwB,MAAM,GAAGrF,UAAU,CAACkG,MAAX,CAAkB;AAC/BJ,EAAAA,SAAS,EAAE;AACTK,IAAAA,QAAQ,EAAE;AADD,GADoB;AAI/Bb,EAAAA,WAAW,EAAE,EACX,GAAGtF,UAAU,CAACoG,kBADH;AAEXC,IAAAA,aAAa,EAAEnG,WAAW,CAACoG,KAAZ,GAAoB,aAApB,GAAoC;AAFxC,GAJkB;AAQ/BX,EAAAA,YAAY,EAAE,EACZ,GAAG3F,UAAU,CAACoG,kBADF;AAEZC,IAAAA,aAAa,EAAEnG,WAAW,CAACoG,KAAZ,GAAoB,KAApB,GAA4B;AAF/B;AARiB,CAAlB,CAAf","sourcesContent":["// Similarily to the DrawerLayout component this deserves to be put in a\n// separate repo. Although, keeping it here for the time being will allow us to\n// move faster and fix possible issues quicker\n\nimport * as React from 'react';\nimport { Component } from 'react';\nimport {\n Animated,\n StyleSheet,\n View,\n I18nManager,\n LayoutChangeEvent,\n StyleProp,\n ViewStyle,\n} from 'react-native';\n\nimport {\n GestureEvent,\n HandlerStateChangeEvent,\n} from '../handlers/gestureHandlerCommon';\nimport {\n PanGestureHandler,\n PanGestureHandlerEventPayload,\n PanGestureHandlerProps,\n} from '../handlers/PanGestureHandler';\nimport {\n TapGestureHandler,\n TapGestureHandlerEventPayload,\n} from '../handlers/TapGestureHandler';\nimport { State } from '../State';\n\nconst DRAG_TOSS = 0.05;\n\ntype SwipeableExcludes = Exclude<\n keyof PanGestureHandlerProps,\n 'onGestureEvent' | 'onHandlerStateChange'\n>;\n\nexport interface SwipeableProps\n extends Pick {\n /**\n * Enables two-finger gestures on supported devices, for example iPads with\n * trackpads. If not enabled the gesture will require click + drag, with\n * `enableTrackpadTwoFingerGesture` swiping with two fingers will also trigger\n * the gesture.\n */\n enableTrackpadTwoFingerGesture?: boolean;\n\n /**\n * Specifies how much the visual interaction will be delayed compared to the\n * gesture distance. e.g. value of 1 will indicate that the swipeable panel\n * should exactly follow the gesture, 2 means it is going to be two times\n * \"slower\".\n */\n friction?: number;\n\n /**\n * Distance from the left edge at which released panel will animate to the\n * open state (or the open panel will animate into the closed state). By\n * default it's a half of the panel's width.\n */\n leftThreshold?: number;\n\n /**\n * Distance from the right edge at which released panel will animate to the\n * open state (or the open panel will animate into the closed state). By\n * default it's a half of the panel's width.\n */\n rightThreshold?: number;\n\n /**\n * Value indicating if the swipeable panel can be pulled further than the left\n * actions panel's width. It is set to true by default as long as the left\n * panel render method is present.\n */\n overshootLeft?: boolean;\n\n /**\n * Value indicating if the swipeable panel can be pulled further than the\n * right actions panel's width. It is set to true by default as long as the\n * right panel render method is present.\n */\n overshootRight?: boolean;\n\n /**\n * Specifies how much the visual interaction will be delayed compared to the\n * gesture distance at overshoot. Default value is 1, it mean no friction, for\n * a native feel, try 8 or above.\n */\n overshootFriction?: number;\n\n /**\n * Called when left action panel gets open.\n */\n onSwipeableLeftOpen?: () => void;\n\n /**\n * Called when right action panel gets open.\n */\n onSwipeableRightOpen?: () => void;\n\n /**\n * Called when action panel gets open (either right or left).\n */\n onSwipeableOpen?: () => void;\n\n /**\n * Called when action panel is closed.\n */\n onSwipeableClose?: () => void;\n\n /**\n * Called when left action panel starts animating on open.\n */\n onSwipeableLeftWillOpen?: () => void;\n\n /**\n * Called when right action panel starts animating on open.\n */\n onSwipeableRightWillOpen?: () => void;\n\n /**\n * Called when action panel starts animating on open (either right or left).\n */\n onSwipeableWillOpen?: () => void;\n\n /**\n * Called when action panel starts animating on close.\n */\n onSwipeableWillClose?: () => void;\n\n /**\n *\n * This map describes the values to use as inputRange for extra interpolation:\n * AnimatedValue: [startValue, endValue]\n *\n * progressAnimatedValue: [0, 1] dragAnimatedValue: [0, +]\n *\n * To support `rtl` flexbox layouts use `flexDirection` styling.\n * */\n renderLeftActions?: (\n progressAnimatedValue: Animated.AnimatedInterpolation,\n dragAnimatedValue: Animated.AnimatedInterpolation\n ) => React.ReactNode;\n /**\n *\n * This map describes the values to use as inputRange for extra interpolation:\n * AnimatedValue: [startValue, endValue]\n *\n * progressAnimatedValue: [0, 1] dragAnimatedValue: [0, -]\n *\n * To support `rtl` flexbox layouts use `flexDirection` styling.\n * */\n renderRightActions?: (\n progressAnimatedValue: Animated.AnimatedInterpolation,\n dragAnimatedValue: Animated.AnimatedInterpolation\n ) => React.ReactNode;\n\n useNativeAnimations?: boolean;\n\n animationOptions?: Record;\n\n /**\n * Style object for the container (`Animated.View`), for example to override\n * `overflow: 'hidden'`.\n */\n containerStyle?: StyleProp;\n\n /**\n * Style object for the children container (`Animated.View`), for example to\n * apply `flex: 1`\n */\n childrenContainerStyle?: StyleProp;\n}\n\ntype SwipeableState = {\n dragX: Animated.Value;\n rowTranslation: Animated.Value;\n rowState: number;\n leftWidth?: number;\n rightOffset?: number;\n rowWidth?: number;\n};\n\nexport default class Swipeable extends Component<\n SwipeableProps,\n SwipeableState\n> {\n static defaultProps = {\n friction: 1,\n overshootFriction: 1,\n useNativeAnimations: true,\n };\n\n constructor(props: SwipeableProps) {\n super(props);\n const dragX = new Animated.Value(0);\n this.state = {\n dragX,\n rowTranslation: new Animated.Value(0),\n rowState: 0,\n leftWidth: undefined,\n rightOffset: undefined,\n rowWidth: undefined,\n };\n this.updateAnimatedEvent(props, this.state);\n\n this.onGestureEvent = Animated.event(\n [{ nativeEvent: { translationX: dragX } }],\n { useNativeDriver: props.useNativeAnimations! }\n );\n }\n\n UNSAFE_componentWillUpdate(props: SwipeableProps, state: SwipeableState) {\n if (\n this.props.friction !== props.friction ||\n this.props.overshootLeft !== props.overshootLeft ||\n this.props.overshootRight !== props.overshootRight ||\n this.props.overshootFriction !== props.overshootFriction ||\n this.state.leftWidth !== state.leftWidth ||\n this.state.rightOffset !== state.rightOffset ||\n this.state.rowWidth !== state.rowWidth\n ) {\n this.updateAnimatedEvent(props, state);\n }\n }\n\n private onGestureEvent?: (\n event: GestureEvent\n ) => void;\n private transX?: Animated.AnimatedInterpolation;\n private showLeftAction?: Animated.AnimatedInterpolation | Animated.Value;\n private leftActionTranslate?: Animated.AnimatedInterpolation;\n private showRightAction?: Animated.AnimatedInterpolation | Animated.Value;\n private rightActionTranslate?: Animated.AnimatedInterpolation;\n\n private updateAnimatedEvent = (\n props: SwipeableProps,\n state: SwipeableState\n ) => {\n const { friction, overshootFriction } = props;\n const { dragX, rowTranslation, leftWidth = 0, rowWidth = 0 } = state;\n const { rightOffset = rowWidth } = state;\n const rightWidth = Math.max(0, rowWidth - rightOffset);\n\n const {\n overshootLeft = leftWidth > 0,\n overshootRight = rightWidth > 0,\n } = props;\n\n const transX = Animated.add(\n rowTranslation,\n dragX.interpolate({\n inputRange: [0, friction!],\n outputRange: [0, 1],\n })\n ).interpolate({\n inputRange: [-rightWidth - 1, -rightWidth, leftWidth, leftWidth + 1],\n outputRange: [\n -rightWidth - (overshootRight ? 1 / overshootFriction! : 0),\n -rightWidth,\n leftWidth,\n leftWidth + (overshootLeft ? 1 / overshootFriction! : 0),\n ],\n });\n this.transX = transX;\n this.showLeftAction =\n leftWidth > 0\n ? transX.interpolate({\n inputRange: [-1, 0, leftWidth],\n outputRange: [0, 0, 1],\n })\n : new Animated.Value(0);\n this.leftActionTranslate = this.showLeftAction.interpolate({\n inputRange: [0, Number.MIN_VALUE],\n outputRange: [-10000, 0],\n extrapolate: 'clamp',\n });\n this.showRightAction =\n rightWidth > 0\n ? transX.interpolate({\n inputRange: [-rightWidth, 0, 1],\n outputRange: [1, 0, 0],\n })\n : new Animated.Value(0);\n this.rightActionTranslate = this.showRightAction.interpolate({\n inputRange: [0, Number.MIN_VALUE],\n outputRange: [-10000, 0],\n extrapolate: 'clamp',\n });\n };\n\n private onTapHandlerStateChange = ({\n nativeEvent,\n }: HandlerStateChangeEvent) => {\n if (nativeEvent.oldState === State.ACTIVE) {\n this.close();\n }\n };\n\n private onHandlerStateChange = (\n ev: HandlerStateChangeEvent\n ) => {\n if (ev.nativeEvent.oldState === State.ACTIVE) {\n this.handleRelease(ev);\n }\n };\n\n private handleRelease = (\n ev: HandlerStateChangeEvent\n ) => {\n const { velocityX, translationX: dragX } = ev.nativeEvent;\n const { leftWidth = 0, rowWidth = 0, rowState } = this.state;\n const { rightOffset = rowWidth } = this.state;\n const rightWidth = rowWidth - rightOffset;\n const {\n friction,\n leftThreshold = leftWidth / 2,\n rightThreshold = rightWidth / 2,\n } = this.props;\n\n const startOffsetX = this.currentOffset() + dragX / friction!;\n const translationX = (dragX + DRAG_TOSS * velocityX) / friction!;\n\n let toValue = 0;\n if (rowState === 0) {\n if (translationX > leftThreshold) {\n toValue = leftWidth;\n } else if (translationX < -rightThreshold) {\n toValue = -rightWidth;\n }\n } else if (rowState === 1) {\n // swiped to left\n if (translationX > -leftThreshold) {\n toValue = leftWidth;\n }\n } else {\n // swiped to right\n if (translationX < rightThreshold) {\n toValue = -rightWidth;\n }\n }\n\n this.animateRow(startOffsetX, toValue, velocityX / friction!);\n };\n\n private animateRow = (\n fromValue: number,\n toValue: number,\n velocityX?:\n | number\n | {\n x: number;\n y: number;\n }\n ) => {\n const { dragX, rowTranslation } = this.state;\n dragX.setValue(0);\n rowTranslation.setValue(fromValue);\n\n this.setState({ rowState: Math.sign(toValue) });\n Animated.spring(rowTranslation, {\n restSpeedThreshold: 1.7,\n restDisplacementThreshold: 0.4,\n velocity: velocityX,\n bounciness: 0,\n toValue,\n useNativeDriver: this.props.useNativeAnimations!,\n ...this.props.animationOptions,\n }).start(({ finished }) => {\n if (finished) {\n if (toValue > 0 && this.props.onSwipeableLeftOpen) {\n this.props.onSwipeableLeftOpen();\n } else if (toValue < 0 && this.props.onSwipeableRightOpen) {\n this.props.onSwipeableRightOpen();\n }\n\n if (toValue === 0) {\n this.props.onSwipeableClose?.();\n } else {\n this.props.onSwipeableOpen?.();\n }\n }\n });\n if (toValue > 0 && this.props.onSwipeableLeftWillOpen) {\n this.props.onSwipeableLeftWillOpen();\n } else if (toValue < 0 && this.props.onSwipeableRightWillOpen) {\n this.props.onSwipeableRightWillOpen();\n }\n\n if (toValue === 0) {\n this.props.onSwipeableWillClose?.();\n } else {\n this.props.onSwipeableWillOpen?.();\n }\n };\n\n private onRowLayout = ({ nativeEvent }: LayoutChangeEvent) => {\n this.setState({ rowWidth: nativeEvent.layout.width });\n };\n\n private currentOffset = () => {\n const { leftWidth = 0, rowWidth = 0, rowState } = this.state;\n const { rightOffset = rowWidth } = this.state;\n const rightWidth = rowWidth - rightOffset;\n if (rowState === 1) {\n return leftWidth;\n } else if (rowState === -1) {\n return -rightWidth;\n }\n return 0;\n };\n\n close = () => {\n this.animateRow(this.currentOffset(), 0);\n };\n\n openLeft = () => {\n const { leftWidth = 0 } = this.state;\n this.animateRow(this.currentOffset(), leftWidth);\n };\n\n openRight = () => {\n const { rowWidth = 0 } = this.state;\n const { rightOffset = rowWidth } = this.state;\n const rightWidth = rowWidth - rightOffset;\n this.animateRow(this.currentOffset(), -rightWidth);\n };\n\n render() {\n const { rowState } = this.state;\n const { children, renderLeftActions, renderRightActions } = this.props;\n\n const left = renderLeftActions && (\n \n {renderLeftActions(this.showLeftAction!, this.transX!)}\n \n this.setState({ leftWidth: nativeEvent.layout.x })\n }\n />\n \n );\n\n const right = renderRightActions && (\n \n {renderRightActions(this.showRightAction!, this.transX!)}\n \n this.setState({ rightOffset: nativeEvent.layout.x })\n }\n />\n \n );\n\n return (\n \n \n {left}\n {right}\n \n \n {children}\n \n \n \n \n );\n }\n}\n\nconst styles = StyleSheet.create({\n container: {\n overflow: 'hidden',\n },\n leftActions: {\n ...StyleSheet.absoluteFillObject,\n flexDirection: I18nManager.isRTL ? 'row-reverse' : 'row',\n },\n rightActions: {\n ...StyleSheet.absoluteFillObject,\n flexDirection: I18nManager.isRTL ? 'row' : 'row-reverse',\n },\n});\n"]} \ No newline at end of file diff --git a/lib/module/components/touchables/GenericTouchable.js b/lib/module/components/touchables/GenericTouchable.js new file mode 100644 index 0000000000..640d7bc31c --- /dev/null +++ b/lib/module/components/touchables/GenericTouchable.js @@ -0,0 +1,262 @@ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +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; } + +import * as React from 'react'; +import { Component } from 'react'; +import { Animated, Platform } from 'react-native'; +import { State } from '../../State'; +import { BaseButton } from '../GestureButtons'; + +/** + * Each touchable is a states' machine which preforms transitions. + * On very beginning (and on the very end or recognition) touchable is + * UNDETERMINED. Then it moves to BEGAN. If touchable recognizes that finger + * travel outside it transits to special MOVED_OUTSIDE state. Gesture recognition + * finishes in UNDETERMINED state. + */ +export const TOUCHABLE_STATE = { + UNDETERMINED: 0, + BEGAN: 1, + MOVED_OUTSIDE: 2 +}; + +/** + * GenericTouchable is not intented to be used as it is. + * Should be treated as a source for the rest of touchables + */ +export default class GenericTouchable extends Component { + constructor(...args) { + super(...args); + + _defineProperty(this, "pressInTimeout", void 0); + + _defineProperty(this, "pressOutTimeout", void 0); + + _defineProperty(this, "longPressTimeout", void 0); + + _defineProperty(this, "longPressDetected", false); + + _defineProperty(this, "pointerInside", true); + + _defineProperty(this, "STATE", TOUCHABLE_STATE.UNDETERMINED); + + _defineProperty(this, "onGestureEvent", ({ + nativeEvent: { + pointerInside + } + }) => { + if (this.pointerInside !== pointerInside) { + if (pointerInside) { + this.onMoveIn(); + } else { + this.onMoveOut(); + } + } + + this.pointerInside = pointerInside; + }); + + _defineProperty(this, "onHandlerStateChange", ({ + nativeEvent + }) => { + const { + state + } = nativeEvent; + + if (state === State.CANCELLED || state === State.FAILED) { + // Need to handle case with external cancellation (e.g. by ScrollView) + this.moveToState(TOUCHABLE_STATE.UNDETERMINED); + } else if ( // This platform check is an implication of slightly different behavior of handlers on different platform. + // And Android "Active" state is achieving on first move of a finger, not on press in. + // On iOS event on "Began" is not delivered. + state === (Platform.OS !== 'android' ? State.ACTIVE : State.BEGAN) && this.STATE === TOUCHABLE_STATE.UNDETERMINED) { + // Moving inside requires + this.handlePressIn(); + } else if (state === State.END) { + const shouldCallOnPress = !this.longPressDetected && this.STATE !== TOUCHABLE_STATE.MOVED_OUTSIDE && this.pressOutTimeout === null; + this.handleGoToUndetermined(); + + if (shouldCallOnPress) { + var _this$props$onPress, _this$props; + + // Calls only inside component whether no long press was called previously + (_this$props$onPress = (_this$props = this.props).onPress) === null || _this$props$onPress === void 0 ? void 0 : _this$props$onPress.call(_this$props); + } + } + }); + + _defineProperty(this, "onLongPressDetected", () => { + var _this$props$onLongPre, _this$props2; + + this.longPressDetected = true; // checked for in the caller of `onLongPressDetected`, but better to check twice + + (_this$props$onLongPre = (_this$props2 = this.props).onLongPress) === null || _this$props$onLongPre === void 0 ? void 0 : _this$props$onLongPre.call(_this$props2); + }); + } + + // handlePressIn in called on first touch on traveling inside component. + // Handles state transition with delay. + handlePressIn() { + if (this.props.delayPressIn) { + this.pressInTimeout = setTimeout(() => { + this.moveToState(TOUCHABLE_STATE.BEGAN); + this.pressInTimeout = null; + }, this.props.delayPressIn); + } else { + this.moveToState(TOUCHABLE_STATE.BEGAN); + } + + if (this.props.onLongPress) { + const time = (this.props.delayPressIn || 0) + (this.props.delayLongPress || 0); + this.longPressTimeout = setTimeout(this.onLongPressDetected, time); + } + } // handleMoveOutside in called on traveling outside component. + // Handles state transition with delay. + + + handleMoveOutside() { + if (this.props.delayPressOut) { + this.pressOutTimeout = this.pressOutTimeout || setTimeout(() => { + this.moveToState(TOUCHABLE_STATE.MOVED_OUTSIDE); + this.pressOutTimeout = null; + }, this.props.delayPressOut); + } else { + this.moveToState(TOUCHABLE_STATE.MOVED_OUTSIDE); + } + } // handleGoToUndetermined transits to UNDETERMINED state with proper delay + + + handleGoToUndetermined() { + clearTimeout(this.pressOutTimeout); // TODO: maybe it can be undefined + + if (this.props.delayPressOut) { + this.pressOutTimeout = setTimeout(() => { + if (this.STATE === TOUCHABLE_STATE.UNDETERMINED) { + this.moveToState(TOUCHABLE_STATE.BEGAN); + } + + this.moveToState(TOUCHABLE_STATE.UNDETERMINED); + this.pressOutTimeout = null; + }, this.props.delayPressOut); + } else { + if (this.STATE === TOUCHABLE_STATE.UNDETERMINED) { + this.moveToState(TOUCHABLE_STATE.BEGAN); + } + + this.moveToState(TOUCHABLE_STATE.UNDETERMINED); + } + } + + componentDidMount() { + this.reset(); + } // reset timeout to prevent memory leaks. + + + reset() { + this.longPressDetected = false; + this.pointerInside = true; + clearTimeout(this.pressInTimeout); + clearTimeout(this.pressOutTimeout); + clearTimeout(this.longPressTimeout); + this.pressOutTimeout = null; + this.longPressTimeout = null; + this.pressInTimeout = null; + } // All states' transitions are defined here. + + + moveToState(newState) { + var _this$props$onStateCh, _this$props6; + + if (newState === this.STATE) { + // Ignore dummy transitions + return; + } + + if (newState === TOUCHABLE_STATE.BEGAN) { + var _this$props$onPressIn, _this$props3; + + // First touch and moving inside + (_this$props$onPressIn = (_this$props3 = this.props).onPressIn) === null || _this$props$onPressIn === void 0 ? void 0 : _this$props$onPressIn.call(_this$props3); + } else if (newState === TOUCHABLE_STATE.MOVED_OUTSIDE) { + var _this$props$onPressOu, _this$props4; + + // Moving outside + (_this$props$onPressOu = (_this$props4 = this.props).onPressOut) === null || _this$props$onPressOu === void 0 ? void 0 : _this$props$onPressOu.call(_this$props4); + } else if (newState === TOUCHABLE_STATE.UNDETERMINED) { + // Need to reset each time on transition to UNDETERMINED + this.reset(); + + if (this.STATE === TOUCHABLE_STATE.BEGAN) { + var _this$props$onPressOu2, _this$props5; + + // ... and if it happens inside button. + (_this$props$onPressOu2 = (_this$props5 = this.props).onPressOut) === null || _this$props$onPressOu2 === void 0 ? void 0 : _this$props$onPressOu2.call(_this$props5); + } + } // Finally call lister (used by subclasses) + + + (_this$props$onStateCh = (_this$props6 = this.props).onStateChange) === null || _this$props$onStateCh === void 0 ? void 0 : _this$props$onStateCh.call(_this$props6, this.STATE, newState); // ... and make transition. + + this.STATE = newState; + } + + componentWillUnmount() { + // to prevent memory leaks + this.reset(); + } + + onMoveIn() { + if (this.STATE === TOUCHABLE_STATE.MOVED_OUTSIDE) { + // This call is not throttled with delays (like in RN's implementation). + this.moveToState(TOUCHABLE_STATE.BEGAN); + } + } + + onMoveOut() { + // long press should no longer be detected + clearTimeout(this.longPressTimeout); + this.longPressTimeout = null; + + if (this.STATE === TOUCHABLE_STATE.BEGAN) { + this.handleMoveOutside(); + } + } + + render() { + const coreProps = { + accessible: this.props.accessible !== false, + accessibilityLabel: this.props.accessibilityLabel, + accessibilityHint: this.props.accessibilityHint, + accessibilityRole: this.props.accessibilityRole, + // TODO: check if changed to no 's' correctly, also removed 2 props that are no longer available: `accessibilityComponentType` and `accessibilityTraits`, + // would be good to check if it is ok for sure, see: https://github.com/facebook/react-native/issues/24016 + accessibilityState: this.props.accessibilityState, + nativeID: this.props.nativeID, + onLayout: this.props.onLayout, + hitSlop: this.props.hitSlop + }; + return /*#__PURE__*/React.createElement(BaseButton, _extends({ + style: this.props.containerStyle, + onHandlerStateChange: // TODO: not sure if it can be undefined instead of null + this.props.disabled ? undefined : this.onHandlerStateChange, + onGestureEvent: this.onGestureEvent, + hitSlop: this.props.hitSlop, + shouldActivateOnStart: this.props.shouldActivateOnStart, + disallowInterruption: this.props.disallowInterruption, + testID: this.props.testID + }, this.props.extraButtonProps), /*#__PURE__*/React.createElement(Animated.View, _extends({}, coreProps, { + style: this.props.style + }), this.props.children)); + } + +} + +_defineProperty(GenericTouchable, "defaultProps", { + delayLongPress: 600, + extraButtonProps: { + rippleColor: 'transparent', + exclusive: true + } +}); +//# sourceMappingURL=GenericTouchable.js.map \ No newline at end of file diff --git a/lib/module/components/touchables/GenericTouchable.js.map b/lib/module/components/touchables/GenericTouchable.js.map new file mode 100644 index 0000000000..698920b6f1 --- /dev/null +++ b/lib/module/components/touchables/GenericTouchable.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GenericTouchable.tsx"],"names":["React","Component","Animated","Platform","State","BaseButton","TOUCHABLE_STATE","UNDETERMINED","BEGAN","MOVED_OUTSIDE","GenericTouchable","nativeEvent","pointerInside","onMoveIn","onMoveOut","state","CANCELLED","FAILED","moveToState","OS","ACTIVE","STATE","handlePressIn","END","shouldCallOnPress","longPressDetected","pressOutTimeout","handleGoToUndetermined","props","onPress","onLongPress","delayPressIn","pressInTimeout","setTimeout","time","delayLongPress","longPressTimeout","onLongPressDetected","handleMoveOutside","delayPressOut","clearTimeout","componentDidMount","reset","newState","onPressIn","onPressOut","onStateChange","componentWillUnmount","render","coreProps","accessible","accessibilityLabel","accessibilityHint","accessibilityRole","accessibilityState","nativeID","onLayout","hitSlop","containerStyle","disabled","undefined","onHandlerStateChange","onGestureEvent","shouldActivateOnStart","disallowInterruption","testID","extraButtonProps","style","children","rippleColor","exclusive"],"mappings":";;;;AAAA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AACA,SAASC,SAAT,QAA0B,OAA1B;AACA,SACEC,QADF,EAEEC,QAFF,QAMO,cANP;AAQA,SAASC,KAAT,QAAsB,aAAtB;AACA,SAASC,UAAT,QAA2B,mBAA3B;;AASA;AACA;AACA;A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AE,KAAKzB,KAAL,CAAWyB,iBAJd;AAKhB;AACA;AACAC,MAAAA,kBAAkB,EAAE,KAAK1B,KAAL,CAAW0B,kBAPf;AAQhBC,MAAAA,QAAQ,EAAE,KAAK3B,KAAL,CAAW2B,QARL;AAShBC,MAAAA,QAAQ,EAAE,KAAK5B,KAAL,CAAW4B,QATL;AAUhBC,MAAAA,OAAO,EAAE,KAAK7B,KAAL,CAAW6B;AAVJ,KAAlB;AAaA,wBACE,oBAAC,UAAD;AACE,MAAA,KAAK,EAAE,KAAK7B,KAAL,CAAW8B,cADpB;AAEE,MAAA,oBAAoB,EAClB;AACA,WAAK9B,KAAL,CAAW+B,QAAX,GAAsBC,SAAtB,GAAkC,KAAKC,oBAJ3C;AAME,MAAA,cAAc,EAAE,KAAKC,cANvB;AAOE,MAAA,OAAO,EAAE,KAAKlC,KAAL,CAAW6B,OAPtB;AAQE,MAAA,qBAAqB,EAAE,KAAK7B,KAAL,CAAWmC,qBARpC;AASE,MAAA,oBAAoB,EAAE,KAAKnC,KAAL,CAAWoC,oBATnC;AAUE,MAAA,MAAM,EAAE,KAAKpC,KAAL,CAAWqC;AAVrB,OAWM,KAAKrC,KAAL,CAAWsC,gBAXjB,gBAYE,oBAAC,QAAD,CAAU,IAAV,eAAmBjB,SAAnB;AAA8B,MAAA,KAAK,EAAE,KAAKrB,KAAL,CAAWuC;AAAhD,QACG,KAAKvC,KAAL,CAAWwC,QADd,CAZF,CADF;AAkBD;;AAvND;;gBAFmB1D,gB,kBAGG;AACpByB,EAAAA,cAAc,EAAE,GADI;AAEpB+B,EAAAA,gBAAgB,EAAE;AAChBG,IAAAA,WAAW,EAAE,aADG;AAEhBC,IAAAA,SAAS,EAAE;AAFK;AAFE,C","sourcesContent":["import * as React from 'react';\nimport { Component } from 'react';\nimport {\n Animated,\n Platform,\n StyleProp,\n ViewStyle,\n TouchableWithoutFeedbackProps,\n} from 'react-native';\n\nimport { State } from '../../State';\nimport { BaseButton } from '../GestureButtons';\n\nimport {\n GestureEvent,\n HandlerStateChangeEvent,\n} from '../../handlers/gestureHandlerCommon';\nimport { NativeViewGestureHandlerPayload } from '../../handlers/NativeViewGestureHandler';\nimport { TouchableNativeFeedbackExtraProps } from './TouchableNativeFeedback.android';\n\n/**\n * Each touchable is a states' machine which preforms transitions.\n * On very beginning (and on the very end or recognition) touchable is\n * UNDETERMINED. Then it moves to BEGAN. If touchable recognizes that finger\n * travel outside it transits to special MOVED_OUTSIDE state. Gesture recognition\n * finishes in UNDETERMINED state.\n */\nexport const TOUCHABLE_STATE = {\n UNDETERMINED: 0,\n BEGAN: 1,\n MOVED_OUTSIDE: 2,\n} as const;\n\ntype TouchableState = typeof TOUCHABLE_STATE[keyof typeof TOUCHABLE_STATE];\n\nexport interface GenericTouchableProps extends TouchableWithoutFeedbackProps {\n // Decided to drop not used fields from RN's implementation.\n // e.g. onBlur and onFocus as well as deprecated props. - TODO: this comment may be unuseful in this moment\n\n // TODO: in RN these events get native event parameter, which prolly could be used in our implementation too\n onPress?: () => void;\n onPressIn?: () => void;\n onPressOut?: () => void;\n onLongPress?: () => void;\n\n nativeID?: string;\n shouldActivateOnStart?: boolean;\n disallowInterruption?: boolean;\n\n containerStyle?: StyleProp;\n}\n\ninterface InternalProps {\n extraButtonProps: TouchableNativeFeedbackExtraProps;\n onStateChange?: (oldState: TouchableState, newState: TouchableState) => void;\n}\n\n// TODO: maybe can be better\n// TODO: all clearTimeout have ! added, maybe they shouldn't ?\ntype Timeout = ReturnType | null | undefined;\n\n/**\n * GenericTouchable is not intented to be used as it is.\n * Should be treated as a source for the rest of touchables\n */\n\nexport default class GenericTouchable extends Component<\n GenericTouchableProps & InternalProps\n> {\n static defaultProps = {\n delayLongPress: 600,\n extraButtonProps: {\n rippleColor: 'transparent',\n exclusive: true,\n },\n };\n\n // timeout handlers\n pressInTimeout: Timeout;\n pressOutTimeout: Timeout;\n longPressTimeout: Timeout;\n\n // This flag is required since recognition of longPress implies not-invoking onPress\n longPressDetected = false;\n\n pointerInside = true;\n\n // State of touchable\n STATE: TouchableState = TOUCHABLE_STATE.UNDETERMINED;\n\n // handlePressIn in called on first touch on traveling inside component.\n // Handles state transition with delay.\n handlePressIn() {\n if (this.props.delayPressIn) {\n this.pressInTimeout = setTimeout(() => {\n this.moveToState(TOUCHABLE_STATE.BEGAN);\n this.pressInTimeout = null;\n }, this.props.delayPressIn);\n } else {\n this.moveToState(TOUCHABLE_STATE.BEGAN);\n }\n if (this.props.onLongPress) {\n const time =\n (this.props.delayPressIn || 0) + (this.props.delayLongPress || 0);\n this.longPressTimeout = setTimeout(this.onLongPressDetected, time);\n }\n }\n // handleMoveOutside in called on traveling outside component.\n // Handles state transition with delay.\n handleMoveOutside() {\n if (this.props.delayPressOut) {\n this.pressOutTimeout =\n this.pressOutTimeout ||\n setTimeout(() => {\n this.moveToState(TOUCHABLE_STATE.MOVED_OUTSIDE);\n this.pressOutTimeout = null;\n }, this.props.delayPressOut);\n } else {\n this.moveToState(TOUCHABLE_STATE.MOVED_OUTSIDE);\n }\n }\n\n // handleGoToUndetermined transits to UNDETERMINED state with proper delay\n handleGoToUndetermined() {\n clearTimeout(this.pressOutTimeout!); // TODO: maybe it can be undefined\n if (this.props.delayPressOut) {\n this.pressOutTimeout = setTimeout(() => {\n if (this.STATE === TOUCHABLE_STATE.UNDETERMINED) {\n this.moveToState(TOUCHABLE_STATE.BEGAN);\n }\n this.moveToState(TOUCHABLE_STATE.UNDETERMINED);\n this.pressOutTimeout = null;\n }, this.props.delayPressOut);\n } else {\n if (this.STATE === TOUCHABLE_STATE.UNDETERMINED) {\n this.moveToState(TOUCHABLE_STATE.BEGAN);\n }\n this.moveToState(TOUCHABLE_STATE.UNDETERMINED);\n }\n }\n\n componentDidMount() {\n this.reset();\n }\n // reset timeout to prevent memory leaks.\n reset() {\n this.longPressDetected = false;\n this.pointerInside = true;\n clearTimeout(this.pressInTimeout!);\n clearTimeout(this.pressOutTimeout!);\n clearTimeout(this.longPressTimeout!);\n this.pressOutTimeout = null;\n this.longPressTimeout = null;\n this.pressInTimeout = null;\n }\n\n // All states' transitions are defined here.\n moveToState(newState: TouchableState) {\n if (newState === this.STATE) {\n // Ignore dummy transitions\n return;\n }\n if (newState === TOUCHABLE_STATE.BEGAN) {\n // First touch and moving inside\n this.props.onPressIn?.();\n } else if (newState === TOUCHABLE_STATE.MOVED_OUTSIDE) {\n // Moving outside\n this.props.onPressOut?.();\n } else if (newState === TOUCHABLE_STATE.UNDETERMINED) {\n // Need to reset each time on transition to UNDETERMINED\n this.reset();\n if (this.STATE === TOUCHABLE_STATE.BEGAN) {\n // ... and if it happens inside button.\n this.props.onPressOut?.();\n }\n }\n // Finally call lister (used by subclasses)\n this.props.onStateChange?.(this.STATE, newState);\n // ... and make transition.\n this.STATE = newState;\n }\n\n onGestureEvent = ({\n nativeEvent: { pointerInside },\n }: GestureEvent) => {\n if (this.pointerInside !== pointerInside) {\n if (pointerInside) {\n this.onMoveIn();\n } else {\n this.onMoveOut();\n }\n }\n this.pointerInside = pointerInside;\n };\n\n onHandlerStateChange = ({\n nativeEvent,\n }: HandlerStateChangeEvent) => {\n const { state } = nativeEvent;\n if (state === State.CANCELLED || state === State.FAILED) {\n // Need to handle case with external cancellation (e.g. by ScrollView)\n this.moveToState(TOUCHABLE_STATE.UNDETERMINED);\n } else if (\n // This platform check is an implication of slightly different behavior of handlers on different platform.\n // And Android \"Active\" state is achieving on first move of a finger, not on press in.\n // On iOS event on \"Began\" is not delivered.\n state === (Platform.OS !== 'android' ? State.ACTIVE : State.BEGAN) &&\n this.STATE === TOUCHABLE_STATE.UNDETERMINED\n ) {\n // Moving inside requires\n this.handlePressIn();\n } else if (state === State.END) {\n const shouldCallOnPress =\n !this.longPressDetected &&\n this.STATE !== TOUCHABLE_STATE.MOVED_OUTSIDE &&\n this.pressOutTimeout === null;\n this.handleGoToUndetermined();\n if (shouldCallOnPress) {\n // Calls only inside component whether no long press was called previously\n this.props.onPress?.();\n }\n }\n };\n\n onLongPressDetected = () => {\n this.longPressDetected = true;\n // checked for in the caller of `onLongPressDetected`, but better to check twice\n this.props.onLongPress?.();\n };\n\n componentWillUnmount() {\n // to prevent memory leaks\n this.reset();\n }\n\n onMoveIn() {\n if (this.STATE === TOUCHABLE_STATE.MOVED_OUTSIDE) {\n // This call is not throttled with delays (like in RN's implementation).\n this.moveToState(TOUCHABLE_STATE.BEGAN);\n }\n }\n\n onMoveOut() {\n // long press should no longer be detected\n clearTimeout(this.longPressTimeout!);\n this.longPressTimeout = null;\n if (this.STATE === TOUCHABLE_STATE.BEGAN) {\n this.handleMoveOutside();\n }\n }\n\n render() {\n const coreProps = {\n accessible: this.props.accessible !== false,\n accessibilityLabel: this.props.accessibilityLabel,\n accessibilityHint: this.props.accessibilityHint,\n accessibilityRole: this.props.accessibilityRole,\n // TODO: check if changed to no 's' correctly, also removed 2 props that are no longer available: `accessibilityComponentType` and `accessibilityTraits`,\n // would be good to check if it is ok for sure, see: https://github.com/facebook/react-native/issues/24016\n accessibilityState: this.props.accessibilityState,\n nativeID: this.props.nativeID,\n onLayout: this.props.onLayout,\n hitSlop: this.props.hitSlop,\n };\n\n return (\n \n \n {this.props.children}\n \n \n );\n }\n}\n"]} \ No newline at end of file diff --git a/lib/module/components/touchables/TouchableHighlight.js b/lib/module/components/touchables/TouchableHighlight.js new file mode 100644 index 0000000000..746af45904 --- /dev/null +++ b/lib/module/components/touchables/TouchableHighlight.js @@ -0,0 +1,95 @@ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +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; } + +import * as React from 'react'; +import { Component } from 'react'; +import GenericTouchable, { TOUCHABLE_STATE } from './GenericTouchable'; +import { StyleSheet, View } from 'react-native'; + +/** + * TouchableHighlight follows RN's implementation + */ +export default class TouchableHighlight extends Component { + constructor(props) { + super(props); + + _defineProperty(this, "showUnderlay", () => { + var _this$props$onShowUnd, _this$props; + + if (!this.hasPressHandler()) { + return; + } + + this.setState({ + extraChildStyle: { + opacity: this.props.activeOpacity + }, + extraUnderlayStyle: { + backgroundColor: this.props.underlayColor + } + }); + (_this$props$onShowUnd = (_this$props = this.props).onShowUnderlay) === null || _this$props$onShowUnd === void 0 ? void 0 : _this$props$onShowUnd.call(_this$props); + }); + + _defineProperty(this, "hasPressHandler", () => this.props.onPress || this.props.onPressIn || this.props.onPressOut || this.props.onLongPress); + + _defineProperty(this, "hideUnderlay", () => { + var _this$props$onHideUnd, _this$props2; + + this.setState({ + extraChildStyle: null, + extraUnderlayStyle: null + }); + (_this$props$onHideUnd = (_this$props2 = this.props).onHideUnderlay) === null || _this$props$onHideUnd === void 0 ? void 0 : _this$props$onHideUnd.call(_this$props2); + }); + + _defineProperty(this, "onStateChange", (_from, to) => { + if (to === TOUCHABLE_STATE.BEGAN) { + this.showUnderlay(); + } else if (to === TOUCHABLE_STATE.UNDETERMINED || to === TOUCHABLE_STATE.MOVED_OUTSIDE) { + this.hideUnderlay(); + } + }); + + this.state = { + extraChildStyle: null, + extraUnderlayStyle: null + }; + } // Copied from RN + + + renderChildren() { + if (!this.props.children) { + return /*#__PURE__*/React.createElement(View, null); + } + + const child = React.Children.only(this.props.children); // TODO: not sure if OK but fixes error + + return /*#__PURE__*/React.cloneElement(child, { + style: StyleSheet.compose(child.props.style, this.state.extraChildStyle) + }); + } + + render() { + const { + style = {}, + ...rest + } = this.props; + const { + extraUnderlayStyle + } = this.state; + return /*#__PURE__*/React.createElement(GenericTouchable, _extends({}, rest, { + style: [style, extraUnderlayStyle], + onStateChange: this.onStateChange + }), this.renderChildren()); + } + +} + +_defineProperty(TouchableHighlight, "defaultProps", { ...GenericTouchable.defaultProps, + activeOpacity: 0.85, + delayPressOut: 100, + underlayColor: 'black' +}); +//# sourceMappingURL=TouchableHighlight.js.map \ No newline at end of file diff --git a/lib/module/components/touchables/TouchableHighlight.js.map b/lib/module/components/touchables/TouchableHighlight.js.map new file mode 100644 index 0000000000..7a5fed8b55 --- /dev/null +++ b/lib/module/components/touchables/TouchableHighlight.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TouchableHighlight.tsx"],"names":["React","Component","GenericTouchable","TOUCHABLE_STATE","StyleSheet","View","TouchableHighlight","constructor","props","hasPressHandler","setState","extraChildStyle","opacity","activeOpacity","extraUnderlayStyle","backgroundColor","underlayColor","onShowUnderlay","onPress","onPressIn","onPressOut","onLongPress","onHideUnderlay","_from","to","BEGAN","showUnderlay","UNDETERMINED","MOVED_OUTSIDE","hideUnderlay","state","renderChildren","children","child","Children","only","cloneElement","style","compose","render","rest","onStateChange","defaultProps","delayPressOut"],"mappings":";;;;AAAA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AACA,SAASC,SAAT,QAA0B,OAA1B;AACA,OAAOC,gBAAP,IAEEC,eAFF,QAGO,oBAHP;AAIA,SACEC,UADF,EAEEC,IAFF,QAMO,cANP;;AAiBA;AACA;AACA;AACA,eAAe,MAAMC,kBAAN,SAAiCL,SAAjC,CAGb;AAQAM,EAAAA,WAAW,CAACC,KAAD,EAAyD;AAClE,UAAMA,KAAN;;AADkE,0CASrD,MAAM;AAAA;;AACnB,UAAI,CAAC,KAAKC,eAAL,EAAL,EAA6B;AAC3B;AACD;;AACD,WAAKC,QAAL,CAAc;AACZC,QAAAA,eAAe,EAAE;AACfC,UAAAA,OAAO,EAAE,KAAKJ,KAAL,CAAWK;AADL,SADL;AAIZC,QAAAA,kBAAkB,EAAE;AAClBC,UAAAA,eAAe,EAAE,KAAKP,KAAL,CAAWQ;AADV;AAJR,OAAd;AAQA,mDAAKR,KAAL,EAAWS,cAAX;AACD,KAtBmE;;AAAA,6CAwBlD,MAChB,KAAKT,KAAL,CAAWU,OAAX,IACA,KAAKV,KAAL,CAAWW,SADX,IAEA,KAAKX,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wBACE,oBAAC,gBAAD,eACMU,IADN;AAEE,MAAA,KAAK,EAAE,CAACH,KAAD,EAAQvB,kBAAR,CAFT;AAGE,MAAA,aAAa,EAAE,KAAK2B;AAHtB,QAIG,KAAKV,cAAL,EAJH,CADF;AAQD;;AAjFD;;gBAHmBzB,kB,kBAIG,EACpB,GAAGJ,gBAAgB,CAACwC,YADA;AAEpB7B,EAAAA,aAAa,EAAE,IAFK;AAGpB8B,EAAAA,aAAa,EAAE,GAHK;AAIpB3B,EAAAA,aAAa,EAAE;AAJK,C","sourcesContent":["import * as React from 'react';\nimport { Component } from 'react';\nimport GenericTouchable, {\n GenericTouchableProps,\n TOUCHABLE_STATE,\n} from './GenericTouchable';\nimport {\n StyleSheet,\n View,\n TouchableHighlightProps,\n ColorValue,\n ViewProps,\n} from 'react-native';\n\ninterface State {\n extraChildStyle: null | {\n opacity?: number;\n };\n extraUnderlayStyle: null | {\n backgroundColor?: ColorValue;\n };\n}\n\n/**\n * TouchableHighlight follows RN's implementation\n */\nexport default class TouchableHighlight extends Component<\n TouchableHighlightProps & GenericTouchableProps,\n State\n> {\n static defaultProps = {\n ...GenericTouchable.defaultProps,\n activeOpacity: 0.85,\n delayPressOut: 100,\n underlayColor: 'black',\n };\n\n constructor(props: TouchableHighlightProps & GenericTouchableProps) {\n super(props);\n this.state = {\n extraChildStyle: null,\n extraUnderlayStyle: null,\n };\n }\n\n // Copied from RN\n showUnderlay = () => {\n if (!this.hasPressHandler()) {\n return;\n }\n this.setState({\n extraChildStyle: {\n opacity: this.props.activeOpacity,\n },\n extraUnderlayStyle: {\n backgroundColor: this.props.underlayColor,\n },\n });\n this.props.onShowUnderlay?.();\n };\n\n hasPressHandler = () =>\n this.props.onPress ||\n this.props.onPressIn ||\n this.props.onPressOut ||\n this.props.onLongPress;\n\n hideUnderlay = () => {\n this.setState({\n extraChildStyle: null,\n extraUnderlayStyle: null,\n });\n this.props.onHideUnderlay?.();\n };\n\n renderChildren() {\n if (!this.props.children) {\n return ;\n }\n\n const child = React.Children.only(\n this.props.children\n ) as React.ReactElement; // TODO: not sure if OK but fixes error\n return React.cloneElement(child, {\n style: StyleSheet.compose(child.props.style, this.state.extraChildStyle),\n });\n }\n\n onStateChange = (_from: number, to: number) => {\n if (to === TOUCHABLE_STATE.BEGAN) {\n this.showUnderlay();\n } else if (\n to === TOUCHABLE_STATE.UNDETERMINED ||\n to === TOUCHABLE_STATE.MOVED_OUTSIDE\n ) {\n this.hideUnderlay();\n }\n };\n\n render() {\n const { style = {}, ...rest } = this.props;\n const { extraUnderlayStyle } = this.state;\n return (\n \n {this.renderChildren()}\n \n );\n }\n}\n"]} \ No newline at end of file diff --git a/lib/module/components/touchables/TouchableNativeFeedback.android.js b/lib/module/components/touchables/TouchableNativeFeedback.android.js new file mode 100644 index 0000000000..8922c64e9c --- /dev/null +++ b/lib/module/components/touchables/TouchableNativeFeedback.android.js @@ -0,0 +1,84 @@ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +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; } + +import { Platform } from 'react-native'; +import * as React from 'react'; +import { Component } from 'react'; +import GenericTouchable from './GenericTouchable'; + +/** + * TouchableNativeFeedback behaves slightly different than RN's TouchableNativeFeedback. + * There's small difference with handling long press ripple since RN's implementation calls + * ripple animation via bridge. This solution leaves all animations' handling for native components so + * it follows native behaviours. + */ +export default class TouchableNativeFeedback extends Component { + // could be taken as RNTouchableNativeFeedback.SelectableBackground etc. but the API may change + getExtraButtonProps() { + const extraProps = {}; + const { + background + } = this.props; + + if (background) { + // I changed type values to match those used in RN + // TODO(TS): check if it works the same as previous implementation - looks like it works the same as RN component, so it should be ok + if (background.type === 'RippleAndroid') { + extraProps['borderless'] = background.borderless; + extraProps['rippleColor'] = background.color; + } else if (background.type === 'ThemeAttrAndroid') { + extraProps['borderless'] = background.attribute === 'selectableItemBackgroundBorderless'; + } // I moved it from above since it should be available in all options + + + extraProps['rippleRadius'] = background.rippleRadius; + } + + extraProps['foreground'] = this.props.useForeground; + return extraProps; + } + + render() { + const { + style = {}, + ...rest + } = this.props; + return /*#__PURE__*/React.createElement(GenericTouchable, _extends({}, rest, { + style: style, + extraButtonProps: this.getExtraButtonProps() + })); + } + +} + +_defineProperty(TouchableNativeFeedback, "defaultProps", { ...GenericTouchable.defaultProps, + useForeground: true, + extraButtonProps: { + // Disable hiding ripple on Android + rippleColor: null + } +}); + +_defineProperty(TouchableNativeFeedback, "SelectableBackground", rippleRadius => ({ + type: 'ThemeAttrAndroid', + // I added `attribute` prop to clone the implementation of RN and be able to use only 2 types + attribute: 'selectableItemBackground', + rippleRadius +})); + +_defineProperty(TouchableNativeFeedback, "SelectableBackgroundBorderless", rippleRadius => ({ + type: 'ThemeAttrAndroid', + attribute: 'selectableItemBackgroundBorderless', + rippleRadius +})); + +_defineProperty(TouchableNativeFeedback, "Ripple", (color, borderless, rippleRadius) => ({ + type: 'RippleAndroid', + color, + borderless, + rippleRadius +})); + +_defineProperty(TouchableNativeFeedback, "canUseNativeForeground", () => Platform.Version >= 23); +//# sourceMappingURL=TouchableNativeFeedback.android.js.map \ No newline at end of file diff --git a/lib/module/components/touchables/TouchableNativeFeedback.android.js.map b/lib/module/components/touchables/TouchableNativeFeedback.android.js.map new file mode 100644 index 0000000000..b5cb68b7c8 --- /dev/null +++ b/lib/module/components/touchables/TouchableNativeFeedback.android.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TouchableNativeFeedback.android.tsx"],"names":["Platform","React","Component","GenericTouchable","TouchableNativeFeedback","getExtraButtonProps","extraProps","background","props","type","borderless","color","attribute","rippleRadius","useForeground","render","style","rest","defaultProps","extraButtonProps","rippleColor","Version"],"mappings":";;;;AAAA,SACEA,QADF,QAIO,cAJP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IAAAA,WAAW,EAAE;AAFG;AAHE,C;;gBAHHhB,uB,0BAaYS,YAAD,KAA4B;AACxDJ,EAAAA,IAAI,EAAE,kBADkD;AAExD;AACAG,EAAAA,SAAS,EAAE,0BAH6C;AAIxDC,EAAAA;AAJwD,CAA5B,C;;gBAbXT,uB,oCAmBsBS,YAAD,KAA4B;AAClEJ,EAAAA,IAAI,EAAE,kBAD4D;AAElEG,EAAAA,SAAS,EAAE,oCAFuD;AAGlEC,EAAAA;AAHkE,CAA5B,C;;gBAnBrBT,uB,YAwBH,CACdO,KADc,EAEdD,UAFc,EAGdG,YAHc,MAIV;AACJJ,EAAAA,IAAI,EAAE,eADF;AAEJE,EAAAA,KAFI;AAGJD,EAAAA,UAHI;AAIJG,EAAAA;AAJI,CAJU,C;;gBAxBGT,uB,4BAmCa,MAAMJ,QAAQ,CAACqB,OAAT,IAAoB,E","sourcesContent":["import {\n Platform,\n TouchableNativeFeedbackProps,\n ColorValue,\n} from 'react-native';\nimport * as React from 'react';\nimport { Component } from 'react';\nimport GenericTouchable, { GenericTouchableProps } from './GenericTouchable';\n\nexport type TouchableNativeFeedbackExtraProps = {\n borderless?: boolean;\n rippleColor?: number | null;\n rippleRadius?: number | null;\n foreground?: boolean;\n};\n\n/**\n * TouchableNativeFeedback behaves slightly different than RN's TouchableNativeFeedback.\n * There's small difference with handling long press ripple since RN's implementation calls\n * ripple animation via bridge. This solution leaves all animations' handling for native components so\n * it follows native behaviours.\n */\nexport default class TouchableNativeFeedback extends Component<\n TouchableNativeFeedbackProps & GenericTouchableProps\n> {\n static defaultProps = {\n ...GenericTouchable.defaultProps,\n useForeground: true,\n extraButtonProps: {\n // Disable hiding ripple on Android\n rippleColor: null,\n },\n };\n\n // could be taken as RNTouchableNativeFeedback.SelectableBackground etc. but the API may change\n static SelectableBackground = (rippleRadius?: number) => ({\n type: 'ThemeAttrAndroid',\n // I added `attribute` prop to clone the implementation of RN and be able to use only 2 types\n attribute: 'selectableItemBackground',\n rippleRadius,\n });\n static SelectableBackgroundBorderless = (rippleRadius?: number) => ({\n type: 'ThemeAttrAndroid',\n attribute: 'selectableItemBackgroundBorderless',\n rippleRadius,\n });\n static Ripple = (\n color: ColorValue,\n borderless: boolean,\n rippleRadius?: number\n ) => ({\n type: 'RippleAndroid',\n color,\n borderless,\n rippleRadius,\n });\n\n static canUseNativeForeground = () => Platform.Version >= 23;\n\n getExtraButtonProps() {\n const extraProps: TouchableNativeFeedbackExtraProps = {};\n const { background } = this.props;\n if (background) {\n // I changed type values to match those used in RN\n // TODO(TS): check if it works the same as previous implementation - looks like it works the same as RN component, so it should be ok\n if (background.type === 'RippleAndroid') {\n extraProps['borderless'] = background.borderless;\n extraProps['rippleColor'] = background.color;\n } else if (background.type === 'ThemeAttrAndroid') {\n extraProps['borderless'] =\n background.attribute === 'selectableItemBackgroundBorderless';\n }\n // I moved it from above since it should be available in all options\n extraProps['rippleRadius'] = background.rippleRadius;\n }\n extraProps['foreground'] = this.props.useForeground;\n return extraProps;\n }\n render() {\n const { style = {}, ...rest } = this.props;\n return (\n \n );\n }\n}\n"]} \ No newline at end of file diff --git a/lib/module/components/touchables/TouchableNativeFeedback.js b/lib/module/components/touchables/TouchableNativeFeedback.js new file mode 100644 index 0000000000..d75a3e2883 --- /dev/null +++ b/lib/module/components/touchables/TouchableNativeFeedback.js @@ -0,0 +1,3 @@ +import { TouchableNativeFeedback } from 'react-native'; +export default TouchableNativeFeedback; +//# sourceMappingURL=TouchableNativeFeedback.js.map \ No newline at end of file diff --git a/lib/module/components/touchables/TouchableNativeFeedback.js.map b/lib/module/components/touchables/TouchableNativeFeedback.js.map new file mode 100644 index 0000000000..aaa81bad77 --- /dev/null +++ b/lib/module/components/touchables/TouchableNativeFeedback.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TouchableNativeFeedback.tsx"],"names":["TouchableNativeFeedback"],"mappings":"AAAA,SAASA,uBAAT,QAAwC,cAAxC;AAEA,eAAeA,uBAAf","sourcesContent":["import { TouchableNativeFeedback } from 'react-native';\n\nexport default TouchableNativeFeedback;\n"]} \ No newline at end of file diff --git a/lib/module/components/touchables/TouchableOpacity.js b/lib/module/components/touchables/TouchableOpacity.js new file mode 100644 index 0000000000..0232b77a21 --- /dev/null +++ b/lib/module/components/touchables/TouchableOpacity.js @@ -0,0 +1,61 @@ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +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; } + +import { Animated, Easing, StyleSheet, View } from 'react-native'; +import GenericTouchable, { TOUCHABLE_STATE } from './GenericTouchable'; +import * as React from 'react'; +import { Component } from 'react'; +/** + * TouchableOpacity bases on timing animation which has been used in RN's core + */ + +export default class TouchableOpacity extends Component { + constructor(...args) { + super(...args); + + _defineProperty(this, "getChildStyleOpacityWithDefault", () => { + const childStyle = StyleSheet.flatten(this.props.style) || {}; + return childStyle.opacity == null ? 1 : childStyle.opacity; + }); + + _defineProperty(this, "opacity", new Animated.Value(this.getChildStyleOpacityWithDefault())); + + _defineProperty(this, "setOpacityTo", (value, duration) => { + Animated.timing(this.opacity, { + toValue: value, + duration: duration, + easing: Easing.inOut(Easing.quad), + useNativeDriver: false + }).start(); + }); + + _defineProperty(this, "onStateChange", (_from, to) => { + if (to === TOUCHABLE_STATE.BEGAN) { + this.setOpacityTo(this.props.activeOpacity, 0); + } else if (to === TOUCHABLE_STATE.UNDETERMINED || to === TOUCHABLE_STATE.MOVED_OUTSIDE) { + this.setOpacityTo(this.getChildStyleOpacityWithDefault(), 150); + } + }); + } + + render() { + const { + style = {}, + ...rest + } = this.props; + return /*#__PURE__*/React.createElement(GenericTouchable, _extends({}, rest, { + style: [style, { + opacity: this.opacity // TODO: fix this + + }], + onStateChange: this.onStateChange + }), this.props.children ? this.props.children : /*#__PURE__*/React.createElement(View, null)); + } + +} + +_defineProperty(TouchableOpacity, "defaultProps", { ...GenericTouchable.defaultProps, + activeOpacity: 0.2 +}); +//# sourceMappingURL=TouchableOpacity.js.map \ No newline at end of file diff --git a/lib/module/components/touchables/TouchableOpacity.js.map b/lib/module/components/touchables/TouchableOpacity.js.map new file mode 100644 index 0000000000..9f2f9db905 --- /dev/null +++ b/lib/module/components/touchables/TouchableOpacity.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TouchableOpacity.tsx"],"names":["Animated","Easing","StyleSheet","View","GenericTouchable","TOUCHABLE_STATE","React","Component","TouchableOpacity","childStyle","flatten","props","style","opacity","Value","getChildStyleOpacityWithDefault","value","duration","timing","toValue","easing","inOut","quad","useNativeDriver","start","_from","to","BEGAN","setOpacityTo","activeOpacity","UNDETERMINED","MOVED_OUTSIDE","render","rest","onStateChange","children","defaultProps"],"mappings":";;;;AAAA,SACEA,QADF,EAEEC,MAFF,EAGEC,UAHF,EAIEC,IAJF,QAMO,cANP;AAOA,OAAOC,gBAAP,IACEC,eADF,QAGO,oBAHP;AAIA,OAAO,KAAKC,KAAZ,MAAuB,OAAvB;AACA,SAASC,SAAT,QAA0B,OAA1B;AAEA;AACA;AACA;;AACA,eAAe,MAAMC,gBAAN,SAA+BD,SAA/B,CAEb;AAAA;AAAA;;AAAA,6DAOkC,MAAM;AACtC,YAAME,UAAU,GAAGP,UAAU,CAACQ,OAAX,CAAmB,KAAKC,KAAL,CAAWC,KAA9B,KAAwC,EAA3D;AACA,aAAOH,UAAU,CAACI,OAAX,IAAsB,IAAtB,GAA6B,CAA7B,GAAiCJ,UAAU,CAACI,OAAnD;AACD,KAVD;;AAAA,qCAYU,IAAIb,QAAQ,CAACc,KAAb,CAAmB,KAAKC,+BAAL,EAAnB,CAZV;;AAAA,0CAce,CAACC,KAAD,EAAgBC,QAAhB,KAAqC;AAClDjB,MAAAA,QAAQ,CAACkB,MAAT,CAAgB,KAAKL,OAArB,EAA8B;AAC5BM,QAAAA,OAAO,EAAEH,KADmB;AAE5BC,QAAAA,QAAQ,EAAEA,QAFkB;AAG5BG,QAAAA,MAAM,EAAEnB,MAAM,CAACoB,KAAP,CAAapB,MAAM,CAACqB,IAApB,CAHoB;AAI5BC,QAAAA,eAAe,EAAE;AAJW,OAA9B,EAKGC,KALH;AAMD,KArBD;;AAAA,2CAuBgB,CAACC,KAAD,EAAgBC,EAAhB,KAA+B;AAC7C,UAAIA,EAAE,KAAKrB,eAAe,CAACsB,KAA3B,EAAkC;AAChC,aAAKC,YAAL,CAAkB,KAAKjB,KAAL,CAAWkB,aAA7B,EAA6C,CAA7C;AACD,OAFD,MAEO,IACLH,EAAE,KAAKrB,eAAe,CAACyB,YAAvB,IACAJ,EAAE,KAAKrB,eAAe,CAAC0B,aAFlB,EAGL;AACA,aAAKH,YAAL,CAAkB,KAAKb,+BAAL,EAAlB,EAA0D,GAA1D;AACD;AACF,KAhCD;AAAA;;AAkCAiB,EAAAA,MAAM,GAAG;AACP,UAAM;AAAEpB,MAAAA,KAAK,GAAG,EAAV;AAAc,SAAGqB;AAAjB,QAA0B,KAAKtB,KAArC;AACA,wBACE,oBAAC,gBAAD,eACMsB,IADN;AAEE,MAAA,KAAK,EAAE,CACLrB,KADK,EAEL;AACEC,QAAAA,OAAO,EAAG,KAAKA,OADjB,CACgD;;AADhD,OAFK,CAFT;AAQE,MAAA,aAAa,EAAE,KAAKqB;AARtB,QASG,KAAKvB,KAAL,CAAWwB,QAAX,GAAsB,KAAKxB,KAAL,CAAWwB,QAAjC,gBAA4C,oBAAC,IAAD,OAT/C,CADF;AAaD;;AAjDD;;gBAFmB3B,gB,kBAGG,EACpB,GAAGJ,gBAAgB,CAACgC,YADA;AAEpBP,EAAAA,aAAa,EAAE;AAFK,C","sourcesContent":["import {\n Animated,\n Easing,\n StyleSheet,\n View,\n TouchableOpacityProps,\n} from 'react-native';\nimport GenericTouchable, {\n TOUCHABLE_STATE,\n GenericTouchableProps,\n} from './GenericTouchable';\nimport * as React from 'react';\nimport { Component } from 'react';\n\n/**\n * TouchableOpacity bases on timing animation which has been used in RN's core\n */\nexport default class TouchableOpacity extends Component<\n TouchableOpacityProps & GenericTouchableProps\n> {\n static defaultProps = {\n ...GenericTouchable.defaultProps,\n activeOpacity: 0.2,\n };\n\n // opacity is 1 one by default but could be overwritten\n getChildStyleOpacityWithDefault = () => {\n const childStyle = StyleSheet.flatten(this.props.style) || {};\n return childStyle.opacity == null ? 1 : childStyle.opacity;\n };\n\n opacity = new Animated.Value(this.getChildStyleOpacityWithDefault());\n\n setOpacityTo = (value: number, duration: number) => {\n Animated.timing(this.opacity, {\n toValue: value,\n duration: duration,\n easing: Easing.inOut(Easing.quad),\n useNativeDriver: false,\n }).start();\n };\n\n onStateChange = (_from: number, to: number) => {\n if (to === TOUCHABLE_STATE.BEGAN) {\n this.setOpacityTo(this.props.activeOpacity!, 0);\n } else if (\n to === TOUCHABLE_STATE.UNDETERMINED ||\n to === TOUCHABLE_STATE.MOVED_OUTSIDE\n ) {\n this.setOpacityTo(this.getChildStyleOpacityWithDefault(), 150);\n }\n };\n\n render() {\n const { style = {}, ...rest } = this.props;\n return (\n \n {this.props.children ? this.props.children : }\n \n );\n }\n}\n"]} \ No newline at end of file diff --git a/lib/module/components/touchables/TouchableWithoutFeedback.js b/lib/module/components/touchables/TouchableWithoutFeedback.js new file mode 100644 index 0000000000..163396ae11 --- /dev/null +++ b/lib/module/components/touchables/TouchableWithoutFeedback.js @@ -0,0 +1,10 @@ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +import * as React from 'react'; +import GenericTouchable from './GenericTouchable'; +const TouchableWithoutFeedback = /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/React.createElement(GenericTouchable, _extends({ + ref: ref +}, props))); +TouchableWithoutFeedback.defaultProps = GenericTouchable.defaultProps; +export default TouchableWithoutFeedback; +//# sourceMappingURL=TouchableWithoutFeedback.js.map \ No newline at end of file diff --git a/lib/module/components/touchables/TouchableWithoutFeedback.js.map b/lib/module/components/touchables/TouchableWithoutFeedback.js.map new file mode 100644 index 0000000000..082ee5ecd2 --- /dev/null +++ b/lib/module/components/touchables/TouchableWithoutFeedback.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TouchableWithoutFeedback.tsx"],"names":["React","GenericTouchable","TouchableWithoutFeedback","forwardRef","props","ref","defaultProps"],"mappings":";;AAAA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AAEA,OAAOC,gBAAP,MAAwD,oBAAxD;AAEA,MAAMC,wBAAwB,gBAAGF,KAAK,CAACG,UAAN,CAG/B,CAACC,KAAD,EAAQC,GAAR,kBAAgB,oBAAC,gBAAD;AAAkB,EAAA,GAAG,EAAEA;AAAvB,GAAgCD,KAAhC,EAHe,CAAjC;AAKAF,wBAAwB,CAACI,YAAzB,GAAwCL,gBAAgB,CAACK,YAAzD;AAEA,eAAeJ,wBAAf","sourcesContent":["import * as React from 'react';\nimport { PropsWithChildren } from 'react';\nimport GenericTouchable, { GenericTouchableProps } from './GenericTouchable';\n\nconst TouchableWithoutFeedback = React.forwardRef<\n GenericTouchable,\n PropsWithChildren\n>((props, ref) => );\n\nTouchableWithoutFeedback.defaultProps = GenericTouchable.defaultProps;\n\nexport default TouchableWithoutFeedback;\n"]} \ No newline at end of file diff --git a/lib/module/components/touchables/index.js b/lib/module/components/touchables/index.js new file mode 100644 index 0000000000..cd5165ed66 --- /dev/null +++ b/lib/module/components/touchables/index.js @@ -0,0 +1,5 @@ +export { default as TouchableNativeFeedback } from './TouchableNativeFeedback'; +export { default as TouchableWithoutFeedback } from './TouchableWithoutFeedback'; +export { default as TouchableOpacity } from './TouchableOpacity'; +export { default as TouchableHighlight } from './TouchableHighlight'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/module/components/touchables/index.js.map b/lib/module/components/touchables/index.js.map new file mode 100644 index 0000000000..9e6c56cd77 --- /dev/null +++ b/lib/module/components/touchables/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["index.ts"],"names":["default","TouchableNativeFeedback","TouchableWithoutFeedback","TouchableOpacity","TouchableHighlight"],"mappings":"AAAA,SAASA,OAAO,IAAIC,uBAApB,QAAmD,2BAAnD;AACA,SAASD,OAAO,IAAIE,wBAApB,QAAoD,4BAApD;AACA,SAASF,OAAO,IAAIG,gBAApB,QAA4C,oBAA5C;AACA,SAASH,OAAO,IAAII,kBAApB,QAA8C,sBAA9C","sourcesContent":["export { default as TouchableNativeFeedback } from './TouchableNativeFeedback';\nexport { default as TouchableWithoutFeedback } from './TouchableWithoutFeedback';\nexport { default as TouchableOpacity } from './TouchableOpacity';\nexport { default as TouchableHighlight } from './TouchableHighlight';\n"]} \ No newline at end of file diff --git a/lib/module/gestureHandlerRootHOC.js b/lib/module/gestureHandlerRootHOC.js new file mode 100644 index 0000000000..e297666751 --- /dev/null +++ b/lib/module/gestureHandlerRootHOC.js @@ -0,0 +1,21 @@ +import * as React from 'react'; +import { StyleSheet } from 'react-native'; +import hoistNonReactStatics from 'hoist-non-react-statics'; +import GestureHandlerRootView from './GestureHandlerRootView'; +export default function gestureHandlerRootHOC(Component, containerStyles) { + function Wrapper(props) { + return /*#__PURE__*/React.createElement(GestureHandlerRootView, { + style: [styles.container, containerStyles] + }, /*#__PURE__*/React.createElement(Component, props)); + } + + Wrapper.displayName = `gestureHandlerRootHOC(${Component.displayName || Component.name})`; + hoistNonReactStatics(Wrapper, Component); + return Wrapper; +} +const styles = StyleSheet.create({ + container: { + flex: 1 + } +}); +//# sourceMappingURL=gestureHandlerRootHOC.js.map \ No newline at end of file diff --git a/lib/module/gestureHandlerRootHOC.js.map b/lib/module/gestureHandlerRootHOC.js.map new file mode 100644 index 0000000000..5bc0449fa1 --- /dev/null +++ b/lib/module/gestureHandlerRootHOC.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["gestureHandlerRootHOC.tsx"],"names":["React","StyleSheet","hoistNonReactStatics","GestureHandlerRootView","gestureHandlerRootHOC","Component","containerStyles","Wrapper","props","styles","container","displayName","name","create","flex"],"mappings":"AAAA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AACA,SAASC,UAAT,QAAiD,cAAjD;AACA,OAAOC,oBAAP,MAAiC,yBAAjC;AACA,OAAOC,sBAAP,MAAmC,0BAAnC;AAEA,eAAe,SAASC,qBAAT,CACbC,SADa,EAEbC,eAFa,EAGW;AACxB,WAASC,OAAT,CAAiBC,KAAjB,EAA2B;AACzB,wBACE,oBAAC,sBAAD;AAAwB,MAAA,KAAK,EAAE,CAACC,MAAM,CAACC,SAAR,EAAmBJ,eAAnB;AAA/B,oBACE,oBAAC,SAAD,EAAeE,KAAf,CADF,CADF;AAKD;;AAEDD,EAAAA,OAAO,CAACI,WAAR,GAAuB,yBACrBN,SAAS,CAACM,WAAV,IAAyBN,SAAS,CAACO,IACpC,GAFD;AAIAV,EAAAA,oBAAoB,CAACK,OAAD,EAAUF,SAAV,CAApB;AAEA,SAAOE,OAAP;AACD;AAED,MAAME,MAAM,GAAGR,UAAU,CAACY,MAAX,CAAkB;AAC/BH,EAAAA,SAAS,EAAE;AAAEI,IAAAA,IAAI,EAAE;AAAR;AADoB,CAAlB,CAAf","sourcesContent":["import * as React from 'react';\nimport { StyleSheet, StyleProp, ViewStyle } from 'react-native';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport GestureHandlerRootView from './GestureHandlerRootView';\n\nexport default function gestureHandlerRootHOC

(\n Component: React.ComponentType

,\n containerStyles?: StyleProp\n): React.ComponentType

{\n function Wrapper(props: P) {\n return (\n \n \n \n );\n }\n\n Wrapper.displayName = `gestureHandlerRootHOC(${\n Component.displayName || Component.name\n })`;\n\n hoistNonReactStatics(Wrapper, Component);\n\n return Wrapper;\n}\n\nconst styles = StyleSheet.create({\n container: { flex: 1 },\n});\n"]} \ No newline at end of file diff --git a/lib/module/handlers/FlingGestureHandler.js b/lib/module/handlers/FlingGestureHandler.js new file mode 100644 index 0000000000..7a1bae8034 --- /dev/null +++ b/lib/module/handlers/FlingGestureHandler.js @@ -0,0 +1,10 @@ +import createHandler from './createHandler'; +import { baseGestureHandlerProps } from './gestureHandlerCommon'; +export const flingGestureHandlerProps = ['numberOfPointers', 'direction']; +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +export const FlingGestureHandler = createHandler({ + name: 'FlingGestureHandler', + allowedProps: [...baseGestureHandlerProps, ...flingGestureHandlerProps], + config: {} +}); +//# sourceMappingURL=FlingGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/handlers/FlingGestureHandler.js.map b/lib/module/handlers/FlingGestureHandler.js.map new file mode 100644 index 0000000000..f54dd81d67 --- /dev/null +++ b/lib/module/handlers/FlingGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["FlingGestureHandler.ts"],"names":["createHandler","baseGestureHandlerProps","flingGestureHandlerProps","FlingGestureHandler","name","allowedProps","config"],"mappings":"AAAA,OAAOA,aAAP,MAA0B,iBAA1B;AACA,SAEEC,uBAFF,QAGO,wBAHP;AAKA,OAAO,MAAMC,wBAAwB,GAAG,CACtC,kBADsC,EAEtC,WAFsC,CAAjC;AAuCP;AACA,OAAO,MAAMC,mBAAmB,GAAGH,aAAa,CAG9C;AACAI,EAAAA,IAAI,EAAE,qBADN;AAEAC,EAAAA,YAAY,EAAE,CACZ,GAAGJ,uBADS,EAEZ,GAAGC,wBAFS,CAFd;AAMAI,EAAAA,MAAM,EAAE;AANR,CAH8C,CAAzC","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport const flingGestureHandlerProps = [\n 'numberOfPointers',\n 'direction',\n] as const;\n\nexport type FlingGestureHandlerEventPayload = {\n x: number;\n y: number;\n absoluteX: number;\n absoluteY: number;\n};\nexport interface FlingGestureConfig {\n /**\n * Expressed allowed direction of movement. It's possible to pass one or many\n * directions in one parameter:\n *\n * ```js\n * direction={Directions.RIGHT | Directions.LEFT}\n * ```\n *\n * or\n *\n * ```js\n * direction={Directions.DOWN}\n * ```\n */\n direction?: number;\n\n /**\n * Determine exact number of points required to handle the fling gesture.\n */\n numberOfPointers?: number;\n}\n\nexport interface FlingGestureHandlerProps\n extends BaseGestureHandlerProps,\n FlingGestureConfig {}\n\nexport type FlingGestureHandler = typeof FlingGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const FlingGestureHandler = createHandler<\n FlingGestureHandlerProps,\n FlingGestureHandlerEventPayload\n>({\n name: 'FlingGestureHandler',\n allowedProps: [\n ...baseGestureHandlerProps,\n ...flingGestureHandlerProps,\n ] as const,\n config: {},\n});\n"]} \ No newline at end of file diff --git a/lib/module/handlers/ForceTouchGestureHandler.js b/lib/module/handlers/ForceTouchGestureHandler.js new file mode 100644 index 0000000000..6b4696c197 --- /dev/null +++ b/lib/module/handlers/ForceTouchGestureHandler.js @@ -0,0 +1,29 @@ +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; } + +import React from 'react'; +import PlatformConstants from '../PlatformConstants'; +import createHandler from './createHandler'; +import { baseGestureHandlerProps } from './gestureHandlerCommon'; +export const forceTouchGestureHandlerProps = ['minForce', 'maxForce', 'feedbackOnActivation']; + +class ForceTouchFallback extends React.Component { + componentDidMount() { + console.warn('ForceTouchGestureHandler is not available on this platform. Please use ForceTouchGestureHandler.forceTouchAvailable to conditionally render other components that would provide a fallback behavior specific to your usecase'); + } + + render() { + return this.props.children; + } + +} + +_defineProperty(ForceTouchFallback, "forceTouchAvailable", false); + +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +export const ForceTouchGestureHandler = PlatformConstants !== null && PlatformConstants !== void 0 && PlatformConstants.forceTouchAvailable ? createHandler({ + name: 'ForceTouchGestureHandler', + allowedProps: [...baseGestureHandlerProps, ...forceTouchGestureHandlerProps], + config: {} +}) : ForceTouchFallback; +ForceTouchGestureHandler.forceTouchAvailable = (PlatformConstants === null || PlatformConstants === void 0 ? void 0 : PlatformConstants.forceTouchAvailable) || false; +//# sourceMappingURL=ForceTouchGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/handlers/ForceTouchGestureHandler.js.map b/lib/module/handlers/ForceTouchGestureHandler.js.map new file mode 100644 index 0000000000..77f7897468 --- /dev/null +++ b/lib/module/handlers/ForceTouchGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["ForceTouchGestureHandler.ts"],"names":["React","PlatformConstants","createHandler","baseGestureHandlerProps","forceTouchGestureHandlerProps","ForceTouchFallback","Component","componentDidMount","console","warn","render","props","children","ForceTouchGestureHandler","forceTouchAvailable","name","allowedProps","config"],"mappings":";;AAAA,OAAOA,KAAP,MAAkB,OAAlB;AACA,OAAOC,iBAAP,MAA8B,sBAA9B;AACA,OAAOC,aAAP,MAA0B,iBAA1B;AACA,SAEEC,uBAFF,QAGO,wBAHP;AAKA,OAAO,MAAMC,6BAA6B,GAAG,CAC3C,UAD2C,EAE3C,UAF2C,EAG3C,sBAH2C,CAAtC;;AAMP,MAAMC,kBAAN,SAAiCL,KAAK,CAACM,SAAvC,CAAiD;AAE/CC,EAAAA,iBAAiB,GAAG;AAClBC,IAAAA,OAAO,CAACC,IAAR,CACE,8NADF;AAGD;;AACDC,EAAAA,MAAM,GAAG;AACP,WAAO,KAAKC,KAAL,CAAWC,QAAlB;AACD;;AAT8C;;gBAA3CP,kB,yBACyB,K;;AAmD/B;AACA,OAAO,MAAMQ,wBAAwB,GAAGZ,iBAAiB,SAAjB,IAAAA,iBAAiB,WAAjB,IAAAA,iBAAiB,CAAEa,mBAAnB,GACpCZ,aAAa,CAGX;AACAa,EAAAA,IAAI,EAAE,0BADN;AAEAC,EAAAA,YAAY,EAAE,CACZ,GAAGb,uBADS,EAEZ,GAAGC,6BAFS,CAFd;AAMAa,EAAAA,MAAM,EAAE;AANR,CAHW,CADuB,GAYpCZ,kBAZG;AAcNQ,wBAAD,CAAuDC,mBAAvD,GACE,CAAAb,iBAAiB,SAAjB,IAAAA,iBAAiB,WAAjB,YAAAA,iBAAiB,CAAEa,mBAAnB,KAA0C,KAD5C","sourcesContent":["import React from 'react';\nimport PlatformConstants from '../PlatformConstants';\nimport createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport const forceTouchGestureHandlerProps = [\n 'minForce',\n 'maxForce',\n 'feedbackOnActivation',\n] as const;\n\nclass ForceTouchFallback extends React.Component {\n static forceTouchAvailable = false;\n componentDidMount() {\n console.warn(\n 'ForceTouchGestureHandler is not available on this platform. Please use ForceTouchGestureHandler.forceTouchAvailable to conditionally render other components that would provide a fallback behavior specific to your usecase'\n );\n }\n render() {\n return this.props.children;\n }\n}\n\nexport type ForceTouchGestureHandlerEventPayload = {\n x: number;\n y: number;\n absoluteX: number;\n absoluteY: number;\n\n /**\n * The pressure of a touch.\n */\n force: number;\n};\n\nexport interface ForceTouchGestureConfig {\n /**\n *\n * A minimal pressure that is required before handler can activate. Should be a\n * value from range `[0.0, 1.0]`. Default is `0.2`.\n */\n minForce?: number;\n\n /**\n * A maximal pressure that could be applied for handler. If the pressure is\n * greater, handler fails. Should be a value from range `[0.0, 1.0]`.\n */\n maxForce?: number;\n\n /**\n * Boolean value defining if haptic feedback has to be performed on\n * activation.\n */\n feedbackOnActivation?: boolean;\n}\n\nexport interface ForceTouchGestureHandlerProps\n extends BaseGestureHandlerProps,\n ForceTouchGestureConfig {}\n\nexport type ForceTouchGestureHandler = typeof ForceTouchGestureHandler & {\n forceTouchAvailable: boolean;\n};\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const ForceTouchGestureHandler = PlatformConstants?.forceTouchAvailable\n ? createHandler<\n ForceTouchGestureHandlerProps,\n ForceTouchGestureHandlerEventPayload\n >({\n name: 'ForceTouchGestureHandler',\n allowedProps: [\n ...baseGestureHandlerProps,\n ...forceTouchGestureHandlerProps,\n ] as const,\n config: {},\n })\n : ForceTouchFallback;\n\n(ForceTouchGestureHandler as ForceTouchGestureHandler).forceTouchAvailable =\n PlatformConstants?.forceTouchAvailable || false;\n"]} \ No newline at end of file diff --git a/lib/module/handlers/LongPressGestureHandler.js b/lib/module/handlers/LongPressGestureHandler.js new file mode 100644 index 0000000000..6136a769f9 --- /dev/null +++ b/lib/module/handlers/LongPressGestureHandler.js @@ -0,0 +1,10 @@ +import createHandler from './createHandler'; +import { baseGestureHandlerProps } from './gestureHandlerCommon'; +export const longPressGestureHandlerProps = ['minDurationMs', 'maxDist']; +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +export const LongPressGestureHandler = createHandler({ + name: 'LongPressGestureHandler', + allowedProps: [...baseGestureHandlerProps, ...longPressGestureHandlerProps], + config: {} +}); +//# sourceMappingURL=LongPressGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/handlers/LongPressGestureHandler.js.map b/lib/module/handlers/LongPressGestureHandler.js.map new file mode 100644 index 0000000000..8422049185 --- /dev/null +++ b/lib/module/handlers/LongPressGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["LongPressGestureHandler.ts"],"names":["createHandler","baseGestureHandlerProps","longPressGestureHandlerProps","LongPressGestureHandler","name","allowedProps","config"],"mappings":"AAAA,OAAOA,aAAP,MAA0B,iBAA1B;AACA,SAEEC,uBAFF,QAGO,wBAHP;AAKA,OAAO,MAAMC,4BAA4B,GAAG,CAC1C,eAD0C,EAE1C,SAF0C,CAArC;AAkEP;AACA,OAAO,MAAMC,uBAAuB,GAAGH,aAAa,CAGlD;AACAI,EAAAA,IAAI,EAAE,yBADN;AAEAC,EAAAA,YAAY,EAAE,CACZ,GAAGJ,uBADS,EAEZ,GAAGC,4BAFS,CAFd;AAMAI,EAAAA,MAAM,EAAE;AANR,CAHkD,CAA7C","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport const longPressGestureHandlerProps = [\n 'minDurationMs',\n 'maxDist',\n] as const;\n\nexport type LongPressGestureHandlerEventPayload = {\n /**\n * X coordinate, expressed in points, of the current position of the pointer\n * (finger or a leading pointer when there are multiple fingers placed)\n * relative to the view attached to the handler.\n */\n x: number;\n\n /**\n * Y coordinate, expressed in points, of the current position of the pointer\n * (finger or a leading pointer when there are multiple fingers placed)\n * relative to the view attached to the handler.\n */\n y: number;\n\n /**\n * X coordinate, expressed in points, of the current position of the pointer\n * (finger or a leading pointer when there are multiple fingers placed)\n * relative to the window. It is recommended to use `absoluteX` instead of\n * `x` in cases when the view attached to the handler can be transformed as an\n * effect of the gesture.\n */\n absoluteX: number;\n\n /**\n * Y coordinate, expressed in points, of the current position of the pointer\n * (finger or a leading pointer when there are multiple fingers placed)\n * relative to the window. It is recommended to use `absoluteY` instead of\n * `y` in cases when the view attached to the handler can be transformed as an\n * effect of the gesture.\n */\n absoluteY: number;\n\n /**\n * Duration of the long press (time since the start of the event), expressed\n * in milliseconds.\n */\n duration: number;\n};\n\nexport interface LongPressGestureConfig {\n /**\n * Minimum time, expressed in milliseconds, that a finger must remain pressed on\n * the corresponding view. The default value is 500.\n */\n minDurationMs?: number;\n\n /**\n * Maximum distance, expressed in points, that defines how far the finger is\n * allowed to travel during a long press gesture. If the finger travels\n * further than the defined distance and the handler hasn't yet activated, it\n * will fail to recognize the gesture. The default value is 10.\n */\n maxDist?: number;\n}\n\nexport interface LongPressGestureHandlerProps\n extends BaseGestureHandlerProps,\n LongPressGestureConfig {}\n\nexport type LongPressGestureHandler = typeof LongPressGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const LongPressGestureHandler = createHandler<\n LongPressGestureHandlerProps,\n LongPressGestureHandlerEventPayload\n>({\n name: 'LongPressGestureHandler',\n allowedProps: [\n ...baseGestureHandlerProps,\n ...longPressGestureHandlerProps,\n ] as const,\n config: {},\n});\n"]} \ No newline at end of file diff --git a/lib/module/handlers/NativeViewGestureHandler.js b/lib/module/handlers/NativeViewGestureHandler.js new file mode 100644 index 0000000000..b5b05bc628 --- /dev/null +++ b/lib/module/handlers/NativeViewGestureHandler.js @@ -0,0 +1,11 @@ +import createHandler from './createHandler'; +import { baseGestureHandlerProps } from './gestureHandlerCommon'; +export const nativeViewGestureHandlerProps = ['shouldActivateOnStart', 'disallowInterruption']; +export const nativeViewProps = [...baseGestureHandlerProps, ...nativeViewGestureHandlerProps]; +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +export const NativeViewGestureHandler = createHandler({ + name: 'NativeViewGestureHandler', + allowedProps: nativeViewProps, + config: {} +}); +//# sourceMappingURL=NativeViewGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/handlers/NativeViewGestureHandler.js.map b/lib/module/handlers/NativeViewGestureHandler.js.map new file mode 100644 index 0000000000..a884f5f4c9 --- /dev/null +++ b/lib/module/handlers/NativeViewGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["NativeViewGestureHandler.ts"],"names":["createHandler","baseGestureHandlerProps","nativeViewGestureHandlerProps","nativeViewProps","NativeViewGestureHandler","name","allowedProps","config"],"mappings":"AAAA,OAAOA,aAAP,MAA0B,iBAA1B;AACA,SAEEC,uBAFF,QAGO,wBAHP;AAKA,OAAO,MAAMC,6BAA6B,GAAG,CAC3C,uBAD2C,EAE3C,sBAF2C,CAAtC;AAgCP,OAAO,MAAMC,eAAe,GAAG,CAC7B,GAAGF,uBAD0B,EAE7B,GAAGC,6BAF0B,CAAxB;AAMP;AACA,OAAO,MAAME,wBAAwB,GAAGJ,aAAa,CAGnD;AACAK,EAAAA,IAAI,EAAE,0BADN;AAEAC,EAAAA,YAAY,EAAEH,eAFd;AAGAI,EAAAA,MAAM,EAAE;AAHR,CAHmD,CAA9C","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport const nativeViewGestureHandlerProps = [\n 'shouldActivateOnStart',\n 'disallowInterruption',\n] as const;\n\nexport interface NativeViewGestureConfig {\n /**\n * Android only.\n *\n * Determines whether the handler should check for an existing touch event on\n * instantiation.\n */\n shouldActivateOnStart?: boolean;\n\n /**\n * When `true`, cancels all other gesture handlers when this\n * `NativeViewGestureHandler` receives an `ACTIVE` state event.\n */\n disallowInterruption?: boolean;\n}\n\nexport interface NativeViewGestureHandlerProps\n extends BaseGestureHandlerProps,\n NativeViewGestureConfig {}\n\nexport type NativeViewGestureHandlerPayload = {\n /**\n * True if gesture was performed inside of containing view, false otherwise.\n */\n pointerInside: boolean;\n};\n\nexport const nativeViewProps = [\n ...baseGestureHandlerProps,\n ...nativeViewGestureHandlerProps,\n] as const;\n\nexport type NativeViewGestureHandler = typeof NativeViewGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const NativeViewGestureHandler = createHandler<\n NativeViewGestureHandlerProps,\n NativeViewGestureHandlerPayload\n>({\n name: 'NativeViewGestureHandler',\n allowedProps: nativeViewProps,\n config: {},\n});\n"]} \ No newline at end of file diff --git a/lib/module/handlers/PanGestureHandler.js b/lib/module/handlers/PanGestureHandler.js new file mode 100644 index 0000000000..cb77e9e389 --- /dev/null +++ b/lib/module/handlers/PanGestureHandler.js @@ -0,0 +1,106 @@ +import createHandler from './createHandler'; +import { baseGestureHandlerProps } from './gestureHandlerCommon'; +export const panGestureHandlerProps = ['activeOffsetY', 'activeOffsetX', 'failOffsetY', 'failOffsetX', 'minDist', 'minVelocity', 'minVelocityX', 'minVelocityY', 'minPointers', 'maxPointers', 'avgTouches', 'enableTrackpadTwoFingerGesture']; +export const panGestureHandlerCustomNativeProps = ['activeOffsetYStart', 'activeOffsetYEnd', 'activeOffsetXStart', 'activeOffsetXEnd', 'failOffsetYStart', 'failOffsetYEnd', 'failOffsetXStart', 'failOffsetXEnd']; +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +export const PanGestureHandler = createHandler({ + name: 'PanGestureHandler', + allowedProps: [...baseGestureHandlerProps, ...panGestureHandlerProps], + config: {}, + transformProps: managePanProps, + customNativeProps: panGestureHandlerCustomNativeProps +}); + +function validatePanGestureHandlerProps(props) { + if (Array.isArray(props.activeOffsetX) && (props.activeOffsetX[0] > 0 || props.activeOffsetX[1] < 0)) { + throw new Error(`First element of activeOffsetX should be negative, a the second one should be positive`); + } + + if (Array.isArray(props.activeOffsetY) && (props.activeOffsetY[0] > 0 || props.activeOffsetY[1] < 0)) { + throw new Error(`First element of activeOffsetY should be negative, a the second one should be positive`); + } + + if (Array.isArray(props.failOffsetX) && (props.failOffsetX[0] > 0 || props.failOffsetX[1] < 0)) { + throw new Error(`First element of failOffsetX should be negative, a the second one should be positive`); + } + + if (Array.isArray(props.failOffsetY) && (props.failOffsetY[0] > 0 || props.failOffsetY[1] < 0)) { + throw new Error(`First element of failOffsetY should be negative, a the second one should be positive`); + } + + if (props.minDist && (props.failOffsetX || props.failOffsetY)) { + throw new Error(`It is not supported to use minDist with failOffsetX or failOffsetY, use activeOffsetX and activeOffsetY instead`); + } + + if (props.minDist && (props.activeOffsetX || props.activeOffsetY)) { + throw new Error(`It is not supported to use minDist with activeOffsetX or activeOffsetY`); + } +} + +function transformPanGestureHandlerProps(props) { + const res = { ...props + }; + + if (props.activeOffsetX !== undefined) { + delete res.activeOffsetX; + + if (Array.isArray(props.activeOffsetX)) { + res.activeOffsetXStart = props.activeOffsetX[0]; + res.activeOffsetXEnd = props.activeOffsetX[1]; + } else if (props.activeOffsetX < 0) { + res.activeOffsetXStart = props.activeOffsetX; + } else { + res.activeOffsetXEnd = props.activeOffsetX; + } + } + + if (props.activeOffsetY !== undefined) { + delete res.activeOffsetY; + + if (Array.isArray(props.activeOffsetY)) { + res.activeOffsetYStart = props.activeOffsetY[0]; + res.activeOffsetYEnd = props.activeOffsetY[1]; + } else if (props.activeOffsetY < 0) { + res.activeOffsetYStart = props.activeOffsetY; + } else { + res.activeOffsetYEnd = props.activeOffsetY; + } + } + + if (props.failOffsetX !== undefined) { + delete res.failOffsetX; + + if (Array.isArray(props.failOffsetX)) { + res.failOffsetXStart = props.failOffsetX[0]; + res.failOffsetXEnd = props.failOffsetX[1]; + } else if (props.failOffsetX < 0) { + res.failOffsetXStart = props.failOffsetX; + } else { + res.failOffsetXEnd = props.failOffsetX; + } + } + + if (props.failOffsetY !== undefined) { + delete res.failOffsetY; + + if (Array.isArray(props.failOffsetY)) { + res.failOffsetYStart = props.failOffsetY[0]; + res.failOffsetYEnd = props.failOffsetY[1]; + } else if (props.failOffsetY < 0) { + res.failOffsetYStart = props.failOffsetY; + } else { + res.failOffsetYEnd = props.failOffsetY; + } + } + + return res; +} + +export function managePanProps(props) { + if (__DEV__) { + validatePanGestureHandlerProps(props); + } + + return transformPanGestureHandlerProps(props); +} +//# sourceMappingURL=PanGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/handlers/PanGestureHandler.js.map b/lib/module/handlers/PanGestureHandler.js.map new file mode 100644 index 0000000000..cdca8c75bc --- /dev/null +++ b/lib/module/handlers/PanGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PanGestureHandler.ts"],"names":["createHandler","baseGestureHandlerProps","panGestureHandlerProps","panGestureHandlerCustomNativeProps","PanGestureHandler","name","allowedProps","config","transformProps","managePanProps","customNativeProps","validatePanGestureHandlerProps","props","Array","isArray","activeOffsetX","Error","activeOffsetY","failOffsetX","failOffsetY","minDist","transformPanGestureHandlerProps","res","undefined","activeOffsetXStart","activeOffsetXEnd","activeOffsetYStart","activeOffsetYEnd","failOffsetXStart","failOffsetXEnd","failOffsetYStart","failOffsetYEnd","__DEV__"],"mappings":"AAAA,OAAOA,aAAP,MAA0B,iBAA1B;AACA,SAEEC,uBAFF,QAGO,wBAHP;AAKA,OAAO,MAAMC,sBAAsB,GAAG,CACpC,eADoC,EAEpC,eAFoC,EAGpC,aAHoC,EAIpC,aAJoC,EAKpC,SALoC,EAMpC,aANoC,EAOpC,cAPoC,EAQpC,cARoC,EASpC,aAToC,EAUpC,aAVoC,EAWpC,YAXoC,EAYpC,gCAZoC,CAA/B;AAeP,OAAO,MAAMC,kCAAkC,GAAG,CAChD,oBADgD,EAEhD,kBAFgD,EAGhD,oBAHgD,EAIhD,kBAJgD,EAKhD,kBALgD,EAMhD,gBANgD,EAOhD,kBAPgD,EAQhD,gBARgD,CAA3C;AAmKP;AACA,OAAO,MAAMC,iBAAiB,GAAGJ,aAAa,CAG5C;AACAK,EAAAA,IAAI,EAAE,mBADN;AAEAC,EAAAA,YAAY,EAAE,CACZ,GAAGL,uBADS,EAEZ,GAAGC,sBAFS,CAFd;AAMAK,EAAAA,MAAM,EAAE,EANR;AAOAC,EAAAA,cAAc,EAAEC,cAPhB;AAQAC,EAAAA,iBAAiB,EAAEP;AARnB,CAH4C,CAAvC;;AAcP,SAASQ,8BAAT,CAAwCC,KAAxC,EAAuE;AACrE,MACEC,KAAK,CAACC,OAAN,CAAcF,KAAK,CAACG,aAApB,MACCH,KAAK,CAACG,aAAN,CAAoB,CAApB,IAAyB,CAAzB,IAA8BH,KAAK,CAACG,aAAN,CAAoB,CAApB,IAAyB,CADxD,CADF,EAGE;AACA,UAAM,IAAIC,KAAJ,CACH,wFADG,CAAN;AAGD;;AAED,MACEH,KAAK,CAACC,OAAN,CAAcF,KAAK,CAACK,aAApB,MACCL,KAAK,CAACK,aAAN,CAAoB,CAApB,IAAyB,CAAzB,IAA8BL,KAAK,CAACK,aAAN,CAAoB,CAApB,I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AA,GAAG,CAACO,cAAJ,GAAqBjB,KAAK,CAACM,WAA3B;AACD;AACF;;AAED,MAAIN,KAAK,CAACO,WAAN,KAAsBI,SAA1B,EAAqC;AACnC,WAAOD,GAAG,CAACH,WAAX;;AACA,QAAIN,KAAK,CAACC,OAAN,CAAcF,KAAK,CAACO,WAApB,CAAJ,EAAsC;AACpCG,MAAAA,GAAG,CAACQ,gBAAJ,GAAuBlB,KAAK,CAACO,WAAN,CAAkB,CAAlB,CAAvB;AACAG,MAAAA,GAAG,CAACS,cAAJ,GAAqBnB,KAAK,CAACO,WAAN,CAAkB,CAAlB,CAArB;AACD,KAHD,MAGO,IAAIP,KAAK,CAACO,WAAN,GAAoB,CAAxB,EAA2B;AAChCG,MAAAA,GAAG,CAACQ,gBAAJ,GAAuBlB,KAAK,CAACO,WAA7B;AACD,KAFM,MAEA;AACLG,MAAAA,GAAG,CAACS,cAAJ,GAAqBnB,KAAK,CAACO,WAA3B;AACD;AACF;;AAED,SAAOG,GAAP;AACD;;AAED,OAAO,SAASb,cAAT,CAAwBG,KAAxB,EAAuD;AAC5D,MAAIoB,OAAJ,EAAa;AACXrB,IAAAA,8BAA8B,CAACC,KAAD,CAA9B;AACD;;AACD,SAAOS,+BAA+B,CAACT,KAAD,CAAtC;AACD","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport const panGestureHandlerProps = [\n 'activeOffsetY',\n 'activeOffsetX',\n 'failOffsetY',\n 'failOffsetX',\n 'minDist',\n 'minVelocity',\n 'minVelocityX',\n 'minVelocityY',\n 'minPointers',\n 'maxPointers',\n 'avgTouches',\n 'enableTrackpadTwoFingerGesture',\n] as const;\n\nexport const panGestureHandlerCustomNativeProps = [\n 'activeOffsetYStart',\n 'activeOffsetYEnd',\n 'activeOffsetXStart',\n 'activeOffsetXEnd',\n 'failOffsetYStart',\n 'failOffsetYEnd',\n 'failOffsetXStart',\n 'failOffsetXEnd',\n] as const;\n\nexport type PanGestureHandlerEventPayload = {\n /**\n * X coordinate of the current position of the pointer (finger or a leading\n * pointer when there are multiple fingers placed) relative to the view\n * attached to the handler. Expressed in point units.\n */\n x: number;\n\n /**\n * Y coordinate of the current position of the pointer (finger or a leading\n * pointer when there are multiple fingers placed) relative to the view\n * attached to the handler. Expressed in point units.\n */\n y: number;\n\n /**\n * X coordinate of the current position of the pointer (finger or a leading\n * pointer when there are multiple fingers placed) relative to the window.\n * The value is expressed in point units. It is recommended to use it instead\n * of `x` in cases when the original view can be transformed as an effect of\n * the gesture.\n */\n absoluteX: number;\n\n /**\n * Y coordinate of the current position of the pointer (finger or a leading\n * pointer when there are multiple fingers placed) relative to the window.\n * The value is expressed in point units. It is recommended to use it instead\n * of `y` in cases when the original view can be transformed as an\n * effect of the gesture.\n */\n absoluteY: number;\n\n /**\n * Translation of the pan gesture along X axis accumulated over the time of\n * the gesture. The value is expressed in the point units.\n */\n translationX: number;\n\n /**\n * Translation of the pan gesture along Y axis accumulated over the time of\n * the gesture. The value is expressed in the point units.\n */\n translationY: number;\n\n /**\n * Velocity of the pan gesture along the X axis in the current moment. The\n * value is expressed in point units per second.\n */\n velocityX: number;\n\n /**\n * Velocity of the pan gesture along the Y axis in the current moment. The\n * value is expressed in point units per second.\n */\n velocityY: number;\n};\n\ninterface CommonPanProperties {\n /**\n * Minimum distance the finger (or multiple finger) need to travel before the\n * handler activates. Expressed in points.\n */\n minDist?: number;\n\n /**\n * Android only.\n */\n avgTouches?: boolean;\n\n /**\n * Enables two-finger gestures on supported devices, for example iPads with\n * trackpads. If not enabled the gesture will require click + drag, with\n * enableTrackpadTwoFingerGesture swiping with two fingers will also trigger\n * the gesture.\n */\n enableTrackpadTwoFingerGesture?: boolean;\n\n /**\n * A number of fingers that is required to be placed before handler can\n * activate. Should be a higher or equal to 0 integer.\n */\n minPointers?: number;\n\n /**\n * When the given number of fingers is placed on the screen and handler hasn't\n * yet activated it will fail recognizing the gesture. Should be a higher or\n * equal to 0 integer.\n */\n maxPointers?: number;\n\n minVelocity?: number;\n minVelocityX?: number;\n minVelocityY?: number;\n}\n\nexport interface PanGestureConfig extends CommonPanProperties {\n activeOffsetYStart?: number;\n activeOffsetYEnd?: number;\n activeOffsetXStart?: number;\n activeOffsetXEnd?: number;\n failOffsetYStart?: number;\n failOffsetYEnd?: number;\n failOffsetXStart?: number;\n failOffsetXEnd?: number;\n}\n\nexport interface PanGestureHandlerProps\n extends BaseGestureHandlerProps,\n CommonPanProperties {\n /**\n * Range along X axis (in points) where fingers travels without activation of\n * handler. Moving outside of this range implies activation of handler. Range\n * can be given as an array or a single number. If range is set as an array,\n * first value must be lower or equal to 0, a the second one higher or equal\n * to 0. If only one number `p` is given a range of `(-inf, p)` will be used\n * if `p` is higher or equal to 0 and `(-p, inf)` otherwise.\n */\n activeOffsetY?: number | number[];\n\n /**\n * Range along X axis (in points) where fingers travels without activation of\n * handler. Moving outside of this range implies activation of handler. Range\n * can be given as an array or a single number. If range is set as an array,\n * first value must be lower or equal to 0, a the second one higher or equal\n * to 0. If only one number `p` is given a range of `(-inf, p)` will be used\n * if `p` is higher or equal to 0 and `(-p, inf)` otherwise.\n */\n activeOffsetX?: number | number[];\n\n /**\n * When the finger moves outside this range (in points) along Y axis and\n * handler hasn't yet activated it will fail recognizing the gesture. Range\n * can be given as an array or a single number. If range is set as an array,\n * first value must be lower or equal to 0, a the second one higher or equal\n * to 0. If only one number `p` is given a range of `(-inf, p)` will be used\n * if `p` is higher or equal to 0 and `(-p, inf)` otherwise.\n */\n failOffsetY?: number | number[];\n\n /**\n * When the finger moves outside this range (in points) along X axis and\n * handler hasn't yet activated it will fail recognizing the gesture. Range\n * can be given as an array or a single number. If range is set as an array,\n * first value must be lower or equal to 0, a the second one higher or equal\n * to 0. If only one number `p` is given a range of `(-inf, p)` will be used\n * if `p` is higher or equal to 0 and `(-p, inf)` otherwise.\n */\n failOffsetX?: number | number[];\n}\n\nexport type PanGestureHandler = typeof PanGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const PanGestureHandler = createHandler<\n PanGestureHandlerProps,\n PanGestureHandlerEventPayload\n>({\n name: 'PanGestureHandler',\n allowedProps: [\n ...baseGestureHandlerProps,\n ...panGestureHandlerProps,\n ] as const,\n config: {},\n transformProps: managePanProps,\n customNativeProps: panGestureHandlerCustomNativeProps,\n});\n\nfunction validatePanGestureHandlerProps(props: PanGestureHandlerProps) {\n if (\n Array.isArray(props.activeOffsetX) &&\n (props.activeOffsetX[0] > 0 || props.activeOffsetX[1] < 0)\n ) {\n throw new Error(\n `First element of activeOffsetX should be negative, a the second one should be positive`\n );\n }\n\n if (\n Array.isArray(props.activeOffsetY) &&\n (props.activeOffsetY[0] > 0 || props.activeOffsetY[1] < 0)\n ) {\n throw new Error(\n `First element of activeOffsetY should be negative, a the second one should be positive`\n );\n }\n\n if (\n Array.isArray(props.failOffsetX) &&\n (props.failOffsetX[0] > 0 || props.failOffsetX[1] < 0)\n ) {\n throw new Error(\n `First element of failOffsetX should be negative, a the second one should be positive`\n );\n }\n\n if (\n Array.isArray(props.failOffsetY) &&\n (props.failOffsetY[0] > 0 || props.failOffsetY[1] < 0)\n ) {\n throw new Error(\n `First element of failOffsetY should be negative, a the second one should be positive`\n );\n }\n\n if (props.minDist && (props.failOffsetX || props.failOffsetY)) {\n throw new Error(\n `It is not supported to use minDist with failOffsetX or failOffsetY, use activeOffsetX and activeOffsetY instead`\n );\n }\n\n if (props.minDist && (props.activeOffsetX || props.activeOffsetY)) {\n throw new Error(\n `It is not supported to use minDist with activeOffsetX or activeOffsetY`\n );\n }\n}\n\nfunction transformPanGestureHandlerProps(props: PanGestureHandlerProps) {\n type InternalPanGHKeys =\n | 'activeOffsetXStart'\n | 'activeOffsetXEnd'\n | 'failOffsetXStart'\n | 'failOffsetXEnd'\n | 'activeOffsetYStart'\n | 'activeOffsetYEnd'\n | 'failOffsetYStart'\n | 'failOffsetYEnd';\n type PanGestureHandlerInternalProps = PanGestureHandlerProps &\n Partial>;\n\n const res: PanGestureHandlerInternalProps = { ...props };\n\n if (props.activeOffsetX !== undefined) {\n delete res.activeOffsetX;\n if (Array.isArray(props.activeOffsetX)) {\n res.activeOffsetXStart = props.activeOffsetX[0];\n res.activeOffsetXEnd = props.activeOffsetX[1];\n } else if (props.activeOffsetX < 0) {\n res.activeOffsetXStart = props.activeOffsetX;\n } else {\n res.activeOffsetXEnd = props.activeOffsetX;\n }\n }\n\n if (props.activeOffsetY !== undefined) {\n delete res.activeOffsetY;\n if (Array.isArray(props.activeOffsetY)) {\n res.activeOffsetYStart = props.activeOffsetY[0];\n res.activeOffsetYEnd = props.activeOffsetY[1];\n } else if (props.activeOffsetY < 0) {\n res.activeOffsetYStart = props.activeOffsetY;\n } else {\n res.activeOffsetYEnd = props.activeOffsetY;\n }\n }\n\n if (props.failOffsetX !== undefined) {\n delete res.failOffsetX;\n if (Array.isArray(props.failOffsetX)) {\n res.failOffsetXStart = props.failOffsetX[0];\n res.failOffsetXEnd = props.failOffsetX[1];\n } else if (props.failOffsetX < 0) {\n res.failOffsetXStart = props.failOffsetX;\n } else {\n res.failOffsetXEnd = props.failOffsetX;\n }\n }\n\n if (props.failOffsetY !== undefined) {\n delete res.failOffsetY;\n if (Array.isArray(props.failOffsetY)) {\n res.failOffsetYStart = props.failOffsetY[0];\n res.failOffsetYEnd = props.failOffsetY[1];\n } else if (props.failOffsetY < 0) {\n res.failOffsetYStart = props.failOffsetY;\n } else {\n res.failOffsetYEnd = props.failOffsetY;\n }\n }\n\n return res;\n}\n\nexport function managePanProps(props: PanGestureHandlerProps) {\n if (__DEV__) {\n validatePanGestureHandlerProps(props);\n }\n return transformPanGestureHandlerProps(props);\n}\n"]} \ No newline at end of file diff --git a/lib/module/handlers/PinchGestureHandler.js b/lib/module/handlers/PinchGestureHandler.js new file mode 100644 index 0000000000..848d6543c1 --- /dev/null +++ b/lib/module/handlers/PinchGestureHandler.js @@ -0,0 +1,9 @@ +import createHandler from './createHandler'; +import { baseGestureHandlerProps } from './gestureHandlerCommon'; +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +export const PinchGestureHandler = createHandler({ + name: 'PinchGestureHandler', + allowedProps: baseGestureHandlerProps, + config: {} +}); +//# sourceMappingURL=PinchGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/handlers/PinchGestureHandler.js.map b/lib/module/handlers/PinchGestureHandler.js.map new file mode 100644 index 0000000000..f4cbfd4d0c --- /dev/null +++ b/lib/module/handlers/PinchGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PinchGestureHandler.ts"],"names":["createHandler","baseGestureHandlerProps","PinchGestureHandler","name","allowedProps","config"],"mappings":"AAAA,OAAOA,aAAP,MAA0B,iBAA1B;AACA,SAEEC,uBAFF,QAGO,wBAHP;AAoCA;AACA,OAAO,MAAMC,mBAAmB,GAAGF,aAAa,CAG9C;AACAG,EAAAA,IAAI,EAAE,qBADN;AAEAC,EAAAA,YAAY,EAAEH,uBAFd;AAGAI,EAAAA,MAAM,EAAE;AAHR,CAH8C,CAAzC","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport type PinchGestureHandlerEventPayload = {\n /**\n * The scale factor relative to the points of the two touches in screen\n * coordinates.\n */\n scale: number;\n\n /**\n * Position expressed in points along X axis of center anchor point of\n * gesture.\n */\n focalX: number;\n\n /**\n * Position expressed in points along Y axis of center anchor point of\n * gesture.\n */\n focalY: number;\n\n /**\n *\n * Velocity of the pan gesture the current moment. The value is expressed in\n * point units per second.\n */\n velocity: number;\n};\n\nexport interface PinchGestureHandlerProps\n extends BaseGestureHandlerProps {}\n\nexport type PinchGestureHandler = typeof PinchGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const PinchGestureHandler = createHandler<\n PinchGestureHandlerProps,\n PinchGestureHandlerEventPayload\n>({\n name: 'PinchGestureHandler',\n allowedProps: baseGestureHandlerProps,\n config: {},\n});\n"]} \ No newline at end of file diff --git a/lib/module/handlers/RotationGestureHandler.js b/lib/module/handlers/RotationGestureHandler.js new file mode 100644 index 0000000000..94337c5d70 --- /dev/null +++ b/lib/module/handlers/RotationGestureHandler.js @@ -0,0 +1,9 @@ +import createHandler from './createHandler'; +import { baseGestureHandlerProps } from './gestureHandlerCommon'; +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +export const RotationGestureHandler = createHandler({ + name: 'RotationGestureHandler', + allowedProps: baseGestureHandlerProps, + config: {} +}); +//# sourceMappingURL=RotationGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/handlers/RotationGestureHandler.js.map b/lib/module/handlers/RotationGestureHandler.js.map new file mode 100644 index 0000000000..137ed65308 --- /dev/null +++ b/lib/module/handlers/RotationGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["RotationGestureHandler.ts"],"names":["createHandler","baseGestureHandlerProps","RotationGestureHandler","name","allowedProps","config"],"mappings":"AAAA,OAAOA,aAAP,MAA0B,iBAA1B;AACA,SAEEC,uBAFF,QAGO,wBAHP;AAoCA;AACA,OAAO,MAAMC,sBAAsB,GAAGF,aAAa,CAGjD;AACAG,EAAAA,IAAI,EAAE,wBADN;AAEAC,EAAAA,YAAY,EAAEH,uBAFd;AAGAI,EAAAA,MAAM,EAAE;AAHR,CAHiD,CAA5C","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport type RotationGestureHandlerEventPayload = {\n /**\n * Amount rotated, expressed in radians, from the gesture's focal point\n * (anchor).\n */\n rotation: number;\n\n /**\n * X coordinate, expressed in points, of the gesture's central focal point\n * (anchor).\n */\n anchorX: number;\n\n /**\n * Y coordinate, expressed in points, of the gesture's central focal point\n * (anchor).\n */\n anchorY: number;\n\n /**\n *\n * Instantaneous velocity, expressed in point units per second, of the\n * gesture.\n */\n velocity: number;\n};\n\nexport interface RotationGestureHandlerProps\n extends BaseGestureHandlerProps {}\n\nexport type RotationGestureHandler = typeof RotationGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const RotationGestureHandler = createHandler<\n RotationGestureHandlerProps,\n RotationGestureHandlerEventPayload\n>({\n name: 'RotationGestureHandler',\n allowedProps: baseGestureHandlerProps,\n config: {},\n});\n"]} \ No newline at end of file diff --git a/lib/module/handlers/TapGestureHandler.js b/lib/module/handlers/TapGestureHandler.js new file mode 100644 index 0000000000..f40b969d33 --- /dev/null +++ b/lib/module/handlers/TapGestureHandler.js @@ -0,0 +1,10 @@ +import createHandler from './createHandler'; +import { baseGestureHandlerProps } from './gestureHandlerCommon'; +export const tapGestureHandlerProps = ['maxDurationMs', 'maxDelayMs', 'numberOfTaps', 'maxDeltaX', 'maxDeltaY', 'maxDist', 'minPointers']; +// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file +export const TapGestureHandler = createHandler({ + name: 'TapGestureHandler', + allowedProps: [...baseGestureHandlerProps, ...tapGestureHandlerProps], + config: {} +}); +//# sourceMappingURL=TapGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/handlers/TapGestureHandler.js.map b/lib/module/handlers/TapGestureHandler.js.map new file mode 100644 index 0000000000..5fa796e22b --- /dev/null +++ b/lib/module/handlers/TapGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TapGestureHandler.ts"],"names":["createHandler","baseGestureHandlerProps","tapGestureHandlerProps","TapGestureHandler","name","allowedProps","config"],"mappings":"AAAA,OAAOA,aAAP,MAA0B,iBAA1B;AACA,SAEEC,uBAFF,QAGO,wBAHP;AAKA,OAAO,MAAMC,sBAAsB,GAAG,CACpC,eADoC,EAEpC,YAFoC,EAGpC,cAHoC,EAIpC,WAJoC,EAKpC,WALoC,EAMpC,SANoC,EAOpC,aAPoC,CAA/B;AAwEP;AACA,OAAO,MAAMC,iBAAiB,GAAGH,aAAa,CAG5C;AACAI,EAAAA,IAAI,EAAE,mBADN;AAEAC,EAAAA,YAAY,EAAE,CACZ,GAAGJ,uBADS,EAEZ,GAAGC,sBAFS,CAFd;AAMAI,EAAAA,MAAM,EAAE;AANR,CAH4C,CAAvC","sourcesContent":["import createHandler from './createHandler';\nimport {\n BaseGestureHandlerProps,\n baseGestureHandlerProps,\n} from './gestureHandlerCommon';\n\nexport const tapGestureHandlerProps = [\n 'maxDurationMs',\n 'maxDelayMs',\n 'numberOfTaps',\n 'maxDeltaX',\n 'maxDeltaY',\n 'maxDist',\n 'minPointers',\n] as const;\n\nexport type TapGestureHandlerEventPayload = {\n x: number;\n y: number;\n absoluteX: number;\n absoluteY: number;\n};\nexport interface TapGestureConfig {\n /**\n * Minimum number of pointers (fingers) required to be placed before the\n * handler activates. Should be a positive integer.\n * The default value is 1.\n */\n minPointers?: number;\n\n /**\n * Maximum time, expressed in milliseconds, that defines how fast a finger\n * must be released after a touch. The default value is 500.\n */\n maxDurationMs?: number;\n\n /**\n * Maximum time, expressed in milliseconds, that can pass before the next tap\n * if many taps are required. The default value is 500.\n */\n maxDelayMs?: number;\n\n /**\n * Number of tap gestures required to activate the handler. The default value\n * is 1.\n */\n numberOfTaps?: number;\n\n /**\n * Maximum distance, expressed in points, that defines how far the finger is\n * allowed to travel along the X axis during a tap gesture. If the finger\n * travels further than the defined distance along the X axis and the handler\n * hasn't yet activated, it will fail to recognize the gesture.\n */\n maxDeltaX?: number;\n\n /**\n * Maximum distance, expressed in points, that defines how far the finger is\n * allowed to travel along the Y axis during a tap gesture. If the finger\n * travels further than the defined distance along the Y axis and the handler\n * hasn't yet activated, it will fail to recognize the gesture.\n */\n maxDeltaY?: number;\n\n /**\n * Maximum distance, expressed in points, that defines how far the finger is\n * allowed to travel during a tap gesture. If the finger travels further than\n * the defined distance and the handler hasn't yet\n * activated, it will fail to recognize the gesture.\n */\n maxDist?: number;\n}\n\nexport interface TapGestureHandlerProps\n extends BaseGestureHandlerProps,\n TapGestureConfig {}\n\nexport type TapGestureHandler = typeof TapGestureHandler;\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- backward compatibility; see description on the top of gestureHandlerCommon.ts file\nexport const TapGestureHandler = createHandler<\n TapGestureHandlerProps,\n TapGestureHandlerEventPayload\n>({\n name: 'TapGestureHandler',\n allowedProps: [\n ...baseGestureHandlerProps,\n ...tapGestureHandlerProps,\n ] as const,\n config: {},\n});\n"]} \ No newline at end of file diff --git a/lib/module/handlers/createHandler.js b/lib/module/handlers/createHandler.js new file mode 100644 index 0000000000..51d489d353 --- /dev/null +++ b/lib/module/handlers/createHandler.js @@ -0,0 +1,361 @@ +var _UIManagerAny$getView, _UIManagerAny$getView2, _UIManagerAny$getCons; + +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; } + +import * as React from 'react'; +import { Platform, Touchable, UIManager, DeviceEventEmitter } from 'react-native'; // @ts-ignore - it isn't typed by TS & don't have definitelyTyped types + +import deepEqual from 'lodash/isEqual'; +import RNGestureHandlerModule from '../RNGestureHandlerModule'; +import { State } from '../State'; +import { handlerIDToTag, getNextHandlerTag } from './handlersRegistry'; +import { filterConfig, findNodeHandle } from './gestureHandlerCommon'; +const UIManagerAny = UIManager; +const customGHEventsConfig = { + onGestureHandlerEvent: { + registrationName: 'onGestureHandlerEvent' + }, + onGestureHandlerStateChange: { + registrationName: 'onGestureHandlerStateChange' + } +}; // Add gesture specific events to genericDirectEventTypes object exported from UIManager +// native module. +// Once new event types are registered with react it is possible to dispatch these +// events to all kind of native views. + +UIManagerAny.genericDirectEventTypes = { ...UIManagerAny.genericDirectEventTypes, + ...customGHEventsConfig +}; // In newer versions of RN the `genericDirectEventTypes` is located in the object +// returned by UIManager.getViewManagerConfig('getConstants') or in older RN UIManager.getConstants(), we need to add it there as well to make +// it compatible with RN 61+ + +const UIManagerConstants = (_UIManagerAny$getView = (_UIManagerAny$getView2 = UIManagerAny.getViewManagerConfig) === null || _UIManagerAny$getView2 === void 0 ? void 0 : _UIManagerAny$getView2.call(UIManagerAny, 'getConstants')) !== null && _UIManagerAny$getView !== void 0 ? _UIManagerAny$getView : (_UIManagerAny$getCons = UIManagerAny.getConstants) === null || _UIManagerAny$getCons === void 0 ? void 0 : _UIManagerAny$getCons.call(UIManagerAny); + +if (UIManagerConstants) { + UIManagerConstants.genericDirectEventTypes = { ...UIManagerConstants.genericDirectEventTypes, + ...customGHEventsConfig + }; +} // Wrap JS responder calls and notify gesture handler manager + + +const { + setJSResponder: oldSetJSResponder = () => {//no operation + }, + clearJSResponder: oldClearJSResponder = () => {//no operation + } +} = UIManagerAny; + +UIManagerAny.setJSResponder = (tag, blockNativeResponder) => { + RNGestureHandlerModule.handleSetJSResponder(tag, blockNativeResponder); + oldSetJSResponder(tag, blockNativeResponder); +}; + +UIManagerAny.clearJSResponder = () => { + RNGestureHandlerModule.handleClearJSResponder(); + oldClearJSResponder(); +}; + +let allowTouches = true; +const DEV_ON_ANDROID = __DEV__ && Platform.OS === 'android'; // Toggled inspector blocks touch events in order to allow inspecting on Android +// This needs to be a global variable in order to set initial state for `allowTouches` property in Handler component + +if (DEV_ON_ANDROID) { + DeviceEventEmitter.addListener('toggleElementInspector', () => { + allowTouches = !allowTouches; + }); +} + +function hasUnresolvedRefs(props) { + // TODO(TS) - add type for extract arg + const extract = refs => { + if (!Array.isArray(refs)) { + return refs && refs.current === null; + } + + return refs.some(r => r && r.current === null); + }; + + return extract(props['simultaneousHandlers']) || extract(props['waitFor']); +} + +const stateToPropMappings = { + [State.UNDETERMINED]: undefined, + [State.BEGAN]: 'onBegan', + [State.FAILED]: 'onFailed', + [State.CANCELLED]: 'onCancelled', + [State.ACTIVE]: 'onActivated', + [State.END]: 'onEnded' +}; +let showedRngh2Notice = false; + +function showRngh2NoticeIfNeeded() { + if (!showedRngh2Notice) { + console.warn("[react-native-gesture-handler] Seems like you're using an old API with gesture components, check out new Gestures system!"); + showedRngh2Notice = true; + } +} // TODO(TS) - make sure that BaseGestureHandlerProps doesn't need other generic parameter to work with custom properties. + + +export default function createHandler({ + name, + allowedProps = [], + config = {}, + transformProps, + customNativeProps = [] +}) { + class Handler extends React.Component { + constructor(props) { + super(props); + + _defineProperty(this, "handlerTag", void 0); + + _defineProperty(this, "config", void 0); + + _defineProperty(this, "propsRef", void 0); + + _defineProperty(this, "viewNode", void 0); + + _defineProperty(this, "viewTag", void 0); + + _defineProperty(this, "updateEnqueued", null); + + _defineProperty(this, "inspectorToggleListener", void 0); + + _defineProperty(this, "onGestureHandlerEvent", event => { + if (event.nativeEvent.handlerTag === this.handlerTag) { + var _this$props$onGesture, _this$props; + + (_this$props$onGesture = (_this$props = this.props).onGestureEvent) === null || _this$props$onGesture === void 0 ? void 0 : _this$props$onGesture.call(_this$props, event); + } else { + var _this$props$onGesture2, _this$props2; + + (_this$props$onGesture2 = (_this$props2 = this.props).onGestureHandlerEvent) === null || _this$props$onGesture2 === void 0 ? void 0 : _this$props$onGesture2.call(_this$props2, event); + } + }); + + _defineProperty(this, "onGestureHandlerStateChange", event => { + if (event.nativeEvent.handlerTag === this.handlerTag) { + var _this$props$onHandler, _this$props3; + + (_this$props$onHandler = (_this$props3 = this.props).onHandlerStateChange) === null || _this$props$onHandler === void 0 ? void 0 : _this$props$onHandler.call(_this$props3, event); + const state = event.nativeEvent.state; + const stateEventName = stateToPropMappings[state]; + const eventHandler = stateEventName && this.props[stateEventName]; + + if (eventHandler && typeof eventHandler === 'function') { + eventHandler(event); + } + } else { + var _this$props$onGesture3, _this$props4; + + (_this$props$onGesture3 = (_this$props4 = this.props).onGestureHandlerStateChange) === null || _this$props$onGesture3 === void 0 ? void 0 : _this$props$onGesture3.call(_this$props4, event); + } + }); + + _defineProperty(this, "refHandler", node => { + this.viewNode = node; + const child = React.Children.only(this.props.children); // TODO(TS) fix ref type + + const { + ref + } = child; + + if (ref !== null) { + if (typeof ref === 'function') { + ref(node); + } else { + ref.current = node; + } + } + }); + + _defineProperty(this, "createGestureHandler", newConfig => { + this.config = newConfig; + RNGestureHandlerModule.createGestureHandler(name, this.handlerTag, newConfig); + }); + + _defineProperty(this, "attachGestureHandler", newViewTag => { + this.viewTag = newViewTag; + + if (Platform.OS === 'web') { + // typecast due to dynamic resolution, attachGestureHandler should have web version signature in this branch + RNGestureHandlerModule.attachGestureHandler(this.handlerTag, newViewTag, false, this.propsRef); + } else { + RNGestureHandlerModule.attachGestureHandler(this.handlerTag, newViewTag, false); + } + }); + + _defineProperty(this, "updateGestureHandler", newConfig => { + this.config = newConfig; + RNGestureHandlerModule.updateGestureHandler(this.handlerTag, newConfig); + }); + + this.handlerTag = getNextHandlerTag(); + this.config = {}; + this.propsRef = /*#__PURE__*/React.createRef(); + this.state = { + allowTouches + }; + + if (props.id) { + if (handlerIDToTag[props.id] !== undefined) { + throw new Error(`Handler with ID "${props.id}" already registered`); + } + + handlerIDToTag[props.id] = this.handlerTag; + } + + if (__DEV__) { + showRngh2NoticeIfNeeded(); + } + } + + componentDidMount() { + const props = this.props; + + if (DEV_ON_ANDROID) { + this.inspectorToggleListener = DeviceEventEmitter.addListener('toggleElementInspector', () => { + this.setState(_ => ({ + allowTouches + })); + this.update(); + }); + } + + if (hasUnresolvedRefs(props)) { + // If there are unresolved refs (e.g. ".current" has not yet been set) + // passed as `simultaneousHandlers` or `waitFor`, we enqueue a call to + // _update method that will try to update native handler props using + // setImmediate. This makes it so update() function gets called after all + // react components are mounted and we expect the missing ref object to + // be resolved by then. + this.updateEnqueued = setImmediate(() => { + this.updateEnqueued = null; + this.update(); + }); + } + + this.createGestureHandler(filterConfig(transformProps ? transformProps(this.props) : this.props, [...allowedProps, ...customNativeProps], config)); + this.attachGestureHandler(findNodeHandle(this.viewNode)); // TODO(TS) - check if this can be null + } + + componentDidUpdate() { + const viewTag = findNodeHandle(this.viewNode); + + if (this.viewTag !== viewTag) { + this.attachGestureHandler(viewTag); // TODO(TS) - check interaction between _viewTag & findNodeHandle + } + + this.update(); + } + + componentWillUnmount() { + var _this$inspectorToggle; + + (_this$inspectorToggle = this.inspectorToggleListener) === null || _this$inspectorToggle === void 0 ? void 0 : _this$inspectorToggle.remove(); + RNGestureHandlerModule.dropGestureHandler(this.handlerTag); + + if (this.updateEnqueued) { + clearImmediate(this.updateEnqueued); + } // We can't use this.props.id directly due to TS generic type narrowing bug, see https://github.com/microsoft/TypeScript/issues/13995 for more context + + + const handlerID = this.props.id; + + if (handlerID) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete handlerIDToTag[handlerID]; + } + } + + update() { + const newConfig = filterConfig(transformProps ? transformProps(this.props) : this.props, [...allowedProps, ...customNativeProps], config); + + if (!deepEqual(this.config, newConfig)) { + this.updateGestureHandler(newConfig); + } + } + + setNativeProps(updates) { + const mergedProps = { ...this.props, + ...updates + }; + const newConfig = filterConfig(transformProps ? transformProps(mergedProps) : mergedProps, [...allowedProps, ...customNativeProps], config); + this.updateGestureHandler(newConfig); + } + + render() { + let gestureEventHandler = this.onGestureHandlerEvent; // Another instance of https://github.com/microsoft/TypeScript/issues/13995 + + const { + onGestureEvent, + onGestureHandlerEvent + } = this.props; + + if (onGestureEvent && typeof onGestureEvent !== 'function') { + // If it's not a method it should be an native Animated.event + // object. We set it directly as the handler for the view + // In this case nested handlers are not going to be supported + if (onGestureHandlerEvent) { + throw new Error('Nesting touch handlers with native animated driver is not supported yet'); + } + + gestureEventHandler = onGestureEvent; + } else { + if (onGestureHandlerEvent && typeof onGestureHandlerEvent !== 'function') { + throw new Error('Nesting touch handlers with native animated driver is not supported yet'); + } + } + + let gestureStateEventHandler = this.onGestureHandlerStateChange; // Another instance of https://github.com/microsoft/TypeScript/issues/13995 + + const { + onHandlerStateChange, + onGestureHandlerStateChange + } = this.props; + + if (onHandlerStateChange && typeof onHandlerStateChange !== 'function') { + // If it's not a method it should be an native Animated.event + // object. We set it directly as the handler for the view + // In this case nested handlers are not going to be supported + if (onGestureHandlerStateChange) { + throw new Error('Nesting touch handlers with native animated driver is not supported yet'); + } + + gestureStateEventHandler = onHandlerStateChange; + } else { + if (onGestureHandlerStateChange && typeof onGestureHandlerStateChange !== 'function') { + throw new Error('Nesting touch handlers with native animated driver is not supported yet'); + } + } + + const events = { + onGestureHandlerEvent: this.state.allowTouches ? gestureEventHandler : undefined, + onGestureHandlerStateChange: this.state.allowTouches ? gestureStateEventHandler : undefined + }; + this.propsRef.current = events; + const child = React.Children.only(this.props.children); + let grandChildren = child.props.children; + + if (Touchable.TOUCH_TARGET_DEBUG && child.type && (child.type === 'RNGestureHandlerButton' || child.type.name === 'View' || child.type.displayName === 'View')) { + grandChildren = React.Children.toArray(grandChildren); + grandChildren.push(Touchable.renderDebugView({ + color: 'mediumspringgreen', + hitSlop: child.props.hitSlop + })); + } + + return /*#__PURE__*/React.cloneElement(child, { + ref: this.refHandler, + collapsable: false, + ...events + }, grandChildren); + } + + } + + _defineProperty(Handler, "displayName", name); + + return Handler; +} +//# sourceMappingURL=createHandler.js.map \ No newline at end of file diff --git a/lib/module/handlers/createHandler.js.map b/lib/module/handlers/createHandler.js.map new file mode 100644 index 0000000000..578e410626 --- /dev/null +++ b/lib/module/handlers/createHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["createHandler.ts"],"names":["React","Platform","Touchable","UIManager","DeviceEventEmitter","deepEqual","RNGestureHandlerModule","State","handlerIDToTag","getNextHandlerTag","filterConfig","findNodeHandle","UIManagerAny","customGHEventsConfig","onGestureHandlerEvent","registrationName","onGestureHandlerStateChange","genericDirectEventTypes","UIManagerConstants","getViewManagerConfig","getConstants","setJSResponder","oldSetJSResponder","clearJSResponder","oldClearJSResponder","tag","blockNativeResponder","handleSetJSResponder","handleClearJSResponder","allowTouches","DEV_ON_ANDROID","__DEV__","OS","addListener","hasUnresolvedRefs","props","extract","refs","Array","isArray","current","some","r","stateToPropMappings","UNDETERMINED","undefined","BEGAN","FAILED","CANCELLED","ACTIVE","END","showedRngh2Notice","showRngh2NoticeIfNeeded","console","warn","createHandler","name","allowedProps","config","transformProps","customNativeProps","Handler","Component","constructor","event","nativeEvent","handlerTag","onGestureEvent","onHandlerStateChange","state","stateEventName","eventHandler","node","viewNode","child","Children","only","children","ref","newConfig","createGestureHandler","newViewTag","viewTag","attachGestureHandler","propsRef","updateGestureHandler","createRef","id","Error","componentDidMount","inspectorToggleListener","setState","_","update","updateEnqueued","setImmediate","componentDidUpdate","componentWillUnmount","remove","dropGestureHandler","clearImmediate","handlerID","setNativeProps","updates","mergedProps","render","gestureEventHandler","gestureStateEventHandler","events","grandChildren","TOUCH_TARGET_DEBUG","type","displayName","toArray","push","renderDebugView","color","hitSlop","cloneElement","refHandler","collapsable"],"mappings":";;;;AAAA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AACA,SACEC,QADF,EAEEC,SAFF,EAGEC,SAHF,EAIEC,kBAJF,QAMO,cANP,C,CAOA;;AACA,OAAOC,SAAP,MAAsB,gBAAtB;AACA,OAAOC,sBAAP,MAAmC,2BAAnC;AAEA,SAASC,KAAT,QAAsB,UAAtB;AACA,SAASC,cAAT,EAAyBC,iBAAzB,QAAkD,oBAAlD;AAEA,SAEEC,YAFF,EAKEC,cALF,QAMO,wBANP;AASA,MAAMC,YAAY,GAAGT,SAArB;AAEA,MAAMU,oBAAoB,GAAG;AAC3BC,EAAAA,qBAAqB,EAAE;AAAEC,IAAAA,gBAAgB,EAAE;AAApB,GADI;AAE3BC,EAAAA,2BAA2B,EAAE;AAC3BD,IAAAA,gBAAgB,EAAE;AADS;AAFF,CAA7B,C,CAOA;AACA;AACA;AACA;;AACAH,YAAY,CAACK,uBAAb,GAAuC,EACrC,GAAGL,YAAY,CAACK,uBADqB;AAErC,KAAGJ;AAFkC,CAAvC,C,CAIA;AACA;AACA;;AACA,MAAMK,kBAAkB,sDACtBN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H,eAAV,CAA0B;AACxBC,UAAAA,KAAK,EAAE,mBADiB;AAExBC,UAAAA,OAAO,EAAE3C,KAAK,CAACvC,KAAN,CAAYkF;AAFG,SAA1B,CADF;AAMD;;AAED,0BAAOrH,KAAK,CAACsH,YAAN,CACL5C,KADK,EAEL;AACEI,QAAAA,GAAG,EAAE,KAAKyC,UADZ;AAEEC,QAAAA,WAAW,EAAE,KAFf;AAGE,WAAGZ;AAHL,OAFK,EAOLC,aAPK,CAAP;AASD;;AAhSD;;AAPwE,kBAIpEhD,OAJoE,iBAQnDL,IARmD;;AAyS1E,SAAOK,OAAP;AACD","sourcesContent":["import * as React from 'react';\nimport {\n Platform,\n Touchable,\n UIManager,\n DeviceEventEmitter,\n EmitterSubscription,\n} from 'react-native';\n// @ts-ignore - it isn't typed by TS & don't have definitelyTyped types\nimport deepEqual from 'lodash/isEqual';\nimport RNGestureHandlerModule from '../RNGestureHandlerModule';\nimport type RNGestureHandlerModuleWeb from '../RNGestureHandlerModule.web';\nimport { State } from '../State';\nimport { handlerIDToTag, getNextHandlerTag } from './handlersRegistry';\n\nimport {\n BaseGestureHandlerProps,\n filterConfig,\n GestureEvent,\n HandlerStateChangeEvent,\n findNodeHandle,\n} from './gestureHandlerCommon';\nimport { ValueOf } from '../typeUtils';\n\nconst UIManagerAny = UIManager as any;\n\nconst customGHEventsConfig = {\n onGestureHandlerEvent: { registrationName: 'onGestureHandlerEvent' },\n onGestureHandlerStateChange: {\n registrationName: 'onGestureHandlerStateChange',\n },\n};\n\n// Add gesture specific events to genericDirectEventTypes object exported from UIManager\n// native module.\n// Once new event types are registered with react it is possible to dispatch these\n// events to all kind of native views.\nUIManagerAny.genericDirectEventTypes = {\n ...UIManagerAny.genericDirectEventTypes,\n ...customGHEventsConfig,\n};\n// In newer versions of RN the `genericDirectEventTypes` is located in the object\n// returned by UIManager.getViewManagerConfig('getConstants') or in older RN UIManager.getConstants(), we need to add it there as well to make\n// it compatible with RN 61+\nconst UIManagerConstants =\n UIManagerAny.getViewManagerConfig?.('getConstants') ??\n UIManagerAny.getConstants?.();\n\nif (UIManagerConstants) {\n UIManagerConstants.genericDirectEventTypes = {\n ...UIManagerConstants.genericDirectEventTypes,\n ...customGHEventsConfig,\n };\n}\n\n// Wrap JS responder calls and notify gesture handler manager\nconst {\n setJSResponder: oldSetJSResponder = () => {\n //no operation\n },\n clearJSResponder: oldClearJSResponder = () => {\n //no operation\n },\n} = UIManagerAny;\nUIManagerAny.setJSResponder = (tag: number, blockNativeResponder: boolean) => {\n RNGestureHandlerModule.handleSetJSResponder(tag, blockNativeResponder);\n oldSetJSResponder(tag, blockNativeResponder);\n};\nUIManagerAny.clearJSResponder = () => {\n RNGestureHandlerModule.handleClearJSResponder();\n oldClearJSResponder();\n};\n\nlet allowTouches = true;\nconst DEV_ON_ANDROID = __DEV__ && Platform.OS === 'android';\n// Toggled inspector blocks touch events in order to allow inspecting on Android\n// This needs to be a global variable in order to set initial state for `allowTouches` property in Handler component\nif (DEV_ON_ANDROID) {\n DeviceEventEmitter.addListener('toggleElementInspector', () => {\n allowTouches = !allowTouches;\n });\n}\n\ntype HandlerProps> = Readonly<\n React.PropsWithChildren>\n>;\nfunction hasUnresolvedRefs>(\n props: HandlerProps\n) {\n // TODO(TS) - add type for extract arg\n const extract = (refs: any | any[]) => {\n if (!Array.isArray(refs)) {\n return refs && refs.current === null;\n }\n return refs.some((r) => r && r.current === null);\n };\n return extract(props['simultaneousHandlers']) || extract(props['waitFor']);\n}\n\nconst stateToPropMappings = {\n [State.UNDETERMINED]: undefined,\n [State.BEGAN]: 'onBegan',\n [State.FAILED]: 'onFailed',\n [State.CANCELLED]: 'onCancelled',\n [State.ACTIVE]: 'onActivated',\n [State.END]: 'onEnded',\n} as const;\n\ntype CreateHandlerArgs<\n HandlerPropsT extends Record\n> = Readonly<{\n name: string;\n allowedProps: Readonly[]>;\n config: Readonly>;\n transformProps?: (props: HandlerPropsT) => HandlerPropsT;\n customNativeProps?: Readonly;\n}>;\n\n// TODO(TS) fix event types\ntype InternalEventHandlers = {\n onGestureHandlerEvent?: (event: any) => void;\n onGestureHandlerStateChange?: (event: any) => void;\n};\n\nlet showedRngh2Notice = false;\nfunction showRngh2NoticeIfNeeded() {\n if (!showedRngh2Notice) {\n console.warn(\n \"[react-native-gesture-handler] Seems like you're using an old API with gesture components, check out new Gestures system!\"\n );\n showedRngh2Notice = true;\n }\n}\n\n// TODO(TS) - make sure that BaseGestureHandlerProps doesn't need other generic parameter to work with custom properties.\nexport default function createHandler<\n T extends BaseGestureHandlerProps,\n U extends Record\n>({\n name,\n allowedProps = [],\n config = {},\n transformProps,\n customNativeProps = [],\n}: CreateHandlerArgs): React.ComponentType> {\n interface HandlerState {\n allowTouches: boolean;\n }\n class Handler extends React.Component<\n T & InternalEventHandlers,\n HandlerState\n > {\n static displayName = name;\n\n private handlerTag: number;\n private config: Record;\n private propsRef: React.MutableRefObject;\n private viewNode: any;\n private viewTag?: number;\n private updateEnqueued: ReturnType | null = null;\n private inspectorToggleListener?: EmitterSubscription;\n\n constructor(props: T & InternalEventHandlers) {\n super(props);\n this.handlerTag = getNextHandlerTag();\n this.config = {};\n this.propsRef = React.createRef();\n this.state = { allowTouches };\n if (props.id) {\n if (handlerIDToTag[props.id] !== undefined) {\n throw new Error(`Handler with ID \"${props.id}\" already registered`);\n }\n handlerIDToTag[props.id] = this.handlerTag;\n }\n if (__DEV__) {\n showRngh2NoticeIfNeeded();\n }\n }\n\n componentDidMount() {\n const props: HandlerProps = this.props;\n\n if (DEV_ON_ANDROID) {\n this.inspectorToggleListener = DeviceEventEmitter.addListener(\n 'toggleElementInspector',\n () => {\n this.setState((_) => ({ allowTouches }));\n this.update();\n }\n );\n }\n if (hasUnresolvedRefs(props)) {\n // If there are unresolved refs (e.g. \".current\" has not yet been set)\n // passed as `simultaneousHandlers` or `waitFor`, we enqueue a call to\n // _update method that will try to update native handler props using\n // setImmediate. This makes it so update() function gets called after all\n // react components are mounted and we expect the missing ref object to\n // be resolved by then.\n this.updateEnqueued = setImmediate(() => {\n this.updateEnqueued = null;\n this.update();\n });\n }\n\n this.createGestureHandler(\n filterConfig(\n transformProps ? transformProps(this.props) : this.props,\n [...allowedProps, ...customNativeProps],\n config\n )\n );\n\n this.attachGestureHandler(findNodeHandle(this.viewNode) as number); // TODO(TS) - check if this can be null\n }\n\n componentDidUpdate() {\n const viewTag = findNodeHandle(this.viewNode);\n if (this.viewTag !== viewTag) {\n this.attachGestureHandler(viewTag as number); // TODO(TS) - check interaction between _viewTag & findNodeHandle\n }\n this.update();\n }\n\n componentWillUnmount() {\n this.inspectorToggleListener?.remove();\n RNGestureHandlerModule.dropGestureHandler(this.handlerTag);\n if (this.updateEnqueued) {\n clearImmediate(this.updateEnqueued);\n }\n // We can't use this.props.id directly due to TS generic type narrowing bug, see https://github.com/microsoft/TypeScript/issues/13995 for more context\n const handlerID: string | undefined = this.props.id;\n if (handlerID) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete handlerIDToTag[handlerID];\n }\n }\n\n private onGestureHandlerEvent = (event: GestureEvent) => {\n if (event.nativeEvent.handlerTag === this.handlerTag) {\n this.props.onGestureEvent?.(event);\n } else {\n this.props.onGestureHandlerEvent?.(event);\n }\n };\n\n // TODO(TS) - make sure this is right type for event\n private onGestureHandlerStateChange = (\n event: HandlerStateChangeEvent\n ) => {\n if (event.nativeEvent.handlerTag === this.handlerTag) {\n this.props.onHandlerStateChange?.(event);\n\n const state: ValueOf = event.nativeEvent.state;\n const stateEventName = stateToPropMappings[state];\n const eventHandler = stateEventName && this.props[stateEventName];\n if (eventHandler && typeof eventHandler === 'function') {\n eventHandler(event);\n }\n } else {\n this.props.onGestureHandlerStateChange?.(event);\n }\n };\n\n private refHandler = (node: any) => {\n this.viewNode = node;\n\n const child = React.Children.only(this.props.children);\n // TODO(TS) fix ref type\n const { ref }: any = child;\n if (ref !== null) {\n if (typeof ref === 'function') {\n ref(node);\n } else {\n ref.current = node;\n }\n }\n };\n\n private createGestureHandler = (\n newConfig: Readonly>\n ) => {\n this.config = newConfig;\n\n RNGestureHandlerModule.createGestureHandler(\n name,\n this.handlerTag,\n newConfig\n );\n };\n\n private attachGestureHandler = (newViewTag: number) => {\n this.viewTag = newViewTag;\n\n if (Platform.OS === 'web') {\n // typecast due to dynamic resolution, attachGestureHandler should have web version signature in this branch\n (RNGestureHandlerModule.attachGestureHandler as typeof RNGestureHandlerModuleWeb.attachGestureHandler)(\n this.handlerTag,\n newViewTag,\n false,\n this.propsRef\n );\n } else {\n RNGestureHandlerModule.attachGestureHandler(\n this.handlerTag,\n newViewTag,\n false\n );\n }\n };\n\n private updateGestureHandler = (\n newConfig: Readonly>\n ) => {\n this.config = newConfig;\n\n RNGestureHandlerModule.updateGestureHandler(this.handlerTag, newConfig);\n };\n\n private update() {\n const newConfig = filterConfig(\n transformProps ? transformProps(this.props) : this.props,\n [...allowedProps, ...customNativeProps],\n config\n );\n if (!deepEqual(this.config, newConfig)) {\n this.updateGestureHandler(newConfig);\n }\n }\n\n setNativeProps(updates: any) {\n const mergedProps = { ...this.props, ...updates };\n const newConfig = filterConfig(\n transformProps ? transformProps(mergedProps) : mergedProps,\n [...allowedProps, ...customNativeProps],\n config\n );\n this.updateGestureHandler(newConfig);\n }\n\n render() {\n let gestureEventHandler = this.onGestureHandlerEvent;\n // Another instance of https://github.com/microsoft/TypeScript/issues/13995\n type OnGestureEventHandlers = {\n onGestureEvent?: BaseGestureHandlerProps['onGestureEvent'];\n onGestureHandlerEvent?: InternalEventHandlers['onGestureHandlerEvent'];\n };\n const {\n onGestureEvent,\n onGestureHandlerEvent,\n }: OnGestureEventHandlers = this.props;\n if (onGestureEvent && typeof onGestureEvent !== 'function') {\n // If it's not a method it should be an native Animated.event\n // object. We set it directly as the handler for the view\n // In this case nested handlers are not going to be supported\n if (onGestureHandlerEvent) {\n throw new Error(\n 'Nesting touch handlers with native animated driver is not supported yet'\n );\n }\n gestureEventHandler = onGestureEvent;\n } else {\n if (\n onGestureHandlerEvent &&\n typeof onGestureHandlerEvent !== 'function'\n ) {\n throw new Error(\n 'Nesting touch handlers with native animated driver is not supported yet'\n );\n }\n }\n\n let gestureStateEventHandler = this.onGestureHandlerStateChange;\n // Another instance of https://github.com/microsoft/TypeScript/issues/13995\n type OnGestureStateChangeHandlers = {\n onHandlerStateChange?: BaseGestureHandlerProps['onHandlerStateChange'];\n onGestureHandlerStateChange?: InternalEventHandlers['onGestureHandlerStateChange'];\n };\n const {\n onHandlerStateChange,\n onGestureHandlerStateChange,\n }: OnGestureStateChangeHandlers = this.props;\n if (onHandlerStateChange && typeof onHandlerStateChange !== 'function') {\n // If it's not a method it should be an native Animated.event\n // object. We set it directly as the handler for the view\n // In this case nested handlers are not going to be supported\n if (onGestureHandlerStateChange) {\n throw new Error(\n 'Nesting touch handlers with native animated driver is not supported yet'\n );\n }\n gestureStateEventHandler = onHandlerStateChange;\n } else {\n if (\n onGestureHandlerStateChange &&\n typeof onGestureHandlerStateChange !== 'function'\n ) {\n throw new Error(\n 'Nesting touch handlers with native animated driver is not supported yet'\n );\n }\n }\n const events = {\n onGestureHandlerEvent: this.state.allowTouches\n ? gestureEventHandler\n : undefined,\n onGestureHandlerStateChange: this.state.allowTouches\n ? gestureStateEventHandler\n : undefined,\n };\n\n this.propsRef.current = events;\n\n const child: any = React.Children.only(this.props.children);\n let grandChildren = child.props.children;\n if (\n Touchable.TOUCH_TARGET_DEBUG &&\n child.type &&\n (child.type === 'RNGestureHandlerButton' ||\n child.type.name === 'View' ||\n child.type.displayName === 'View')\n ) {\n grandChildren = React.Children.toArray(grandChildren);\n grandChildren.push(\n Touchable.renderDebugView({\n color: 'mediumspringgreen',\n hitSlop: child.props.hitSlop,\n })\n );\n }\n\n return React.cloneElement(\n child,\n {\n ref: this.refHandler,\n collapsable: false,\n ...events,\n },\n grandChildren\n );\n }\n }\n return Handler;\n}\n"]} \ No newline at end of file diff --git a/lib/module/handlers/createNativeWrapper.js b/lib/module/handlers/createNativeWrapper.js new file mode 100644 index 0000000000..ae34b121d7 --- /dev/null +++ b/lib/module/handlers/createNativeWrapper.js @@ -0,0 +1,58 @@ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +import * as React from 'react'; +import { useImperativeHandle, useRef } from 'react'; +import { NativeViewGestureHandler, nativeViewProps } from './NativeViewGestureHandler'; +/* + * This array should consist of: + * - All keys in propTypes from NativeGestureHandler + * (and all keys in GestureHandlerPropTypes) + * - 'onGestureHandlerEvent' + * - 'onGestureHandlerStateChange' + */ + +const NATIVE_WRAPPER_PROPS_FILTER = [...nativeViewProps, 'onGestureHandlerEvent', 'onGestureHandlerStateChange']; +export default function createNativeWrapper(Component, config = {}) { + const ComponentWrapper = /*#__PURE__*/React.forwardRef((props, ref) => { + // filter out props that should be passed to gesture handler wrapper + const gestureHandlerProps = Object.keys(props).reduce((res, key) => { + // TS being overly protective with it's types, see https://github.com/microsoft/TypeScript/issues/26255#issuecomment-458013731 for more info + const allowedKeys = NATIVE_WRAPPER_PROPS_FILTER; + + if (allowedKeys.includes(key)) { + // @ts-ignore FIXME(TS) + res[key] = props[key]; + } + + return res; + }, { ...config + } // watch out not to modify config + ); + + const _ref = useRef(); + + const _gestureHandlerRef = useRef(); + + useImperativeHandle(ref, // @ts-ignore TODO(TS) decide how nulls work in this context + () => { + const node = _gestureHandlerRef.current; // add handlerTag for relations config + + if (_ref.current && node) { + // @ts-ignore FIXME(TS) think about createHandler return type + _ref.current.handlerTag = node.handlerTag; + return _ref.current; + } + + return null; + }, [_ref, _gestureHandlerRef]); + return /*#__PURE__*/React.createElement(NativeViewGestureHandler, _extends({}, gestureHandlerProps, { + // @ts-ignore TODO(TS) + ref: _gestureHandlerRef + }), /*#__PURE__*/React.createElement(Component, _extends({}, props, { + ref: _ref + }))); + }); + ComponentWrapper.displayName = Component.displayName || 'ComponentWrapper'; + return ComponentWrapper; +} +//# sourceMappingURL=createNativeWrapper.js.map \ No newline at end of file diff --git a/lib/module/handlers/createNativeWrapper.js.map b/lib/module/handlers/createNativeWrapper.js.map new file mode 100644 index 0000000000..83d5949a7f --- /dev/null +++ b/lib/module/handlers/createNativeWrapper.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["createNativeWrapper.tsx"],"names":["React","useImperativeHandle","useRef","NativeViewGestureHandler","nativeViewProps","NATIVE_WRAPPER_PROPS_FILTER","createNativeWrapper","Component","config","ComponentWrapper","forwardRef","props","ref","gestureHandlerProps","Object","keys","reduce","res","key","allowedKeys","includes","_ref","_gestureHandlerRef","node","current","handlerTag","displayName"],"mappings":";;AAAA,OAAO,KAAKA,KAAZ,MAAuB,OAAvB;AACA,SAASC,mBAAT,EAA8BC,MAA9B,QAA4C,OAA5C;AAEA,SACEC,wBADF,EAGEC,eAHF,QAIO,4BAJP;AAMA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA,MAAMC,2BAA2B,GAAG,CAClC,GAAGD,eAD+B,EAElC,uBAFkC,EAGlC,6BAHkC,CAApC;AAMA,eAAe,SAASE,mBAAT,CACbC,SADa,EAEbC,MAA+C,GAAG,EAFrC,EAGb;AACA,QAAMC,gBAAgB,gBAAGT,KAAK,CAACU,UAAN,CAGvB,CAACC,KAAD,EAAQC,GAAR,KAAgB;AAChB;AACA,UAAMC,mBAAmB,GAAGC,MAAM,CAACC,IAAP,CAAYJ,KAAZ,EAAmBK,MAAnB,CAC1B,CAACC,GAAD,EAAMC,GAAN,KAAc;AACZ;AACA,YAAMC,WAA8B,GAAGd,2BAAvC;;AACA,UAAIc,WAAW,CAACC,QAAZ,CAAqBF,GAArB,CAAJ,EAA+B;AAC7B;AACAD,QAAAA,GAAG,CAACC,GAAD,CAAH,GAAWP,KAAK,CAACO,GAAD,CAAhB;AACD;;AACD,aAAOD,GAAP;AACD,KATyB,EAU1B,EAAE,GAAGT;AAAL,KAV0B,CAUZ;AAVY,KAA5B;;AAYA,UAAMa,IAAI,GAAGnB,MAAM,EAAnB;;AACA,UAAMoB,kBAAkB,GAAGpB,MAAM,EAAjC;;AACAD,IAAAA,mBAAmB,CACjBW,GADiB,EAEjB;AACA,UAAM;AACJ,YAAMW,IAAI,GAAGD,kBAAkB,CAACE,OAAhC,CADI,CAEJ;;AACA,UAAIH,IAAI,CAACG,OAAL,IAAgBD,IAApB,EAA0B;AACxB;AACAF,QAAAA,IAAI,CAACG,OAAL,CAAaC,UAAb,GAA0BF,IAAI,CAACE,UAA/B;AACA,eAAOJ,IAAI,CAACG,OAAZ;AACD;;AACD,aAAO,IAAP;AACD,KAZgB,EAajB,CAACH,IAAD,EAAOC,kBAAP,CAbiB,CAAnB;AAeA,wBACE,oBAAC,wBAAD,eACMT,mBADN;AAEE;AACA,MAAA,GAAG,EAAES;AAHP,qBAIE,oBAAC,SAAD,eAAeX,KAAf;AAAsB,MAAA,GAAG,EAAEU;AAA3B,OAJF,CADF;AAQD,GA1CwB,CAAzB;AA4CAZ,EAAAA,gBAAgB,CAACiB,WAAjB,GAA+BnB,SAAS,CAACmB,WAAV,IAAyB,kBAAxD;AAEA,SAAOjB,gBAAP;AACD","sourcesContent":["import * as React from 'react';\nimport { useImperativeHandle, useRef } from 'react';\n\nimport {\n NativeViewGestureHandler,\n NativeViewGestureHandlerProps,\n nativeViewProps,\n} from './NativeViewGestureHandler';\n\n/*\n * This array should consist of:\n * - All keys in propTypes from NativeGestureHandler\n * (and all keys in GestureHandlerPropTypes)\n * - 'onGestureHandlerEvent'\n * - 'onGestureHandlerStateChange'\n */\nconst NATIVE_WRAPPER_PROPS_FILTER = [\n ...nativeViewProps,\n 'onGestureHandlerEvent',\n 'onGestureHandlerStateChange',\n] as const;\n\nexport default function createNativeWrapper

(\n Component: React.ComponentType

,\n config: Readonly = {}\n) {\n const ComponentWrapper = React.forwardRef<\n React.ComponentType,\n P & NativeViewGestureHandlerProps\n >((props, ref) => {\n // filter out props that should be passed to gesture handler wrapper\n const gestureHandlerProps = Object.keys(props).reduce(\n (res, key) => {\n // TS being overly protective with it's types, see https://github.com/microsoft/TypeScript/issues/26255#issuecomment-458013731 for more info\n const allowedKeys: readonly string[] = NATIVE_WRAPPER_PROPS_FILTER;\n if (allowedKeys.includes(key)) {\n // @ts-ignore FIXME(TS)\n res[key] = props[key];\n }\n return res;\n },\n { ...config } // watch out not to modify config\n );\n const _ref = useRef>();\n const _gestureHandlerRef = useRef>();\n useImperativeHandle(\n ref,\n // @ts-ignore TODO(TS) decide how nulls work in this context\n () => {\n const node = _gestureHandlerRef.current;\n // add handlerTag for relations config\n if (_ref.current && node) {\n // @ts-ignore FIXME(TS) think about createHandler return type\n _ref.current.handlerTag = node.handlerTag;\n return _ref.current;\n }\n return null;\n },\n [_ref, _gestureHandlerRef]\n );\n return (\n \n \n \n );\n });\n\n ComponentWrapper.displayName = Component.displayName || 'ComponentWrapper';\n\n return ComponentWrapper;\n}\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestureHandlerCommon.js b/lib/module/handlers/gestureHandlerCommon.js new file mode 100644 index 0000000000..2b0801ce8d --- /dev/null +++ b/lib/module/handlers/gestureHandlerCommon.js @@ -0,0 +1,66 @@ +// Previous types exported gesture handlers as classes which creates an interface and variable, both named the same as class. +// Without those types, we'd introduce breaking change, forcing users to prefix every handler type specification with typeof +// e.g. React.createRef -> React.createRef. +// See https://www.typescriptlang.org/docs/handbook/classes.html#constructor-functions for reference. +import { Platform, findNodeHandle as findNodeHandleRN } from 'react-native'; +import { handlerIDToTag } from './handlersRegistry'; +import { toArray } from '../utils'; +const commonProps = ['id', 'enabled', 'shouldCancelWhenOutside', 'hitSlop']; +const componentInteractionProps = ['waitFor', 'simultaneousHandlers']; +export const baseGestureHandlerProps = [...commonProps, ...componentInteractionProps, 'onBegan', 'onFailed', 'onCancelled', 'onActivated', 'onEnded', 'onGestureEvent', 'onHandlerStateChange']; +export const baseGestureHandlerWithMonitorProps = [...commonProps, 'needsPointerData', 'manualActivation']; + +function isConfigParam(param, name) { + // param !== Object(param) returns false if `param` is a function + // or an object and returns true if `param` is null + return param !== undefined && (param !== Object(param) || !('__isNative' in param)) && name !== 'onHandlerStateChange' && name !== 'onGestureEvent'; +} + +export function filterConfig(props, validProps, defaults = {}) { + const filteredConfig = { ...defaults + }; + + for (const key of validProps) { + let value = props[key]; + + if (isConfigParam(value, key)) { + if (key === 'simultaneousHandlers' || key === 'waitFor') { + value = transformIntoHandlerTags(props[key]); + } else if (key === 'hitSlop' && typeof value !== 'object') { + value = { + top: value, + left: value, + bottom: value, + right: value + }; + } + + filteredConfig[key] = value; + } + } + + return filteredConfig; +} + +function transformIntoHandlerTags(handlerIDs) { + handlerIDs = toArray(handlerIDs); + + if (Platform.OS === 'web') { + return handlerIDs.map(({ + current + }) => current).filter(handle => handle); + } // converts handler string IDs into their numeric tags + + + return handlerIDs.map(handlerID => { + var _handlerID$current; + + return handlerIDToTag[handlerID] || ((_handlerID$current = handlerID.current) === null || _handlerID$current === void 0 ? void 0 : _handlerID$current.handlerTag) || -1; + }).filter(handlerTag => handlerTag > 0); +} + +export function findNodeHandle(node) { + if (Platform.OS === 'web') return node; + return findNodeHandleRN(node); +} +//# sourceMappingURL=gestureHandlerCommon.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestureHandlerCommon.js.map b/lib/module/handlers/gestureHandlerCommon.js.map new file mode 100644 index 0000000000..b98b3b2607 --- /dev/null +++ b/lib/module/handlers/gestureHandlerCommon.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["gestureHandlerCommon.ts"],"names":["Platform","findNodeHandle","findNodeHandleRN","handlerIDToTag","toArray","commonProps","componentInteractionProps","baseGestureHandlerProps","baseGestureHandlerWithMonitorProps","isConfigParam","param","name","undefined","Object","filterConfig","props","validProps","defaults","filteredConfig","key","value","transformIntoHandlerTags","top","left","bottom","right","handlerIDs","OS","map","current","filter","handle","handlerID","handlerTag","node"],"mappings":"AAAA;AACA;AACA;AACA;AAEA,SAASA,QAAT,EAAmBC,cA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AAOC,KAAP,KAAiB,QAA1C,EAAoD;AACzDA,QAAAA,KAAK,GAAG;AAAEE,UAAAA,GAAG,EAAEF,KAAP;AAAcG,UAAAA,IAAI,EAAEH,KAApB;AAA2BI,UAAAA,MAAM,EAAEJ,KAAnC;AAA0CK,UAAAA,KAAK,EAAEL;AAAjD,SAAR;AACD;;AACDF,MAAAA,cAAc,CAACC,GAAD,CAAd,GAAsBC,KAAtB;AACD;AACF;;AACD,SAAOF,cAAP;AACD;;AAED,SAASG,wBAAT,CAAkCK,UAAlC,EAAmD;AACjDA,EAAAA,UAAU,GAAGtB,OAAO,CAACsB,UAAD,CAApB;;AAEA,MAAI1B,QAAQ,CAAC2B,EAAT,KAAgB,KAApB,EAA2B;AACzB,WAAOD,UAAU,CACdE,GADI,CACA,CAAC;AAAEC,MAAAA;AAAF,KAAD,KAAmCA,OADnC,EAEJC,MAFI,CAEIC,MAAD,IAAiBA,MAFpB,CAAP;AAGD,GAPgD,CAQjD;;;AACA,SAAOL,UAAU,CACdE,GADI,CAEFI,SAAD;AAAA;;AAAA,WACE7B,cAAc,CAAC6B,SAAD,CAAd,2BAA6BA,SAAS,CAACH,OAAvC,uDAA6B,mBAAmBI,UAAhD,KAA8D,CAAC,CADjE;AAAA,GAFG,EAKJH,MALI,CAKIG,UAAD,IAAwBA,UAAU,GAAG,CALxC,CAAP;AAMD;;AAED,OAAO,SAAShC,cAAT,CACLiC,IADK,EAEkE;AACvE,MAAIlC,QAAQ,CAAC2B,EAAT,KAAgB,KAApB,EAA2B,OAAOO,IAAP;AAC3B,SAAOhC,gBAAgB,CAACgC,IAAD,CAAvB;AACD","sourcesContent":["// Previous types exported gesture handlers as classes which creates an interface and variable, both named the same as class.\n// Without those types, we'd introduce breaking change, forcing users to prefix every handler type specification with typeof\n// e.g. React.createRef -> React.createRef.\n// See https://www.typescriptlang.org/docs/handbook/classes.html#constructor-functions for reference.\nimport * as React from 'react';\nimport { Platform, findNodeHandle as findNodeHandleRN } from 'react-native';\n\nimport { State } from '../State';\nimport { EventType } from '../EventType';\nimport { ValueOf } from '../typeUtils';\nimport { handlerIDToTag } from './handlersRegistry';\nimport { toArray } from '../utils';\n\nconst commonProps = [\n 'id',\n 'enabled',\n 'shouldCancelWhenOutside',\n 'hitSlop',\n] as const;\n\nconst componentInteractionProps = ['waitFor', 'simultaneousHandlers'] as const;\n\nexport const baseGestureHandlerProps = [\n ...commonProps,\n ...componentInteractionProps,\n 'onBegan',\n 'onFailed',\n 'onCancelled',\n 'onActivated',\n 'onEnded',\n 'onGestureEvent',\n 'onHandlerStateChange',\n] as const;\n\nexport const baseGestureHandlerWithMonitorProps = [\n ...commonProps,\n 'needsPointerData',\n 'manualActivation',\n];\n\nexport interface GestureEventPayload {\n handlerTag: number;\n numberOfPointers: number;\n state: ValueOf;\n}\n\nexport interface HandlerStateChangeEventPayload {\n handlerTag: number;\n numberOfPointers: number;\n state: ValueOf;\n oldState: ValueOf;\n}\n\nexport type HitSlop =\n | number\n | Partial<\n Record<\n 'left' | 'right' | 'top' | 'bottom' | 'vertical' | 'horizontal',\n number\n >\n >\n | Record<'width' | 'left', number>\n | Record<'width' | 'right', number>\n | Record<'height' | 'top', number>\n | Record<'height' | 'bottom', number>;\n\n//TODO(TS) events in handlers\n\nexport interface GestureEvent> {\n nativeEvent: Readonly;\n}\nexport interface HandlerStateChangeEvent<\n ExtraEventPayloadT = Record\n> {\n nativeEvent: Readonly;\n}\n\nexport type TouchData = {\n id: number;\n x: number;\n y: number;\n absoluteX: number;\n absoluteY: number;\n};\n\nexport type GestureTouchEvent = {\n handlerTag: number;\n numberOfTouches: number;\n state: ValueOf;\n eventType: EventType;\n allTouches: TouchData[];\n changedTouches: TouchData[];\n};\n\nexport type GestureUpdateEvent<\n GestureEventPayloadT = Record\n> = GestureEventPayload & GestureEventPayloadT;\n\nexport type GestureStateChangeEvent<\n GestureStateChangeEventPayloadT = Record\n> = HandlerStateChangeEventPayload & GestureStateChangeEventPayloadT;\n\nexport type CommonGestureConfig = {\n enabled?: boolean;\n shouldCancelWhenOutside?: boolean;\n hitSlop?: HitSlop;\n};\n\n// Events payloads are types instead of interfaces due to TS limitation.\n// See https://github.com/microsoft/TypeScript/issues/15300 for more info.\nexport type BaseGestureHandlerProps<\n ExtraEventPayloadT extends Record = Record\n> = CommonGestureConfig & {\n id?: string;\n waitFor?: React.Ref | React.Ref[];\n simultaneousHandlers?: React.Ref | React.Ref[];\n // TODO(TS) - fix event types\n onBegan?: (event: HandlerStateChangeEvent) => void;\n onFailed?: (event: HandlerStateChangeEvent) => void;\n onCancelled?: (event: HandlerStateChangeEvent) => void;\n onActivated?: (event: HandlerStateChangeEvent) => void;\n onEnded?: (event: HandlerStateChangeEvent) => void;\n\n //TODO(TS) consider using NativeSyntheticEvent\n onGestureEvent?: (event: GestureEvent) => void;\n onHandlerStateChange?: (\n event: HandlerStateChangeEvent\n ) => void;\n};\n\nfunction isConfigParam(param: unknown, name: string) {\n // param !== Object(param) returns false if `param` is a function\n // or an object and returns true if `param` is null\n return (\n param !== undefined &&\n (param !== Object(param) ||\n !('__isNative' in (param as Record))) &&\n name !== 'onHandlerStateChange' &&\n name !== 'onGestureEvent'\n );\n}\n\nexport function filterConfig(\n props: Record,\n validProps: string[],\n defaults: Record = {}\n) {\n const filteredConfig = { ...defaults };\n for (const key of validProps) {\n let value = props[key];\n if (isConfigParam(value, key)) {\n if (key === 'simultaneousHandlers' || key === 'waitFor') {\n value = transformIntoHandlerTags(props[key]);\n } else if (key === 'hitSlop' && typeof value !== 'object') {\n value = { top: value, left: value, bottom: value, right: value };\n }\n filteredConfig[key] = value;\n }\n }\n return filteredConfig;\n}\n\nfunction transformIntoHandlerTags(handlerIDs: any) {\n handlerIDs = toArray(handlerIDs);\n\n if (Platform.OS === 'web') {\n return handlerIDs\n .map(({ current }: { current: any }) => current)\n .filter((handle: any) => handle);\n }\n // converts handler string IDs into their numeric tags\n return handlerIDs\n .map(\n (handlerID: any) =>\n handlerIDToTag[handlerID] || handlerID.current?.handlerTag || -1\n )\n .filter((handlerTag: number) => handlerTag > 0);\n}\n\nexport function findNodeHandle(\n node: null | number | React.Component | React.ComponentClass\n): null | number | React.Component | React.ComponentClass {\n if (Platform.OS === 'web') return node;\n return findNodeHandleRN(node);\n}\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestureHandlerTypesCompat.js b/lib/module/handlers/gestureHandlerTypesCompat.js new file mode 100644 index 0000000000..31a5362764 --- /dev/null +++ b/lib/module/handlers/gestureHandlerTypesCompat.js @@ -0,0 +1,2 @@ + +//# sourceMappingURL=gestureHandlerTypesCompat.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestureHandlerTypesCompat.js.map b/lib/module/handlers/gestureHandlerTypesCompat.js.map new file mode 100644 index 0000000000..9ffd4b22fc --- /dev/null +++ b/lib/module/handlers/gestureHandlerTypesCompat.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","sourcesContent":[]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/GestureDetector.js b/lib/module/handlers/gestures/GestureDetector.js new file mode 100644 index 0000000000..4f8fb599f2 --- /dev/null +++ b/lib/module/handlers/gestures/GestureDetector.js @@ -0,0 +1,402 @@ +var _Reanimated$default$c, _Reanimated$default; + +import React, { useEffect, useRef } from 'react'; +import { BaseGesture, CALLBACK_TYPE } from './gesture'; +import { Reanimated } from './reanimatedWrapper'; +import { registerHandler, unregisterHandler } from '../handlersRegistry'; +import RNGestureHandlerModule from '../../RNGestureHandlerModule'; +import { baseGestureHandlerWithMonitorProps, filterConfig, findNodeHandle } from '../gestureHandlerCommon'; +import { GestureStateManager } from './gestureStateManager'; +import { flingGestureHandlerProps } from '../FlingGestureHandler'; +import { forceTouchGestureHandlerProps } from '../ForceTouchGestureHandler'; +import { longPressGestureHandlerProps } from '../LongPressGestureHandler'; +import { panGestureHandlerProps, panGestureHandlerCustomNativeProps } from '../PanGestureHandler'; +import { tapGestureHandlerProps } from '../TapGestureHandler'; +import { State } from '../../State'; +import { EventType } from '../../EventType'; +const ALLOWED_PROPS = [...baseGestureHandlerWithMonitorProps, ...tapGestureHandlerProps, ...panGestureHandlerProps, ...panGestureHandlerCustomNativeProps, ...longPressGestureHandlerProps, ...forceTouchGestureHandlerProps, ...flingGestureHandlerProps]; + +function convertToHandlerTag(ref) { + if (typeof ref === 'number') { + return ref; + } else if (ref instanceof BaseGesture) { + return ref.handlerTag; + } else { + var _ref$current$handlerT, _ref$current; + + // @ts-ignore in this case it should be a ref either to gesture object or + // a gesture handler component, in both cases handlerTag property exists + return (_ref$current$handlerT = (_ref$current = ref.current) === null || _ref$current === void 0 ? void 0 : _ref$current.handlerTag) !== null && _ref$current$handlerT !== void 0 ? _ref$current$handlerT : -1; + } +} + +function extractValidHandlerTags(interactionGroup) { + var _interactionGroup$map, _interactionGroup$map2; + + return (_interactionGroup$map = interactionGroup === null || interactionGroup === void 0 ? void 0 : (_interactionGroup$map2 = interactionGroup.map(convertToHandlerTag)) === null || _interactionGroup$map2 === void 0 ? void 0 : _interactionGroup$map2.filter(tag => tag > 0)) !== null && _interactionGroup$map !== void 0 ? _interactionGroup$map : []; +} + +function dropHandlers(preparedGesture) { + for (const handler of preparedGesture.config) { + RNGestureHandlerModule.dropGestureHandler(handler.handlerTag); + unregisterHandler(handler.handlerTag); + } +} + +function attachHandlers({ + preparedGesture, + gestureConfig, + gesture, + viewTag, + useAnimated +}) { + if (!preparedGesture.firstExecution) { + gestureConfig === null || gestureConfig === void 0 ? void 0 : gestureConfig.initialize(); + } else { + preparedGesture.firstExecution = false; + } // use setImmediate to extract handlerTags, because all refs should be initialized + // when it's ran + + + setImmediate(() => { + gestureConfig === null || gestureConfig === void 0 ? void 0 : gestureConfig.prepare(); + }); + + for (const handler of gesture) { + RNGestureHandlerModule.createGestureHandler(handler.handlerName, handler.handlerTag, filterConfig(handler.config, ALLOWED_PROPS)); + registerHandler(handler.handlerTag, handler); // use setImmediate to extract handlerTags, because all refs should be initialized + // when it's ran + + setImmediate(() => { + let requireToFail = []; + + if (handler.config.requireToFail) { + requireToFail = extractValidHandlerTags(handler.config.requireToFail); + } + + let simultaneousWith = []; + + if (handler.config.simultaneousWith) { + simultaneousWith = extractValidHandlerTags(handler.config.simultaneousWith); + } + + RNGestureHandlerModule.updateGestureHandler(handler.handlerTag, filterConfig(handler.config, ALLOWED_PROPS, { + simultaneousHandlers: simultaneousWith, + waitFor: requireToFail + })); + }); + } + + preparedGesture.config = gesture; + + for (const gesture of preparedGesture.config) { + RNGestureHandlerModule.attachGestureHandler(gesture.handlerTag, viewTag, !useAnimated // send direct events when using animatedGesture, device events otherwise + ); + } + + if (preparedGesture.animatedHandlers) { + preparedGesture.animatedHandlers.value = gesture.map(g => g.handlers); + } +} + +function updateHandlers(preparedGesture, gestureConfig, gesture) { + gestureConfig === null || gestureConfig === void 0 ? void 0 : gestureConfig.prepare(); + + for (let i = 0; i < gesture.length; i++) { + const handler = preparedGesture.config[i]; + gesture[i].handlerTag = handler.handlerTag; + gesture[i].handlers.handlerTag = handler.handlerTag; + } // use setImmediate to extract handlerTags, because when it's ran, all refs should be updated + // and handlerTags in BaseGesture references should be updated in the loop above (we need to wait + // in case of external relations) + + + setImmediate(() => { + for (let i = 0; i < gesture.length; i++) { + const handler = preparedGesture.config[i]; + handler.config = gesture[i].config; + handler.handlers = gesture[i].handlers; + handler.handlers.handlerTag = handler.handlerTag; + const requireToFail = extractValidHandlerTags(handler.config.requireToFail); + const simultaneousWith = extractValidHandlerTags(handler.config.simultaneousWith); + RNGestureHandlerModule.updateGestureHandler(handler.handlerTag, filterConfig(handler.config, ALLOWED_PROPS, { + simultaneousHandlers: simultaneousWith, + waitFor: requireToFail + })); + registerHandler(handler.handlerTag, handler); + } + + if (preparedGesture.animatedHandlers) { + preparedGesture.animatedHandlers.value = preparedGesture.config.map(g => g.handlers); + } + }); +} + +function needsToReattach(preparedGesture, gesture) { + if (gesture.length !== preparedGesture.config.length) { + return true; + } + + for (let i = 0; i < gesture.length; i++) { + if (gesture[i].handlerName !== preparedGesture.config[i].handlerName) { + return true; + } + } + + return false; +} + +function useAnimatedGesture(preparedGesture) { + if (!Reanimated) { + return; + } + + function isStateChangeEvent(event) { + 'worklet'; // @ts-ignore Yes, the oldState prop is missing on GestureTouchEvent, that's the point + + return event.oldState != null; + } + + function isTouchEvent(event) { + 'worklet'; + + return event.eventType != null; + } + + function getHandler(type, gesture) { + 'worklet'; + + switch (type) { + case CALLBACK_TYPE.BEGAN: + return gesture.onBegin; + + case CALLBACK_TYPE.START: + return gesture.onStart; + + case CALLBACK_TYPE.UPDATE: + return gesture.onUpdate; + + case CALLBACK_TYPE.CHANGE: + return gesture.onChange; + + case CALLBACK_TYPE.END: + return gesture.onEnd; + + case CALLBACK_TYPE.FINALIZE: + return gesture.onFinalize; + + case CALLBACK_TYPE.TOUCHES_DOWN: + return gesture.onTouchesDown; + + case CALLBACK_TYPE.TOUCHES_MOVE: + return gesture.onTouchesMove; + + case CALLBACK_TYPE.TOUCHES_UP: + return gesture.onTouchesUp; + + case CALLBACK_TYPE.TOUCHES_CANCELLED: + return gesture.onTouchesCancelled; + } + } + + function touchEventTypeToCallbackType(eventType) { + 'worklet'; + + switch (eventType) { + case EventType.TOUCHES_DOWN: + return CALLBACK_TYPE.TOUCHES_DOWN; + + case EventType.TOUCHES_MOVE: + return CALLBACK_TYPE.TOUCHES_MOVE; + + case EventType.TOUCHES_UP: + return CALLBACK_TYPE.TOUCHES_UP; + + case EventType.TOUCHES_CANCELLED: + return CALLBACK_TYPE.TOUCHES_CANCELLED; + } + + return CALLBACK_TYPE.UNDEFINED; + } + + function runWorklet(type, gesture, event, ...args) { + 'worklet'; + + const handler = getHandler(type, gesture); + + if (gesture.isWorklet[type]) { + // @ts-ignore Logic below makes sure the correct event is send to the + // correct handler. + handler === null || handler === void 0 ? void 0 : handler(event, ...args); + } else if (handler) { + console.warn('Animated gesture callback must be a worklet'); + } + } // Hooks are called conditionally, but the condition is whether the + // react-native-reanimated is installed, which shouldn't change while running + // eslint-disable-next-line react-hooks/rules-of-hooks + + + const sharedHandlersCallbacks = Reanimated.useSharedValue(null); // eslint-disable-next-line react-hooks/rules-of-hooks + + const lastUpdateEvent = Reanimated.useSharedValue([]); // not every gesture needs a state controller, init them lazily + + const stateControllers = []; + + const callback = event => { + 'worklet'; + + const currentCallback = sharedHandlersCallbacks.value; + + if (!currentCallback) { + return; + } + + for (let i = 0; i < currentCallback.length; i++) { + const gesture = currentCallback[i]; + + if (event.handlerTag === gesture.handlerTag) { + if (isStateChangeEvent(event)) { + if (event.oldState === State.UNDETERMINED && event.state === State.BEGAN) { + runWorklet(CALLBACK_TYPE.BEGAN, gesture, event); + } else if ((event.oldState === State.BEGAN || event.oldState === State.UNDETERMINED) && event.state === State.ACTIVE) { + runWorklet(CALLBACK_TYPE.START, gesture, event); + lastUpdateEvent.value[gesture.handlerTag] = undefined; + } else if (event.oldState !== event.state && event.state === State.END) { + if (event.oldState === State.ACTIVE) { + runWorklet(CALLBACK_TYPE.END, gesture, event, true); + } + + runWorklet(CALLBACK_TYPE.FINALIZE, gesture, event, true); + } else if ((event.state === State.FAILED || event.state === State.CANCELLED) && event.state !== event.oldState) { + if (event.oldState === State.ACTIVE) { + runWorklet(CALLBACK_TYPE.END, gesture, event, false); + } + + runWorklet(CALLBACK_TYPE.FINALIZE, gesture, event, false); + } + } else if (isTouchEvent(event)) { + if (!stateControllers[i]) { + stateControllers[i] = GestureStateManager.create(event.handlerTag); + } + + if (event.eventType !== EventType.UNDETERMINED) { + runWorklet(touchEventTypeToCallbackType(event.eventType), gesture, event, stateControllers[i]); + } + } else { + runWorklet(CALLBACK_TYPE.UPDATE, gesture, event); + + if (gesture.onChange && gesture.changeEventCalculator) { + var _gesture$changeEventC; + + runWorklet(CALLBACK_TYPE.CHANGE, gesture, (_gesture$changeEventC = gesture.changeEventCalculator) === null || _gesture$changeEventC === void 0 ? void 0 : _gesture$changeEventC.call(gesture, event, lastUpdateEvent.value[gesture.handlerTag])); + lastUpdateEvent.value[gesture.handlerTag] = event; + } + } + } + } + }; // eslint-disable-next-line react-hooks/rules-of-hooks + + + const event = Reanimated.useEvent(callback, ['onGestureHandlerStateChange', 'onGestureHandlerEvent'], true); + preparedGesture.animatedEventHandler = event; + preparedGesture.animatedHandlers = sharedHandlersCallbacks; +} + +export const GestureDetector = props => { + var _gestureConfig$toGest, _gestureConfig$toGest2; + + const gestureConfig = props.gesture; + const gesture = (_gestureConfig$toGest = gestureConfig === null || gestureConfig === void 0 ? void 0 : (_gestureConfig$toGest2 = gestureConfig.toGestureArray) === null || _gestureConfig$toGest2 === void 0 ? void 0 : _gestureConfig$toGest2.call(gestureConfig)) !== null && _gestureConfig$toGest !== void 0 ? _gestureConfig$toGest : []; + const useAnimated = gesture.find(gesture => gesture.handlers.isWorklet.reduce((prev, current) => prev || current)) != null; + const viewRef = useRef(null); + const firstRenderRef = useRef(true); + const preparedGesture = React.useRef({ + config: gesture, + animatedEventHandler: null, + animatedHandlers: null, + firstExecution: true, + useAnimated: useAnimated + }).current; + + if (useAnimated !== preparedGesture.useAnimated) { + throw new Error('You cannot change whether you are using gesture or animatedGesture while the app is running'); + } + + if (preparedGesture.firstExecution) { + var _gestureConfig$initia; + + gestureConfig === null || gestureConfig === void 0 ? void 0 : (_gestureConfig$initia = gestureConfig.initialize) === null || _gestureConfig$initia === void 0 ? void 0 : _gestureConfig$initia.call(gestureConfig); + } + + if (useAnimated) { + // Whether animatedGesture or gesture is used shouldn't change + // during while an app is running + // eslint-disable-next-line react-hooks/rules-of-hooks + useAnimatedGesture(preparedGesture); + } + + useEffect(() => { + firstRenderRef.current = true; + const viewTag = findNodeHandle(viewRef.current); + attachHandlers({ + preparedGesture, + gestureConfig, + gesture, + viewTag, + useAnimated + }); + return () => { + dropHandlers(preparedGesture); + }; + }, []); + useEffect(() => { + if (!firstRenderRef.current) { + const viewTag = findNodeHandle(viewRef.current); + + if (needsToReattach(preparedGesture, gesture)) { + dropHandlers(preparedGesture); + attachHandlers({ + preparedGesture, + gestureConfig, + gesture, + viewTag, + useAnimated + }); + } else { + updateHandlers(preparedGesture, gestureConfig, gesture); + } + } else { + firstRenderRef.current = false; + } + }, [props]); + + if (useAnimated) { + return /*#__PURE__*/React.createElement(AnimatedWrap, { + ref: viewRef, + onGestureHandlerEvent: preparedGesture.animatedEventHandler + }, props.children); + } else { + return /*#__PURE__*/React.createElement(Wrap, { + ref: viewRef + }, props.children); + } +}; + +class Wrap extends React.Component { + render() { + // I don't think that fighting with types over such a simple function is worth it + // The only thing it does is add 'collapsable: false' to the child component + // to make sure it is in the native view hierarchy so the detector can find + // correct viewTag to attach to. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const child = React.Children.only(this.props.children); + return /*#__PURE__*/React.cloneElement(child, { + collapsable: false + }, // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + child.props.children); + } + +} + +const AnimatedWrap = (_Reanimated$default$c = Reanimated === null || Reanimated === void 0 ? void 0 : (_Reanimated$default = Reanimated.default) === null || _Reanimated$default === void 0 ? void 0 : _Reanimated$default.createAnimatedComponent(Wrap)) !== null && _Reanimated$default$c !== void 0 ? _Reanimated$default$c : Wrap; +//# sourceMappingURL=GestureDetector.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/GestureDetector.js.map b/lib/module/handlers/gestures/GestureDetector.js.map new file mode 100644 index 0000000000..a19ba9bd04 --- /dev/null +++ b/lib/module/handlers/gestures/GestureDetector.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureDetector.tsx"],"names":["React","useEffect","useRef","BaseGesture","CALLBACK_TYPE","Reanimated","registerHandler","unregisterHandler","RNGestureHandlerModule","baseGestureHandlerWithMonitorProps","filterConfig","findNodeHandle","GestureStateManager","flingGestureHandlerProps","forceTouchGestureHandlerProps","longPressGestureHandlerProps","panGestureHandlerProps","panGestureHandlerCustomNativeProps","tapGestureHandlerProps","State","EventType","ALLOWED_PROPS","convertToHandlerTag","ref","handlerTag","current","extractValidHandlerTags","interactionGroup","map","filter","tag","dropHandlers","preparedGesture","handler","config","dropGestureHandler","attachHandlers","gestureConfig","gesture","viewTag","useAnimated","firstExecution","initialize","setImmediate","prepare","createGestureHandler","handlerName","requireToFail","simultaneousWith","updateGestureHandler","simultaneousHandlers","waitFor","attachGestureHandler","animatedHandlers","value","g","handlers","updateHandlers","i","length","needsToReattach","useAnimatedGesture","isStateChangeEvent","event","oldState","isTouchEvent","eventType","getHandler","type","BEGAN","onBegin","START","onStart","UPDATE","onUpdate","CHANGE","onChange","END","onEnd","FINALIZE","onFinalize","TOUCHES_DOWN","onTouchesDown","TOUCHES_MOVE","onTouchesMove","TOUCHES_UP","onTouchesUp","TOUCHES_CANCELLED","onTouchesCancelled","touchEventTypeToCallbackType","UNDEFINED","runWorklet","args","isWorklet","console","warn","sharedHandlersCallbacks","useSharedValue","lastUpdateEvent","stateControllers","callback","currentCallback","UNDETERMINED","state","ACTIVE","undefined","FAILED","CANCELLED","create","changeEventCalculator","useEvent","animatedEventHandler","GestureDetector","props","toGestureArray","find","reduce","prev","viewRef","firstRenderRef","Error","children","Wrap","Component","render","child","Children","only","cloneElement","collapsable","AnimatedWrap","default","createAnimatedComponent"],"mappings":";;AAAA,OAAOA,KAAP,IAAgBC,SAAhB,EAA2BC,MAA3B,QAAyC,OAAzC;AACA,SAGEC,WAHF,EAKEC,aALF,QAMO,WANP;AAOA,SAASC,UAAT,QAAwC,qBAAxC;AACA,SAASC,eAAT,EAA0BC,iBAA1B,QAAmD,qBAAnD;AACA,OAAOC,sBAAP,MAAmC,8BAAnC;AACA,SACEC,kCADF,EAEEC,YAFF,EAGEC,cAHF,QAOO,yBAPP;AAQA,SACEC,mBADF,QAGO,uBAHP;AAIA,SAASC,wBAAT,QAAyC,wBAAzC;AACA,SAASC,6BAAT,QAA8C,6BAA9C;AACA,SAASC,4BAAT,QAA6C,4BAA7C;AACA,SACEC,sBADF,EAEEC,kCAFF,QAGO,sBAHP;AAIA,SAASC,sBAAT,QAAuC,sBAAvC;AACA,SAASC,KAAT,QAAsB,aAAt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C+E;AAFzC,OAGGE,KAAK,CAACQ,QAHT,CADF;AAOD,GARD,MAQO;AACL,wBAAO,oBAAC,IAAD;AAAM,MAAA,GAAG,EAAEH;AAAX,OAAqBL,KAAK,CAACQ,QAA3B,CAAP;AACD;AACF,CArFM;;AAuFP,MAAMC,IAAN,SAAmB1H,KAAK,CAAC2H,SAAzB,CAAwE;AACtEC,EAAAA,MAAM,GAAG;AACP;AACA;AACA;AACA;AACA;AACA,UAAMC,KAAU,GAAG7H,KAAK,CAAC8H,QAAN,CAAeC,IAAf,CAAoB,KAAKd,KAAL,CAAWQ,QAA/B,CAAnB;AAEA,wBAAOzH,KAAK,CAACgI,YAAN,CACLH,KADK,EAEL;AAAEI,MAAAA,WAAW,EAAE;AAAf,KAFK,EAGL;AACAJ,IAAAA,KAAK,CAACZ,KAAN,CAAYQ,QAJP,CAAP;AAMD;;AAfqE;;AAkBxE,MAAMS,YAAY,4BAAG7H,UAAH,aAAGA,UAAH,8CAAGA,UAAU,CAAE8H,OAAf,wDAAG,oBAAqBC,uBAArB,CAA6CV,IAA7C,CAAH,yEAAyDA,IAA3E","sourcesContent":["import React, { useEffect, useRef } from 'react';\nimport {\n GestureType,\n HandlerCallbacks,\n BaseGesture,\n GestureRef,\n CALLBACK_TYPE,\n} from './gesture';\nimport { Reanimated, SharedValue } from './reanimatedWrapper';\nimport { registerHandler, unregisterHandler } from '../handlersRegistry';\nimport RNGestureHandlerModule from '../../RNGestureHandlerModule';\nimport {\n baseGestureHandlerWithMonitorProps,\n filterConfig,\n findNodeHandle,\n GestureTouchEvent,\n GestureUpdateEvent,\n GestureStateChangeEvent,\n} from '../gestureHandlerCommon';\nimport {\n GestureStateManager,\n GestureStateManagerType,\n} from './gestureStateManager';\nimport { flingGestureHandlerProps } from '../FlingGestureHandler';\nimport { forceTouchGestureHandlerProps } from '../ForceTouchGestureHandler';\nimport { longPressGestureHandlerProps } from '../LongPressGestureHandler';\nimport {\n panGestureHandlerProps,\n panGestureHandlerCustomNativeProps,\n} from '../PanGestureHandler';\nimport { tapGestureHandlerProps } from '../TapGestureHandler';\nimport { State } from '../../State';\nimport { EventType } from '../../EventType';\nimport { ComposedGesture } from './gestureComposition';\n\nconst ALLOWED_PROPS = [\n ...baseGestureHandlerWithMonitorProps,\n ...tapGestureHandlerProps,\n ...panGestureHandlerProps,\n ...panGestureHandlerCustomNativeProps,\n ...longPressGestureHandlerProps,\n ...forceTouchGestureHandlerProps,\n ...flingGestureHandlerProps,\n];\n\nexport type GestureConfigReference = {\n config: GestureType[];\n animatedEventHandler: unknown;\n animatedHandlers: SharedValue<\n HandlerCallbacks>[] | null\n > | null;\n firstExecution: boolean;\n useAnimated: boolean;\n};\n\nfunction convertToHandlerTag(ref: GestureRef): number {\n if (typeof ref === 'number') {\n return ref;\n } else if (ref instanceof BaseGesture) {\n return ref.handlerTag;\n } else {\n // @ts-ignore in this case it should be a ref either to gesture object or\n // a gesture handler component, in both cases handlerTag property exists\n return ref.current?.handlerTag ?? -1;\n }\n}\n\nfunction extractValidHandlerTags(interactionGroup: GestureRef[] | undefined) {\n return (\n interactionGroup?.map(convertToHandlerTag)?.filter((tag) => tag > 0) ?? []\n );\n}\n\nfunction dropHandlers(preparedGesture: GestureConfigReference) {\n for (const handler of preparedGesture.config) {\n RNGestureHandlerModule.dropGestureHandler(handler.handlerTag);\n\n unregisterHandler(handler.handlerTag);\n }\n}\n\ninterface AttachHandlersConfig {\n preparedGesture: GestureConfigReference;\n gestureConfig: ComposedGesture | GestureType | undefined;\n gesture: GestureType[];\n viewTag: number;\n useAnimated: boolean;\n}\n\nfunction attachHandlers({\n preparedGesture,\n gestureConfig,\n gesture,\n viewTag,\n useAnimated,\n}: AttachHandlersConfig) {\n if (!preparedGesture.firstExecution) {\n gestureConfig?.initialize();\n } else {\n preparedGesture.firstExecution = false;\n }\n\n // use setImmediate to extract handlerTags, because all refs should be initialized\n // when it's ran\n setImmediate(() => {\n gestureConfig?.prepare();\n });\n\n for (const handler of gesture) {\n RNGestureHandlerModule.createGestureHandler(\n handler.handlerName,\n handler.handlerTag,\n filterConfig(handler.config, ALLOWED_PROPS)\n );\n\n registerHandler(handler.handlerTag, handler);\n\n // use setImmediate to extract handlerTags, because all refs should be initialized\n // when it's ran\n setImmediate(() => {\n let requireToFail: number[] = [];\n if (handler.config.requireToFail) {\n requireToFail = extractValidHandlerTags(handler.config.requireToFail);\n }\n\n let simultaneousWith: number[] = [];\n if (handler.config.simultaneousWith) {\n simultaneousWith = extractValidHandlerTags(\n handler.config.simultaneousWith\n );\n }\n\n RNGestureHandlerModule.updateGestureHandler(\n handler.handlerTag,\n filterConfig(handler.config, ALLOWED_PROPS, {\n simultaneousHandlers: simultaneousWith,\n waitFor: requireToFail,\n })\n );\n });\n }\n preparedGesture.config = gesture;\n\n for (const gesture of preparedGesture.config) {\n RNGestureHandlerModule.attachGestureHandler(\n gesture.handlerTag,\n viewTag,\n !useAnimated // send direct events when using animatedGesture, device events otherwise\n );\n }\n\n if (preparedGesture.animatedHandlers) {\n preparedGesture.animatedHandlers.value = (gesture.map(\n (g) => g.handlers\n ) as unknown) as HandlerCallbacks>[];\n }\n}\n\nfunction updateHandlers(\n preparedGesture: GestureConfigReference,\n gestureConfig: ComposedGesture | GestureType | undefined,\n gesture: GestureType[]\n) {\n gestureConfig?.prepare();\n\n for (let i = 0; i < gesture.length; i++) {\n const handler = preparedGesture.config[i];\n\n gesture[i].handlerTag = handler.handlerTag;\n gesture[i].handlers.handlerTag = handler.handlerTag;\n }\n\n // use setImmediate to extract handlerTags, because when it's ran, all refs should be updated\n // and handlerTags in BaseGesture references should be updated in the loop above (we need to wait\n // in case of external relations)\n setImmediate(() => {\n for (let i = 0; i < gesture.length; i++) {\n const handler = preparedGesture.config[i];\n\n handler.config = gesture[i].config;\n handler.handlers = gesture[i].handlers;\n handler.handlers.handlerTag = handler.handlerTag;\n\n const requireToFail = extractValidHandlerTags(\n handler.config.requireToFail\n );\n\n const simultaneousWith = extractValidHandlerTags(\n handler.config.simultaneousWith\n );\n\n RNGestureHandlerModule.updateGestureHandler(\n handler.handlerTag,\n filterConfig(handler.config, ALLOWED_PROPS, {\n simultaneousHandlers: simultaneousWith,\n waitFor: requireToFail,\n })\n );\n\n registerHandler(handler.handlerTag, handler);\n }\n\n if (preparedGesture.animatedHandlers) {\n preparedGesture.animatedHandlers.value = (preparedGesture.config.map(\n (g) => g.handlers\n ) as unknown) as HandlerCallbacks>[];\n }\n });\n}\n\nfunction needsToReattach(\n preparedGesture: GestureConfigReference,\n gesture: GestureType[]\n) {\n if (gesture.length !== preparedGesture.config.length) {\n return true;\n }\n for (let i = 0; i < gesture.length; i++) {\n if (gesture[i].handlerName !== preparedGesture.config[i].handlerName) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction useAnimatedGesture(preparedGesture: GestureConfigReference) {\n if (!Reanimated) {\n return;\n }\n\n function isStateChangeEvent(\n event: GestureUpdateEvent | GestureStateChangeEvent | GestureTouchEvent\n ): event is GestureStateChangeEvent {\n 'worklet';\n // @ts-ignore Yes, the oldState prop is missing on GestureTouchEvent, that's the point\n return event.oldState != null;\n }\n\n function isTouchEvent(\n event: GestureUpdateEvent | GestureStateChangeEvent | GestureTouchEvent\n ): event is GestureTouchEvent {\n 'worklet';\n return event.eventType != null;\n }\n\n function getHandler(\n type: CALLBACK_TYPE,\n gesture: HandlerCallbacks>\n ) {\n 'worklet';\n switch (type) {\n case CALLBACK_TYPE.BEGAN:\n return gesture.onBegin;\n case CALLBACK_TYPE.START:\n return gesture.onStart;\n case CALLBACK_TYPE.UPDATE:\n return gesture.onUpdate;\n case CALLBACK_TYPE.CHANGE:\n return gesture.onChange;\n case CALLBACK_TYPE.END:\n return gesture.onEnd;\n case CALLBACK_TYPE.FINALIZE:\n return gesture.onFinalize;\n case CALLBACK_TYPE.TOUCHES_DOWN:\n return gesture.onTouchesDown;\n case CALLBACK_TYPE.TOUCHES_MOVE:\n return gesture.onTouchesMove;\n case CALLBACK_TYPE.TOUCHES_UP:\n return gesture.onTouchesUp;\n case CALLBACK_TYPE.TOUCHES_CANCELLED:\n return gesture.onTouchesCancelled;\n }\n }\n\n function touchEventTypeToCallbackType(eventType: EventType): CALLBACK_TYPE {\n 'worklet';\n switch (eventType) {\n case EventType.TOUCHES_DOWN:\n return CALLBACK_TYPE.TOUCHES_DOWN;\n case EventType.TOUCHES_MOVE:\n return CALLBACK_TYPE.TOUCHES_MOVE;\n case EventType.TOUCHES_UP:\n return CALLBACK_TYPE.TOUCHES_UP;\n case EventType.TOUCHES_CANCELLED:\n return CALLBACK_TYPE.TOUCHES_CANCELLED;\n }\n return CALLBACK_TYPE.UNDEFINED;\n }\n\n function runWorklet(\n type: CALLBACK_TYPE,\n gesture: HandlerCallbacks>,\n event: GestureStateChangeEvent | GestureUpdateEvent | GestureTouchEvent,\n ...args: any[]\n ) {\n 'worklet';\n const handler = getHandler(type, gesture);\n if (gesture.isWorklet[type]) {\n // @ts-ignore Logic below makes sure the correct event is send to the\n // correct handler.\n handler?.(event, ...args);\n } else if (handler) {\n console.warn('Animated gesture callback must be a worklet');\n }\n }\n\n // Hooks are called conditionally, but the condition is whether the\n // react-native-reanimated is installed, which shouldn't change while running\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const sharedHandlersCallbacks = Reanimated.useSharedValue<\n HandlerCallbacks>[] | null\n >(null);\n\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const lastUpdateEvent = Reanimated.useSharedValue<\n (GestureUpdateEvent | undefined)[]\n >([]);\n\n // not every gesture needs a state controller, init them lazily\n const stateControllers: GestureStateManagerType[] = [];\n\n const callback = (\n event: GestureStateChangeEvent | GestureUpdateEvent | GestureTouchEvent\n ) => {\n 'worklet';\n\n const currentCallback = sharedHandlersCallbacks.value;\n if (!currentCallback) {\n return;\n }\n\n for (let i = 0; i < currentCallback.length; i++) {\n const gesture = currentCallback[i];\n\n if (event.handlerTag === gesture.handlerTag) {\n if (isStateChangeEvent(event)) {\n if (\n event.oldState === State.UNDETERMINED &&\n event.state === State.BEGAN\n ) {\n runWorklet(CALLBACK_TYPE.BEGAN, gesture, event);\n } else if (\n (event.oldState === State.BEGAN ||\n event.oldState === State.UNDETERMINED) &&\n event.state === State.ACTIVE\n ) {\n runWorklet(CALLBACK_TYPE.START, gesture, event);\n lastUpdateEvent.value[gesture.handlerTag] = undefined;\n } else if (\n event.oldState !== event.state &&\n event.state === State.END\n ) {\n if (event.oldState === State.ACTIVE) {\n runWorklet(CALLBACK_TYPE.END, gesture, event, true);\n }\n runWorklet(CALLBACK_TYPE.FINALIZE, gesture, event, true);\n } else if (\n (event.state === State.FAILED || event.state === State.CANCELLED) &&\n event.state !== event.oldState\n ) {\n if (event.oldState === State.ACTIVE) {\n runWorklet(CALLBACK_TYPE.END, gesture, event, false);\n }\n runWorklet(CALLBACK_TYPE.FINALIZE, gesture, event, false);\n }\n } else if (isTouchEvent(event)) {\n if (!stateControllers[i]) {\n stateControllers[i] = GestureStateManager.create(event.handlerTag);\n }\n\n if (event.eventType !== EventType.UNDETERMINED) {\n runWorklet(\n touchEventTypeToCallbackType(event.eventType),\n gesture,\n event,\n stateControllers[i]\n );\n }\n } else {\n runWorklet(CALLBACK_TYPE.UPDATE, gesture, event);\n\n if (gesture.onChange && gesture.changeEventCalculator) {\n runWorklet(\n CALLBACK_TYPE.CHANGE,\n gesture,\n gesture.changeEventCalculator?.(\n event,\n lastUpdateEvent.value[gesture.handlerTag]\n )\n );\n\n lastUpdateEvent.value[gesture.handlerTag] = event;\n }\n }\n }\n }\n };\n\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const event = Reanimated.useEvent(\n callback,\n ['onGestureHandlerStateChange', 'onGestureHandlerEvent'],\n true\n );\n\n preparedGesture.animatedEventHandler = event;\n preparedGesture.animatedHandlers = sharedHandlersCallbacks;\n}\n\ninterface GestureDetectorProps {\n gesture?: ComposedGesture | GestureType;\n}\nexport const GestureDetector: React.FunctionComponent = (\n props\n) => {\n const gestureConfig = props.gesture;\n const gesture = gestureConfig?.toGestureArray?.() ?? [];\n const useAnimated =\n gesture.find((gesture) =>\n gesture.handlers.isWorklet.reduce((prev, current) => prev || current)\n ) != null;\n const viewRef = useRef(null);\n const firstRenderRef = useRef(true);\n\n const preparedGesture = React.useRef({\n config: gesture,\n animatedEventHandler: null,\n animatedHandlers: null,\n firstExecution: true,\n useAnimated: useAnimated,\n }).current;\n\n if (useAnimated !== preparedGesture.useAnimated) {\n throw new Error(\n 'You cannot change whether you are using gesture or animatedGesture while the app is running'\n );\n }\n\n if (preparedGesture.firstExecution) {\n gestureConfig?.initialize?.();\n }\n\n if (useAnimated) {\n // Whether animatedGesture or gesture is used shouldn't change\n // during while an app is running\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useAnimatedGesture(preparedGesture);\n }\n\n useEffect(() => {\n firstRenderRef.current = true;\n const viewTag = findNodeHandle(viewRef.current) as number;\n attachHandlers({\n preparedGesture,\n gestureConfig,\n gesture,\n viewTag,\n useAnimated,\n });\n\n return () => {\n dropHandlers(preparedGesture);\n };\n }, []);\n\n useEffect(() => {\n if (!firstRenderRef.current) {\n const viewTag = findNodeHandle(viewRef.current) as number;\n\n if (needsToReattach(preparedGesture, gesture)) {\n dropHandlers(preparedGesture);\n attachHandlers({\n preparedGesture,\n gestureConfig,\n gesture,\n viewTag,\n useAnimated,\n });\n } else {\n updateHandlers(preparedGesture, gestureConfig, gesture);\n }\n } else {\n firstRenderRef.current = false;\n }\n }, [props]);\n\n if (useAnimated) {\n return (\n \n {props.children}\n \n );\n } else {\n return {props.children};\n }\n};\n\nclass Wrap extends React.Component<{ onGestureHandlerEvent?: unknown }> {\n render() {\n // I don't think that fighting with types over such a simple function is worth it\n // The only thing it does is add 'collapsable: false' to the child component\n // to make sure it is in the native view hierarchy so the detector can find\n // correct viewTag to attach to.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const child: any = React.Children.only(this.props.children);\n\n return React.cloneElement(\n child,\n { collapsable: false },\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n child.props.children\n );\n }\n}\n\nconst AnimatedWrap = Reanimated?.default?.createAnimatedComponent(Wrap) ?? Wrap;\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/eventReceiver.js b/lib/module/handlers/gestures/eventReceiver.js new file mode 100644 index 0000000000..f0134506b7 --- /dev/null +++ b/lib/module/handlers/gestures/eventReceiver.js @@ -0,0 +1,120 @@ +import { DeviceEventEmitter } from 'react-native'; +import { State } from '../../State'; +import { EventType } from '../../EventType'; +import { findHandler } from '../handlersRegistry'; +let gestureHandlerEventSubscription = null; +let gestureHandlerStateChangeEventSubscription = null; +const dummyStateManager = { + begin: () => { + console.warn('You have to use react-native-reanimated in order to control the state of the gesture.'); + }, + activate: () => { + console.warn('You have to use react-native-reanimated in order to control the state of the gesture.'); + }, + end: () => { + console.warn('You have to use react-native-reanimated in order to control the state of the gesture.'); + }, + fail: () => { + console.warn('You have to use react-native-reanimated in order to control the state of the gesture.'); + } +}; +const lastUpdateEvent = []; + +function isStateChangeEvent(event) { + // @ts-ignore oldState doesn't exist on GestureTouchEvent and that's the point + return event.oldState != null; +} + +function isTouchEvent(event) { + return event.eventType != null; +} + +function onGestureHandlerEvent(event) { + var _handler$handlers7, _handler$handlers7$on, _handler$handlers8, _handler$handlers8$on, _handler$handlers9, _handler$handlers9$on, _handler$handlers10, _handler$handlers10$o; + + const handler = findHandler(event.handlerTag); + + if (handler) { + if (isStateChangeEvent(event)) { + if (event.oldState === State.UNDETERMINED && event.state === State.BEGAN) { + var _handler$handlers$onB, _handler$handlers; + + (_handler$handlers$onB = (_handler$handlers = handler.handlers).onBegin) === null || _handler$handlers$onB === void 0 ? void 0 : _handler$handlers$onB.call(_handler$handlers, event); + } else if ((event.oldState === State.BEGAN || event.oldState === State.UNDETERMINED) && event.state === State.ACTIVE) { + var _handler$handlers$onS, _handler$handlers2; + + (_handler$handlers$onS = (_handler$handlers2 = handler.handlers).onStart) === null || _handler$handlers$onS === void 0 ? void 0 : _handler$handlers$onS.call(_handler$handlers2, event); + lastUpdateEvent[handler.handlers.handlerTag] = event; + } else if (event.oldState !== event.state && event.state === State.END) { + var _handler$handlers$onF, _handler$handlers4; + + if (event.oldState === State.ACTIVE) { + var _handler$handlers$onE, _handler$handlers3; + + (_handler$handlers$onE = (_handler$handlers3 = handler.handlers).onEnd) === null || _handler$handlers$onE === void 0 ? void 0 : _handler$handlers$onE.call(_handler$handlers3, event, true); + } + + (_handler$handlers$onF = (_handler$handlers4 = handler.handlers).onFinalize) === null || _handler$handlers$onF === void 0 ? void 0 : _handler$handlers$onF.call(_handler$handlers4, event, true); + lastUpdateEvent[handler.handlers.handlerTag] = undefined; + } else if ((event.state === State.FAILED || event.state === State.CANCELLED) && event.oldState !== event.state) { + var _handler$handlers$onF2, _handler$handlers6; + + if (event.oldState === State.ACTIVE) { + var _handler$handlers$onE2, _handler$handlers5; + + (_handler$handlers$onE2 = (_handler$handlers5 = handler.handlers).onEnd) === null || _handler$handlers$onE2 === void 0 ? void 0 : _handler$handlers$onE2.call(_handler$handlers5, event, false); + } + + (_handler$handlers$onF2 = (_handler$handlers6 = handler.handlers).onFinalize) === null || _handler$handlers$onF2 === void 0 ? void 0 : _handler$handlers$onF2.call(_handler$handlers6, event, false); + lastUpdateEvent[handler.handlers.handlerTag] = undefined; + } + } else if (isTouchEvent(event)) { + switch (event.eventType) { + case EventType.TOUCHES_DOWN: + (_handler$handlers7 = handler.handlers) === null || _handler$handlers7 === void 0 ? void 0 : (_handler$handlers7$on = _handler$handlers7.onTouchesDown) === null || _handler$handlers7$on === void 0 ? void 0 : _handler$handlers7$on.call(_handler$handlers7, event, dummyStateManager); + break; + + case EventType.TOUCHES_MOVE: + (_handler$handlers8 = handler.handlers) === null || _handler$handlers8 === void 0 ? void 0 : (_handler$handlers8$on = _handler$handlers8.onTouchesMove) === null || _handler$handlers8$on === void 0 ? void 0 : _handler$handlers8$on.call(_handler$handlers8, event, dummyStateManager); + break; + + case EventType.TOUCHES_UP: + (_handler$handlers9 = handler.handlers) === null || _handler$handlers9 === void 0 ? void 0 : (_handler$handlers9$on = _handler$handlers9.onTouchesUp) === null || _handler$handlers9$on === void 0 ? void 0 : _handler$handlers9$on.call(_handler$handlers9, event, dummyStateManager); + break; + + case EventType.TOUCHES_CANCELLED: + (_handler$handlers10 = handler.handlers) === null || _handler$handlers10 === void 0 ? void 0 : (_handler$handlers10$o = _handler$handlers10.onTouchesCancelled) === null || _handler$handlers10$o === void 0 ? void 0 : _handler$handlers10$o.call(_handler$handlers10, event, dummyStateManager); + break; + } + } else { + var _handler$handlers$onU, _handler$handlers11; + + (_handler$handlers$onU = (_handler$handlers11 = handler.handlers).onUpdate) === null || _handler$handlers$onU === void 0 ? void 0 : _handler$handlers$onU.call(_handler$handlers11, event); + + if (handler.handlers.onChange && handler.handlers.changeEventCalculator) { + var _handler$handlers$onC, _handler$handlers12, _handler$handlers$cha, _handler$handlers13; + + (_handler$handlers$onC = (_handler$handlers12 = handler.handlers).onChange) === null || _handler$handlers$onC === void 0 ? void 0 : _handler$handlers$onC.call(_handler$handlers12, (_handler$handlers$cha = (_handler$handlers13 = handler.handlers).changeEventCalculator) === null || _handler$handlers$cha === void 0 ? void 0 : _handler$handlers$cha.call(_handler$handlers13, event, lastUpdateEvent[handler.handlers.handlerTag])); + lastUpdateEvent[handler.handlers.handlerTag] = event; + } + } + } +} + +export function startListening() { + stopListening(); + gestureHandlerEventSubscription = DeviceEventEmitter.addListener('onGestureHandlerEvent', onGestureHandlerEvent); + gestureHandlerStateChangeEventSubscription = DeviceEventEmitter.addListener('onGestureHandlerStateChange', onGestureHandlerEvent); +} +export function stopListening() { + if (gestureHandlerEventSubscription) { + DeviceEventEmitter.removeSubscription(gestureHandlerEventSubscription); + gestureHandlerEventSubscription = null; + } + + if (gestureHandlerStateChangeEventSubscription) { + DeviceEventEmitter.removeSubscription(gestureHandlerStateChangeEventSubscription); + gestureHandlerStateChangeEventSubscription = null; + } +} +//# sourceMappingURL=eventReceiver.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/eventReceiver.js.map b/lib/module/handlers/gestures/eventReceiver.js.map new file mode 100644 index 0000000000..646cb5333e --- /dev/null +++ b/lib/module/handlers/gestures/eventReceiver.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["eventReceiver.ts"],"names":["DeviceEventEmitter","State","EventType","findHandler","gestureHandlerEventSubscription","gestureHandlerStateChangeEventSubscription","dummyStateManager","begin","console","warn","activate","end","fail","lastUpdateEvent","isStateChangeEvent","event","oldState","isTouchEvent","eventType","onGestureHandlerEvent","handler","handlerTag","UNDETERMINED","state","BEGAN","handlers","onBegin","ACTIVE","onStart","END","onEnd","onFinalize","undefined","FAILED","CANCELLED","TOUCHES_DOWN","onTouchesDown","TOUCHES_MOVE","onTouchesMove","TOUCHES_UP","onTouchesUp","TOUCHES_CANCELLED","onTouchesCancelled","onUpdate","onChange","changeEventCalculator","startListening","stopListening","addListener","removeSubscription"],"mappings":"AAAA,SAASA,kBAAT,QAAwD,cAAxD;AACA,SAASC,KAAT,QAAsB,aAAtB;AACA,SAASC,SAAT,QAA0B,iBAA1B;AAOA,SAASC,WAAT,QAA4B,qBAA5B;AAGA,IAAIC,+BAA2D,GAAG,IAAlE;AACA,IAAIC,0CAAsE,GAAG,IAA7E;AAEA,MAAMC,iBAA0C,GAAG;AACjDC,EAAAA,KAAK,EAAE,MAAM;AACXC,IAAAA,OAAO,CAACC,IAAR,CACE,uFADF;AAGD,GALgD;AAMjDC,EAAAA,QAAQ,EAAE,MAAM;AACdF,IAAAA,OAAO,CAACC,IAAR,CACE,uFADF;AAGD,GAVgD;AAWjDE,EAAAA,GAAG,EAAE,MAAM;AACTH,IAAAA,OAAO,CAACC,IAAR,CACE,uFADF;AAGD,GAfgD;AAgBjDG,EAAAA,IAAI,EAAE,MAAM;AACVJ,IAAAA,OAAO,CAACC,IAAR,CACE,uFADF;AAGD;AApBgD,CAAnD;AAuBA,MAAMI,eAAmD,GAAG,EAA5D;;AAEA,SAASC,kBAAT,CACEC,KADF,EAEoC;AACl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;AACL,sDAAAc,OAAO,CAACK,QAAR,EAAiBkB,QAAjB,0GAA4B5B,KAA5B;;AAEA,UAAIK,OAAO,CAACK,QAAR,CAAiBmB,QAAjB,IAA6BxB,OAAO,CAACK,QAAR,CAAiBoB,qBAAlD,EAAyE;AAAA;;AACvE,wDAAAzB,OAAO,CAACK,QAAR,EAAiBmB,QAAjB,mIACE,uBAAAxB,OAAO,CAACK,QAAR,EAAiBoB,qBADnB,0DACE,gDACE9B,KADF,EAEEF,eAAe,CAACO,OAAO,CAACK,QAAR,CAAiBJ,UAAlB,CAFjB,CADF;AAOAR,QAAAA,eAAe,CAACO,OAAO,CAACK,QAAR,CAAiBJ,UAAlB,CAAf,GAA+CN,KAA/C;AACD;AACF;AACF;AACF;;AAED,OAAO,SAAS+B,cAAT,GAA0B;AAC/BC,EAAAA,aAAa;AAEb3C,EAAAA,+BAA+B,GAAGJ,kBAAkB,CAACgD,WAAnB,CAChC,uBADgC,EAEhC7B,qBAFgC,CAAlC;AAKAd,EAAAA,0CAA0C,GAAGL,kBAAkB,CAACgD,WAAnB,CAC3C,6BAD2C,EAE3C7B,qBAF2C,CAA7C;AAID;AAED,OAAO,SAAS4B,aAAT,GAAyB;AAC9B,MAAI3C,+BAAJ,EAAqC;AACnCJ,IAAAA,kBAAkB,CAACiD,kBAAnB,CAAsC7C,+BAAtC;AAEAA,IAAAA,+BAA+B,GAAG,IAAlC;AACD;;AAED,MAAIC,0CAAJ,EAAgD;AAC9CL,IAAAA,kBAAkB,CAACiD,kBAAnB,CACE5C,0CADF;AAIAA,IAAAA,0CAA0C,GAAG,IAA7C;AACD;AACF","sourcesContent":["import { DeviceEventEmitter, EmitterSubscription } from 'react-native';\nimport { State } from '../../State';\nimport { EventType } from '../../EventType';\nimport {\n GestureTouchEvent,\n GestureUpdateEvent,\n GestureStateChangeEvent,\n} from '../gestureHandlerCommon';\nimport { GestureStateManagerType } from './gestureStateManager';\nimport { findHandler } from '../handlersRegistry';\nimport { BaseGesture } from './gesture';\n\nlet gestureHandlerEventSubscription: EmitterSubscription | null = null;\nlet gestureHandlerStateChangeEventSubscription: EmitterSubscription | null = null;\n\nconst dummyStateManager: GestureStateManagerType = {\n begin: () => {\n console.warn(\n 'You have to use react-native-reanimated in order to control the state of the gesture.'\n );\n },\n activate: () => {\n console.warn(\n 'You have to use react-native-reanimated in order to control the state of the gesture.'\n );\n },\n end: () => {\n console.warn(\n 'You have to use react-native-reanimated in order to control the state of the gesture.'\n );\n },\n fail: () => {\n console.warn(\n 'You have to use react-native-reanimated in order to control the state of the gesture.'\n );\n },\n};\n\nconst lastUpdateEvent: (GestureUpdateEvent | undefined)[] = [];\n\nfunction isStateChangeEvent(\n event: GestureUpdateEvent | GestureStateChangeEvent | GestureTouchEvent\n): event is GestureStateChangeEvent {\n // @ts-ignore oldState doesn't exist on GestureTouchEvent and that's the point\n return event.oldState != null;\n}\n\nfunction isTouchEvent(\n event: GestureUpdateEvent | GestureStateChangeEvent | GestureTouchEvent\n): event is GestureTouchEvent {\n return event.eventType != null;\n}\n\nfunction onGestureHandlerEvent(\n event: GestureUpdateEvent | GestureStateChangeEvent | GestureTouchEvent\n) {\n const handler = findHandler(event.handlerTag) as BaseGesture<\n Record\n >;\n\n if (handler) {\n if (isStateChangeEvent(event)) {\n if (\n event.oldState === State.UNDETERMINED &&\n event.state === State.BEGAN\n ) {\n handler.handlers.onBegin?.(event);\n } else if (\n (event.oldState === State.BEGAN ||\n event.oldState === State.UNDETERMINED) &&\n event.state === State.ACTIVE\n ) {\n handler.handlers.onStart?.(event);\n lastUpdateEvent[handler.handlers.handlerTag] = event;\n } else if (event.oldState !== event.state && event.state === State.END) {\n if (event.oldState === State.ACTIVE) {\n handler.handlers.onEnd?.(event, true);\n }\n handler.handlers.onFinalize?.(event, true);\n lastUpdateEvent[handler.handlers.handlerTag] = undefined;\n } else if (\n (event.state === State.FAILED || event.state === State.CANCELLED) &&\n event.oldState !== event.state\n ) {\n if (event.oldState === State.ACTIVE) {\n handler.handlers.onEnd?.(event, false);\n }\n handler.handlers.onFinalize?.(event, false);\n lastUpdateEvent[handler.handlers.handlerTag] = undefined;\n }\n } else if (isTouchEvent(event)) {\n switch (event.eventType) {\n case EventType.TOUCHES_DOWN:\n handler.handlers?.onTouchesDown?.(event, dummyStateManager);\n break;\n case EventType.TOUCHES_MOVE:\n handler.handlers?.onTouchesMove?.(event, dummyStateManager);\n break;\n case EventType.TOUCHES_UP:\n handler.handlers?.onTouchesUp?.(event, dummyStateManager);\n break;\n case EventType.TOUCHES_CANCELLED:\n handler.handlers?.onTouchesCancelled?.(event, dummyStateManager);\n break;\n }\n } else {\n handler.handlers.onUpdate?.(event);\n\n if (handler.handlers.onChange && handler.handlers.changeEventCalculator) {\n handler.handlers.onChange?.(\n handler.handlers.changeEventCalculator?.(\n event,\n lastUpdateEvent[handler.handlers.handlerTag]\n )\n );\n\n lastUpdateEvent[handler.handlers.handlerTag] = event;\n }\n }\n }\n}\n\nexport function startListening() {\n stopListening();\n\n gestureHandlerEventSubscription = DeviceEventEmitter.addListener(\n 'onGestureHandlerEvent',\n onGestureHandlerEvent\n );\n\n gestureHandlerStateChangeEventSubscription = DeviceEventEmitter.addListener(\n 'onGestureHandlerStateChange',\n onGestureHandlerEvent\n );\n}\n\nexport function stopListening() {\n if (gestureHandlerEventSubscription) {\n DeviceEventEmitter.removeSubscription(gestureHandlerEventSubscription);\n\n gestureHandlerEventSubscription = null;\n }\n\n if (gestureHandlerStateChangeEventSubscription) {\n DeviceEventEmitter.removeSubscription(\n gestureHandlerStateChangeEventSubscription\n );\n\n gestureHandlerStateChangeEventSubscription = null;\n }\n}\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/flingGesture.js b/lib/module/handlers/gestures/flingGesture.js new file mode 100644 index 0000000000..8cb35193d7 --- /dev/null +++ b/lib/module/handlers/gestures/flingGesture.js @@ -0,0 +1,24 @@ +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; } + +import { BaseGesture } from './gesture'; +export class FlingGesture extends BaseGesture { + constructor() { + super(); + + _defineProperty(this, "config", {}); + + this.handlerName = 'FlingGestureHandler'; + } + + numberOfPointers(pointers) { + this.config.numberOfPointers = pointers; + return this; + } + + direction(direction) { + this.config.direction = direction; + return this; + } + +} +//# sourceMappingURL=flingGesture.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/flingGesture.js.map b/lib/module/handlers/gestures/flingGesture.js.map new file mode 100644 index 0000000000..5158bdd1c8 --- /dev/null +++ b/lib/module/handlers/gestures/flingGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["flingGesture.ts"],"names":["BaseGesture","FlingGesture","constructor","handlerName","numberOfPointers","pointers","config","direction"],"mappings":";;AAAA,SAASA,WAAT,QAA+C,WAA/C;AAMA,OAAO,MAAMC,YAAN,SAA2BD,WAA3B,CAAwE;AAG7EE,EAAAA,WAAW,GAAG;AACZ;;AADY,oCAF0C,EAE1C;;AAGZ,SAAKC,WAAL,GAAmB,qBAAnB;AACD;;AAEDC,EAAAA,gBAAgB,CAACC,QAAD,EAAmB;AACjC,SAAKC,MAAL,CAAYF,gBAAZ,GAA+BC,QAA/B;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,SAAS,CAACA,SAAD,EAAoB;AAC3B,SAAKD,MAAL,CAAYC,SAAZ,GAAwBA,SAAxB;AACA,WAAO,IAAP;AACD;;AAjB4E","sourcesContent":["import { BaseGesture, BaseGestureConfig } from './gesture';\nimport {\n FlingGestureConfig,\n FlingGestureHandlerEventPayload,\n} from '../FlingGestureHandler';\n\nexport class FlingGesture extends BaseGesture {\n public config: BaseGestureConfig & FlingGestureConfig = {};\n\n constructor() {\n super();\n\n this.handlerName = 'FlingGestureHandler';\n }\n\n numberOfPointers(pointers: number) {\n this.config.numberOfPointers = pointers;\n return this;\n }\n\n direction(direction: number) {\n this.config.direction = direction;\n return this;\n }\n}\n\nexport type FlingGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/forceTouchGesture.js b/lib/module/handlers/gestures/forceTouchGesture.js new file mode 100644 index 0000000000..3db33fd377 --- /dev/null +++ b/lib/module/handlers/gestures/forceTouchGesture.js @@ -0,0 +1,56 @@ +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; } + +import { ContinousBaseGesture } from './gesture'; + +function changeEventCalculator(current, previous) { + 'worklet'; + + let changePayload; + + if (previous === undefined) { + changePayload = { + forceChange: current.force + }; + } else { + changePayload = { + forceChange: current.force - previous.force + }; + } + + return { ...current, + ...changePayload + }; +} + +export class ForceTouchGesture extends ContinousBaseGesture { + constructor() { + super(); + + _defineProperty(this, "config", {}); + + this.handlerName = 'ForceTouchGestureHandler'; + } + + minForce(force) { + this.config.minForce = force; + return this; + } + + maxForce(force) { + this.config.maxForce = force; + return this; + } + + feedbackOnActivation(value) { + this.config.feedbackOnActivation = value; + return this; + } + + onChange(callback) { + // @ts-ignore TS being overprotective, ForceTouchGestureHandlerEventPayload is Record + this.handlers.changeEventCalculator = changeEventCalculator; + return super.onChange(callback); + } + +} +//# sourceMappingURL=forceTouchGesture.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/forceTouchGesture.js.map b/lib/module/handlers/gestures/forceTouchGesture.js.map new file mode 100644 index 0000000000..69d7431f6a --- /dev/null +++ b/lib/module/handlers/gestures/forceTouchGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["forceTouchGesture.ts"],"names":["ContinousBaseGesture","changeEventCalculator","current","previous","changePayload","undefined","forceChange","force","ForceTouchGesture","constructor","handlerName","minForce","config","maxForce","feedbackOnActivation","value","onChange","callback","handlers"],"mappings":";;AAAA,SAA4BA,oBAA5B,QAAwD,WAAxD;;AAWA,SAASC,qBAAT,CACEC,OADF,EAEEC,QAFF,EAGE;AACA;;AACA,MAAIC,aAAJ;;AACA,MAAID,QAAQ,KAAKE,SAAjB,EAA4B;AAC1BD,IAAAA,aAAa,GAAG;AACdE,MAAAA,WAAW,EAAEJ,OAAO,CAACK;AADP,KAAhB;AAGD,GAJD,MAIO;AACLH,IAAAA,aAAa,GAAG;AACdE,MAAAA,WAAW,EAAEJ,OAAO,CAACK,KAAR,GAAgBJ,QAAQ,CAACI;AADxB,KAAhB;AAGD;;AAED,SAAO,EAAE,GAAGL,OAAL;AAAc,OAAGE;AAAjB,GAAP;AACD;;AAED,OAAO,MAAMI,iBAAN,SAAgCR,oBAAhC,CAGL;AAGAS,EAAAA,WAAW,GAAG;AACZ;;AADY,oCAF+C,EAE/C;;AAGZ,SAAKC,WAAL,GAAmB,0BAAnB;AACD;;AAEDC,EAAAA,QAAQ,CAACJ,KAAD,EAAgB;AACtB,SAAKK,MAAL,CAAYD,QAAZ,GAAuBJ,KAAvB;AACA,WAAO,IAAP;AACD;;AAEDM,EAAAA,QAAQ,CAACN,KAAD,EAAgB;AACtB,SAAKK,MAAL,CAAYC,QAAZ,GAAuBN,KAAvB;AACA,WAAO,IAAP;AACD;;AAEDO,EAAAA,oBAAoB,CAACC,KAAD,EAAiB;AACnC,SAAKH,MAAL,CAAYE,oBAAZ,GAAmCC,KAAnC;AACA,WAAO,IAAP;AACD;;AAEDC,EAAAA,QAAQ,CACNC,QADM,EASN;AACA;AACA,SAAKC,QAAL,CAAcjB,qBAAd,GAAsCA,qBAAtC;AACA,WAAO,MAAMe,QAAN,CAAeC,QAAf,CAAP;AACD;;AArCD","sourcesContent":["import { BaseGestureConfig, ContinousBaseGesture } from './gesture';\nimport {\n ForceTouchGestureConfig,\n ForceTouchGestureHandlerEventPayload,\n} from '../ForceTouchGestureHandler';\nimport { GestureUpdateEvent } from '../gestureHandlerCommon';\n\ntype ForceTouchGestureChangeEventPayload = {\n forceChange: number;\n};\n\nfunction changeEventCalculator(\n current: GestureUpdateEvent,\n previous?: GestureUpdateEvent\n) {\n 'worklet';\n let changePayload: ForceTouchGestureChangeEventPayload;\n if (previous === undefined) {\n changePayload = {\n forceChange: current.force,\n };\n } else {\n changePayload = {\n forceChange: current.force - previous.force,\n };\n }\n\n return { ...current, ...changePayload };\n}\n\nexport class ForceTouchGesture extends ContinousBaseGesture<\n ForceTouchGestureHandlerEventPayload,\n ForceTouchGestureChangeEventPayload\n> {\n public config: BaseGestureConfig & ForceTouchGestureConfig = {};\n\n constructor() {\n super();\n\n this.handlerName = 'ForceTouchGestureHandler';\n }\n\n minForce(force: number) {\n this.config.minForce = force;\n return this;\n }\n\n maxForce(force: number) {\n this.config.maxForce = force;\n return this;\n }\n\n feedbackOnActivation(value: boolean) {\n this.config.feedbackOnActivation = value;\n return this;\n }\n\n onChange(\n callback: (\n event: GestureUpdateEvent<\n GestureUpdateEvent<\n ForceTouchGestureHandlerEventPayload &\n ForceTouchGestureChangeEventPayload\n >\n >\n ) => void\n ) {\n // @ts-ignore TS being overprotective, ForceTouchGestureHandlerEventPayload is Record\n this.handlers.changeEventCalculator = changeEventCalculator;\n return super.onChange(callback);\n }\n}\n\nexport type ForceTouchGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/gesture.js b/lib/module/handlers/gestures/gesture.js new file mode 100644 index 0000000000..21f760bcea --- /dev/null +++ b/lib/module/handlers/gestures/gesture.js @@ -0,0 +1,175 @@ +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; } + +import { getNextHandlerTag } from '../handlersRegistry'; +export const CALLBACK_TYPE = { + UNDEFINED: 0, + BEGAN: 1, + START: 2, + UPDATE: 3, + CHANGE: 4, + END: 5, + FINALIZE: 6, + TOUCHES_DOWN: 7, + TOUCHES_MOVE: 8, + TOUCHES_UP: 9, + TOUCHES_CANCELLED: 10 +}; // Allow using CALLBACK_TYPE as object and type +// eslint-disable-next-line @typescript-eslint/no-redeclare + +export class Gesture {} +export class BaseGesture extends Gesture { + constructor(...args) { + super(...args); + + _defineProperty(this, "handlerTag", -1); + + _defineProperty(this, "handlerName", ''); + + _defineProperty(this, "config", {}); + + _defineProperty(this, "handlers", { + handlerTag: -1, + isWorklet: [false, false, false, false] + }); + } + + addDependency(key, gesture) { + const value = this.config[key]; + this.config[key] = value ? Array().concat(value, gesture) : [gesture]; + } + + withRef(ref) { + this.config.ref = ref; + return this; + } // eslint-disable-next-line @typescript-eslint/ban-types + + + isWorklet(callback) { + //@ts-ignore if callback is a worklet, the property will be available, if not then the check will return false + return callback.__workletHash !== undefined; + } + + onBegin(callback) { + this.handlers.onBegin = callback; + this.handlers.isWorklet[CALLBACK_TYPE.BEGAN] = this.isWorklet(callback); + return this; + } + + onStart(callback) { + this.handlers.onStart = callback; + this.handlers.isWorklet[CALLBACK_TYPE.START] = this.isWorklet(callback); + return this; + } + + onEnd(callback) { + this.handlers.onEnd = callback; //@ts-ignore if callback is a worklet, the property will be available, if not then the check will return false + + this.handlers.isWorklet[CALLBACK_TYPE.END] = this.isWorklet(callback); + return this; + } + + onFinalize(callback) { + this.handlers.onFinalize = callback; //@ts-ignore if callback is a worklet, the property will be available, if not then the check will return false + + this.handlers.isWorklet[CALLBACK_TYPE.FINALIZE] = this.isWorklet(callback); + return this; + } + + onTouchesDown(callback) { + this.config.needsPointerData = true; + this.handlers.onTouchesDown = callback; + this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_DOWN] = this.isWorklet(callback); + return this; + } + + onTouchesMove(callback) { + this.config.needsPointerData = true; + this.handlers.onTouchesMove = callback; + this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_MOVE] = this.isWorklet(callback); + return this; + } + + onTouchesUp(callback) { + this.config.needsPointerData = true; + this.handlers.onTouchesUp = callback; + this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_UP] = this.isWorklet(callback); + return this; + } + + onTouchesCancelled(callback) { + this.config.needsPointerData = true; + this.handlers.onTouchesCancelled = callback; + this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_CANCELLED] = this.isWorklet(callback); + return this; + } + + enabled(enabled) { + this.config.enabled = enabled; + return this; + } + + shouldCancelWhenOutside(value) { + this.config.shouldCancelWhenOutside = value; + return this; + } + + hitSlop(hitSlop) { + this.config.hitSlop = hitSlop; + return this; + } + + simultaneousWithExternalGesture(...gestures) { + for (const gesture of gestures) { + this.addDependency('simultaneousWith', gesture); + } + + return this; + } + + requireExternalGestureToFail(...gestures) { + for (const gesture of gestures) { + this.addDependency('requireToFail', gesture); + } + + return this; + } + + initialize() { + this.handlerTag = getNextHandlerTag(); + this.handlers = { ...this.handlers, + handlerTag: this.handlerTag + }; + + if (this.config.ref) { + this.config.ref.current = this; + } + } + + toGestureArray() { + return [this]; + } // eslint-disable-next-line @typescript-eslint/no-empty-function + + + prepare() {} + +} +export class ContinousBaseGesture extends BaseGesture { + onUpdate(callback) { + this.handlers.onUpdate = callback; + this.handlers.isWorklet[CALLBACK_TYPE.UPDATE] = this.isWorklet(callback); + return this; + } + + onChange(callback) { + this.handlers.onChange = callback; + this.handlers.isWorklet[CALLBACK_TYPE.CHANGE] = this.isWorklet(callback); + return this; + } + + manualActivation(manualActivation) { + this.config.manualActivation = manualActivation; + return this; + } + +} +//# sourceMappingURL=gesture.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/gesture.js.map b/lib/module/handlers/gestures/gesture.js.map new file mode 100644 index 0000000000..896eac70cd --- /dev/null +++ b/lib/module/handlers/gestures/gesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["gesture.ts"],"names":["getNextHandlerTag","CALLBACK_TYPE","UNDEFINED","BEGAN","START","UPDATE","CHANGE","END","FINALIZE","TOUCHES_DOWN","TOUCHES_MOVE","TOUCHES_UP","TOUCHES_CANCELLED","Gesture","BaseGesture","handlerTag","isWorklet","addDependency","key","gesture","value","config","Array","concat","withRef","ref","callback","__workletHash","undefined","onBegin","handlers","onStart","onEnd","onFinalize","onTouchesDown","needsPointerData","onTouchesMove","onTouchesUp","onTouchesCancelled","enabled","shouldCancelWhenOutside","hitSlop","simultaneousWithExternalGesture","gestures","requireExternalGestureToFail","initialize","current","toGestureArray","prepare","ContinousBaseGesture","onUpdate","onChange","manualActivation"],"mappings":";;AASA,SAASA,iBAAT,QAAkC,qBAAlC;AAkEA,OAAO,MAAMC,aAAa,GAAG;AAC3BC,EAAAA,SAAS,EAAE,CADgB;AAE3BC,EAAAA,KAAK,EAAE,CAFoB;AAG3BC,EAAAA,KAAK,EAAE,CAHoB;AAI3BC,EAAAA,MAAM,EAAE,CAJmB;AAK3BC,EAAAA,MAAM,EAAE,CALmB;AAM3BC,EAAAA,GAAG,EAAE,CANsB;AAO3BC,EAAAA,QAAQ,EAAE,CAPiB;AAQ3BC,EAAAA,YAAY,EAAE,CARa;AAS3BC,EAAAA,YAAY,EAAE,CATa;AAU3BC,EAAAA,UAAU,EAAE,CAVe;AAW3BC,EAAAA,iBAAiB,EAAE;AAXQ,CAAtB,C,CAcP;AACA;;AAGA,OAAO,MAAeC,OAAf,CAAuB;AAoB9B,OAAO,MAAeC,WAAf,SAEGD,OAFH,CAEW;AAAA;AAAA;;AAAA,wCACI,CAAC,CADL;;AAAA,yCAEK,EAFL;;AAAA,oCAGmB,EAHnB;;AAAA,sCAImC;AACjDE,MAAAA,UAAU,EAAE,CAAC,CADoC;AAEjDC,MAAAA,SAAS,EAAE,CAAC,KAAD,EAAQ,KAAR,EAAe,KAAf,EAAsB,KAAtB;AAFsC,KAJnC;AAAA;;AASRC,EAAAA,aAAa,CACnBC,GADmB,EAEnBC,OAFmB,EAGnB;AACA,UAAMC,KAAK,GAAG,KAAKC,MAAL,CAAYH,GAAZ,CAAd;AACA,SAAKG,MAAL,CAAYH,GAAZ,IAAmBE,KAAK,GACpBE,KAAK,GAAeC,MAApB,CAA2BH,KAA3B,EAAkCD,OAAlC,CADoB,GAEpB,CAACA,OAAD,CAFJ;AAGD;;AAEDK,EAAAA,OAAO,CAACC,GAAD,EAAuD;AAC5D,SAAKJ,MAAL,CAAYI,GAAZ,GAAkB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ACA,gBAAD,EAA4B;AAC1C,SAAK/B,MAAL,CAAY+B,gBAAZ,GAA+BA,gBAA/B;AACA,WAAO,IAAP;AACD;;AApBkC","sourcesContent":["import { FlingGestureHandlerEventPayload } from '../FlingGestureHandler';\nimport { ForceTouchGestureHandlerEventPayload } from '../ForceTouchGestureHandler';\nimport {\n HitSlop,\n CommonGestureConfig,\n GestureTouchEvent,\n GestureStateChangeEvent,\n GestureUpdateEvent,\n} from '../gestureHandlerCommon';\nimport { getNextHandlerTag } from '../handlersRegistry';\nimport { GestureStateManagerType } from './gestureStateManager';\nimport { LongPressGestureHandlerEventPayload } from '../LongPressGestureHandler';\nimport { PanGestureHandlerEventPayload } from '../PanGestureHandler';\nimport { PinchGestureHandlerEventPayload } from '../PinchGestureHandler';\nimport { RotationGestureHandlerEventPayload } from '../RotationGestureHandler';\nimport { TapGestureHandlerEventPayload } from '../TapGestureHandler';\nimport { NativeViewGestureHandlerPayload } from '../NativeViewGestureHandler';\n\nexport type GestureType =\n | BaseGesture>\n | BaseGesture>\n | BaseGesture\n | BaseGesture\n | BaseGesture\n | BaseGesture\n | BaseGesture\n | BaseGesture\n | BaseGesture\n | BaseGesture;\n\nexport type GestureRef =\n | number\n | GestureType\n | React.RefObject\n | React.RefObject; // allow adding a ref to a gesture handler\nexport interface BaseGestureConfig\n extends CommonGestureConfig,\n Record {\n ref?: React.MutableRefObject;\n requireToFail?: GestureRef[];\n simultaneousWith?: GestureRef[];\n needsPointerData?: boolean;\n manualActivation?: boolean;\n}\n\ntype TouchEventHandlerType = (\n event: GestureTouchEvent,\n stateManager: GestureStateManagerType\n) => void;\n\nexport type HandlerCallbacks> = {\n handlerTag: number;\n onBegin?: (event: GestureStateChangeEvent) => void;\n onStart?: (event: GestureStateChangeEvent) => void;\n onEnd?: (\n event: GestureStateChangeEvent,\n success: boolean\n ) => void;\n onFinalize?: (\n event: GestureStateChangeEvent,\n success: boolean\n ) => void;\n onUpdate?: (event: GestureUpdateEvent) => void;\n onChange?: (event: any) => void;\n onTouchesDown?: TouchEventHandlerType;\n onTouchesMove?: TouchEventHandlerType;\n onTouchesUp?: TouchEventHandlerType;\n onTouchesCancelled?: TouchEventHandlerType;\n changeEventCalculator?: (\n current: GestureUpdateEvent>,\n previous?: GestureUpdateEvent>\n ) => GestureUpdateEvent>;\n isWorklet: boolean[];\n};\n\nexport const CALLBACK_TYPE = {\n UNDEFINED: 0,\n BEGAN: 1,\n START: 2,\n UPDATE: 3,\n CHANGE: 4,\n END: 5,\n FINALIZE: 6,\n TOUCHES_DOWN: 7,\n TOUCHES_MOVE: 8,\n TOUCHES_UP: 9,\n TOUCHES_CANCELLED: 10,\n} as const;\n\n// Allow using CALLBACK_TYPE as object and type\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport type CALLBACK_TYPE = typeof CALLBACK_TYPE[keyof typeof CALLBACK_TYPE];\n\nexport abstract class Gesture {\n /**\n * Return array of gestures, providing the same interface for creating and updating\n * handlers, no matter which object was used to create gesture instance.\n */\n abstract toGestureArray(): GestureType[];\n\n /**\n * Assign handlerTag to the gesture instance and set ref.current (if a ref is set)\n */\n abstract initialize(): void;\n\n /**\n * Make sure that values of properties defining relations are arrays. Do any necessary\n * preprocessing required to configure relations between handlers. Called just before\n * updating the handler on the native side.\n */\n abstract prepare(): void;\n}\n\nexport abstract class BaseGesture<\n EventPayloadT extends Record\n> extends Gesture {\n public handlerTag = -1;\n public handlerName = '';\n public config: BaseGestureConfig = {};\n public handlers: HandlerCallbacks = {\n handlerTag: -1,\n isWorklet: [false, false, false, false],\n };\n\n private addDependency(\n key: 'simultaneousWith' | 'requireToFail',\n gesture: Exclude\n ) {\n const value = this.config[key];\n this.config[key] = value\n ? Array().concat(value, gesture)\n : [gesture];\n }\n\n withRef(ref: React.MutableRefObject) {\n this.config.ref = ref;\n return this;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n protected isWorklet(callback: Function) {\n //@ts-ignore if callback is a worklet, the property will be available, if not then the check will return false\n return callback.__workletHash !== undefined;\n }\n\n onBegin(callback: (event: GestureStateChangeEvent) => void) {\n this.handlers.onBegin = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.BEGAN] = this.isWorklet(callback);\n return this;\n }\n\n onStart(callback: (event: GestureStateChangeEvent) => void) {\n this.handlers.onStart = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.START] = this.isWorklet(callback);\n return this;\n }\n\n onEnd(\n callback: (\n event: GestureStateChangeEvent,\n success: boolean\n ) => void\n ) {\n this.handlers.onEnd = callback;\n //@ts-ignore if callback is a worklet, the property will be available, if not then the check will return false\n this.handlers.isWorklet[CALLBACK_TYPE.END] = this.isWorklet(callback);\n return this;\n }\n\n onFinalize(\n callback: (\n event: GestureStateChangeEvent,\n success: boolean\n ) => void\n ) {\n this.handlers.onFinalize = callback;\n //@ts-ignore if callback is a worklet, the property will be available, if not then the check will return false\n this.handlers.isWorklet[CALLBACK_TYPE.FINALIZE] = this.isWorklet(callback);\n return this;\n }\n\n onTouchesDown(callback: TouchEventHandlerType) {\n this.config.needsPointerData = true;\n this.handlers.onTouchesDown = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_DOWN] = this.isWorklet(\n callback\n );\n\n return this;\n }\n\n onTouchesMove(callback: TouchEventHandlerType) {\n this.config.needsPointerData = true;\n this.handlers.onTouchesMove = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_MOVE] = this.isWorklet(\n callback\n );\n\n return this;\n }\n\n onTouchesUp(callback: TouchEventHandlerType) {\n this.config.needsPointerData = true;\n this.handlers.onTouchesUp = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_UP] = this.isWorklet(\n callback\n );\n\n return this;\n }\n\n onTouchesCancelled(callback: TouchEventHandlerType) {\n this.config.needsPointerData = true;\n this.handlers.onTouchesCancelled = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.TOUCHES_CANCELLED] = this.isWorklet(\n callback\n );\n\n return this;\n }\n\n enabled(enabled: boolean) {\n this.config.enabled = enabled;\n return this;\n }\n\n shouldCancelWhenOutside(value: boolean) {\n this.config.shouldCancelWhenOutside = value;\n return this;\n }\n\n hitSlop(hitSlop: HitSlop) {\n this.config.hitSlop = hitSlop;\n return this;\n }\n\n simultaneousWithExternalGesture(...gestures: Exclude[]) {\n for (const gesture of gestures) {\n this.addDependency('simultaneousWith', gesture);\n }\n return this;\n }\n\n requireExternalGestureToFail(...gestures: Exclude[]) {\n for (const gesture of gestures) {\n this.addDependency('requireToFail', gesture);\n }\n return this;\n }\n\n initialize() {\n this.handlerTag = getNextHandlerTag();\n this.handlers = { ...this.handlers, handlerTag: this.handlerTag };\n\n if (this.config.ref) {\n this.config.ref.current = this as GestureType;\n }\n }\n\n toGestureArray(): GestureType[] {\n return [this as GestureType];\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n prepare() {}\n}\n\nexport abstract class ContinousBaseGesture<\n EventPayloadT extends Record,\n EventChangePayloadT extends Record\n> extends BaseGesture {\n onUpdate(callback: (event: GestureUpdateEvent) => void) {\n this.handlers.onUpdate = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.UPDATE] = this.isWorklet(callback);\n return this;\n }\n\n onChange(\n callback: (\n event: GestureUpdateEvent\n ) => void\n ) {\n this.handlers.onChange = callback;\n this.handlers.isWorklet[CALLBACK_TYPE.CHANGE] = this.isWorklet(callback);\n return this;\n }\n\n manualActivation(manualActivation: boolean) {\n this.config.manualActivation = manualActivation;\n return this;\n }\n}\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/gestureComposition.js b/lib/module/handlers/gestures/gestureComposition.js new file mode 100644 index 0000000000..e5ca8fb69c --- /dev/null +++ b/lib/module/handlers/gestures/gestureComposition.js @@ -0,0 +1,79 @@ +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; } + +import { BaseGesture, Gesture } from './gesture'; + +function extendRelation(currentRelation, extendWith) { + if (currentRelation === undefined) { + return [...extendWith]; + } else { + return [...currentRelation, ...extendWith]; + } +} + +export class ComposedGesture extends Gesture { + constructor(...gestures) { + super(); + + _defineProperty(this, "gestures", []); + + _defineProperty(this, "simultaneousGestures", []); + + _defineProperty(this, "requireGesturesToFail", []); + + this.gestures = gestures; + } + + prepareSingleGesture(gesture, simultaneousGestures, requireGesturesToFail) { + if (gesture instanceof BaseGesture) { + const newConfig = { ...gesture.config + }; + newConfig.simultaneousWith = extendRelation(newConfig.simultaneousWith, simultaneousGestures); + newConfig.requireToFail = extendRelation(newConfig.requireToFail, requireGesturesToFail); + gesture.config = newConfig; + } else if (gesture instanceof ComposedGesture) { + gesture.simultaneousGestures = simultaneousGestures; + gesture.requireGesturesToFail = requireGesturesToFail; + gesture.prepare(); + } + } + + prepare() { + for (const gesture of this.gestures) { + this.prepareSingleGesture(gesture, this.simultaneousGestures, this.requireGesturesToFail); + } + } + + initialize() { + for (const gesture of this.gestures) { + gesture.initialize(); + } + } + + toGestureArray() { + return this.gestures.flatMap(gesture => gesture.toGestureArray()); + } + +} +export class SimultaneousGesture extends ComposedGesture { + prepare() { + const simultaneousArray = this.gestures.flatMap(gesture => gesture.toGestureArray()).concat(this.simultaneousGestures); + + for (const gesture of this.gestures) { + this.prepareSingleGesture(gesture, simultaneousArray, this.requireGesturesToFail); + } + } + +} +export class ExclusiveGesture extends ComposedGesture { + prepare() { + const gestureArrays = this.gestures.map(gesture => gesture.toGestureArray()); + let requireToFail = []; + + for (let i = 0; i < this.gestures.length; i++) { + this.prepareSingleGesture(this.gestures[i], this.simultaneousGestures, this.requireGesturesToFail.concat(requireToFail)); + requireToFail = requireToFail.concat(gestureArrays[i]); + } + } + +} +//# sourceMappingURL=gestureComposition.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/gestureComposition.js.map b/lib/module/handlers/gestures/gestureComposition.js.map new file mode 100644 index 0000000000..f289687608 --- /dev/null +++ b/lib/module/handlers/gestures/gestureComposition.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["gestureComposition.ts"],"names":["BaseGesture","Gesture","extendRelation","currentRelation","extendWith","undefined","ComposedGesture","constructor","gestures","prepareSingleGesture","gesture","simultaneousGestures","requireGesturesToFail","newConfig","config","simultaneousWith","requireToFail","prepare","initialize","toGestureArray","flatMap","SimultaneousGesture","simultaneousArray","concat","ExclusiveGesture","gestureArrays","map","i","length"],"mappings":";;AAAA,SAASA,WAAT,EAAsBC,OAAtB,QAA8D,WAA9D;;AAEA,SAASC,cAAT,CACEC,eADF,EAEEC,UAFF,EAGE;AACA,MAAID,eAAe,KAAKE,SAAxB,EAAmC;AACjC,WAAO,CAAC,GAAGD,UAAJ,CAAP;AACD,GAFD,MAEO;AACL,WAAO,CAAC,GAAGD,eAAJ,EAAqB,GAAGC,UAAxB,CAAP;AACD;AACF;;AAED,OAAO,MAAME,eAAN,SAA8BL,OAA9B,CAAsC;AAK3CM,EAAAA,WAAW,CAAC,GAAGC,QAAJ,EAAyB;AAClC;;AADkC,sCAJJ,EAII;;AAAA,kDAHY,EAGZ;;AAAA,mDAFa,EAEb;;AAElC,SAAKA,QAAL,GAAgBA,QAAhB;AACD;;AAESC,EAAAA,oBAAoB,CAC5BC,OAD4B,EAE5BC,oBAF4B,EAG5BC,qBAH4B,EAI5B;AACA,QAAIF,OAAO,YAAYV,WAAvB,EAAoC;AAClC,YAAMa,SAAS,GAAG,EAAE,GAAGH,OAAO,CAACI;AAAb,OAAlB;AAEAD,MAAAA,SAAS,CAACE,gBAAV,GAA6Bb,cAAc,CACzCW,SAAS,CAACE,gBAD+B,EAEzCJ,oBAFyC,CAA3C;AAIAE,MAAAA,SAAS,CAACG,aAAV,GAA0Bd,cAAc,CACtCW,SAAS,CAACG,aAD4B,EAEtCJ,qBAFsC,CAAxC;AAKAF,MAAAA,OAAO,CAACI,MAAR,GAAiBD,SAAjB;AACD,KAbD,MAaO,IAAIH,OAAO,YAAYJ,eAAvB,EAAwC;AAC7CI,MAAAA,OAAO,CAACC,oBA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C7C,WAAKlB,oBAAL,CACE,KAAKD,QAAL,CAAcmB,CAAd,CADF,EAEE,KAAKhB,oBAFP,EAGE,KAAKC,qBAAL,CAA2BW,MAA3B,CAAkCP,aAAlC,CAHF;AAMAA,MAAAA,aAAa,GAAGA,aAAa,CAACO,MAAd,CAAqBE,aAAa,CAACE,CAAD,CAAlC,CAAhB;AACD;AACF;;AAjBmD","sourcesContent":["import { BaseGesture, Gesture, GestureRef, GestureType } from './gesture';\n\nfunction extendRelation(\n currentRelation: GestureRef[] | undefined,\n extendWith: GestureType[]\n) {\n if (currentRelation === undefined) {\n return [...extendWith];\n } else {\n return [...currentRelation, ...extendWith];\n }\n}\n\nexport class ComposedGesture extends Gesture {\n protected gestures: Gesture[] = [];\n protected simultaneousGestures: GestureType[] = [];\n protected requireGesturesToFail: GestureType[] = [];\n\n constructor(...gestures: Gesture[]) {\n super();\n this.gestures = gestures;\n }\n\n protected prepareSingleGesture(\n gesture: Gesture,\n simultaneousGestures: GestureType[],\n requireGesturesToFail: GestureType[]\n ) {\n if (gesture instanceof BaseGesture) {\n const newConfig = { ...gesture.config };\n\n newConfig.simultaneousWith = extendRelation(\n newConfig.simultaneousWith,\n simultaneousGestures\n );\n newConfig.requireToFail = extendRelation(\n newConfig.requireToFail,\n requireGesturesToFail\n );\n\n gesture.config = newConfig;\n } else if (gesture instanceof ComposedGesture) {\n gesture.simultaneousGestures = simultaneousGestures;\n gesture.requireGesturesToFail = requireGesturesToFail;\n gesture.prepare();\n }\n }\n\n prepare() {\n for (const gesture of this.gestures) {\n this.prepareSingleGesture(\n gesture,\n this.simultaneousGestures,\n this.requireGesturesToFail\n );\n }\n }\n\n initialize() {\n for (const gesture of this.gestures) {\n gesture.initialize();\n }\n }\n\n toGestureArray(): GestureType[] {\n return this.gestures.flatMap((gesture) => gesture.toGestureArray());\n }\n}\n\nexport class SimultaneousGesture extends ComposedGesture {\n prepare() {\n const simultaneousArray = this.gestures\n .flatMap((gesture) => gesture.toGestureArray())\n .concat(this.simultaneousGestures);\n\n for (const gesture of this.gestures) {\n this.prepareSingleGesture(\n gesture,\n simultaneousArray,\n this.requireGesturesToFail\n );\n }\n }\n}\n\nexport class ExclusiveGesture extends ComposedGesture {\n prepare() {\n const gestureArrays = this.gestures.map((gesture) =>\n gesture.toGestureArray()\n );\n\n let requireToFail: GestureType[] = [];\n\n for (let i = 0; i < this.gestures.length; i++) {\n this.prepareSingleGesture(\n this.gestures[i],\n this.simultaneousGestures,\n this.requireGesturesToFail.concat(requireToFail)\n );\n\n requireToFail = requireToFail.concat(gestureArrays[i]);\n }\n }\n}\n\nexport type ComposedGestureType = InstanceType;\nexport type RaceGestureType = ComposedGestureType;\nexport type SimultaneousGestureType = InstanceType;\nexport type ExclusiveGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/gestureObjects.js b/lib/module/handlers/gestures/gestureObjects.js new file mode 100644 index 0000000000..299f4dc266 --- /dev/null +++ b/lib/module/handlers/gestures/gestureObjects.js @@ -0,0 +1,67 @@ +import { FlingGesture } from './flingGesture'; +import { ForceTouchGesture } from './forceTouchGesture'; +import { ComposedGesture, ExclusiveGesture, SimultaneousGesture } from './gestureComposition'; +import { LongPressGesture } from './longPressGesture'; +import { PanGesture } from './panGesture'; +import { PinchGesture } from './pinchGesture'; +import { RotationGesture } from './rotationGesture'; +import { TapGesture } from './tapGesture'; +import { NativeGesture } from './nativeGesture'; +import { ManualGesture } from './manualGesture'; +export const GestureObjects = { + Tap: () => { + return new TapGesture(); + }, + Pan: () => { + return new PanGesture(); + }, + Pinch: () => { + return new PinchGesture(); + }, + Rotation: () => { + return new RotationGesture(); + }, + Fling: () => { + return new FlingGesture(); + }, + LongPress: () => { + return new LongPressGesture(); + }, + ForceTouch: () => { + return new ForceTouchGesture(); + }, + Native: () => { + return new NativeGesture(); + }, + Manual: () => { + return new ManualGesture(); + }, + + /** + * Builds a composed gesture consisting of gestures provided as parameters. + * The first one that becomes active cancels the rest of gestures. + */ + Race: (...gestures) => { + return new ComposedGesture(...gestures); + }, + + /** + * Builds a composed gesture that allows all base gestures to run simultaneously. + */ + Simultaneous(...gestures) { + return new SimultaneousGesture(...gestures); + }, + + /** + * Builds a composed gesture where only one of the provided gestures can become active. + * Priority is decided through the order of gestures: the first one has higher priority + * than the second one, second one has higher priority than the third one, and so on. + * For example, to make a gesture that recognizes both single and double tap you need + * to call Exclusive(doubleTap, singleTap). + */ + Exclusive(...gestures) { + return new ExclusiveGesture(...gestures); + } + +}; +//# sourceMappingURL=gestureObjects.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/gestureObjects.js.map b/lib/module/handlers/gestures/gestureObjects.js.map new file mode 100644 index 0000000000..4706dbfb9d --- /dev/null +++ b/lib/module/handlers/gestures/gestureObjects.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["gestureObjects.ts"],"names":["FlingGesture","ForceTouchGesture","ComposedGesture","ExclusiveGesture","SimultaneousGesture","LongPressGesture","PanGesture","PinchGesture","RotationGesture","TapGesture","NativeGesture","ManualGesture","GestureObjects","Tap","Pan","Pinch","Rotation","Fling","LongPress","ForceTouch","Native","Manual","Race","gestures","Simultaneous","Exclusive"],"mappings":"AAAA,SAASA,YAAT,QAA6B,gBAA7B;AACA,SAASC,iBAAT,QAAkC,qBAAlC;AAEA,SACEC,eADF,EAEEC,gBAFF,EAGEC,mBAHF,QAIO,sBAJP;AAKA,SAASC,gBAAT,QAAiC,oBAAjC;AACA,SAASC,UAAT,QAA2B,cAA3B;AACA,SAASC,YAAT,QAA6B,gBAA7B;AACA,SAASC,eAAT,QAAgC,mBAAhC;AACA,SAASC,UAAT,QAA2B,cAA3B;AACA,SAASC,aAAT,QAA8B,iBAA9B;AACA,SAASC,aAAT,QAA8B,iBAA9B;AAEA,OAAO,MAAMC,cAAc,GAAG;AAC5BC,EAAAA,GAAG,EAAE,MAAM;AACT,WAAO,IAAIJ,UAAJ,EAAP;AACD,GAH2B;AAK5BK,EAAAA,GAAG,EAAE,MAAM;AACT,WAAO,IAAIR,UAAJ,EAAP;AACD,GAP2B;AAS5BS,EAAAA,KAAK,EAAE,MAAM;AACX,WAAO,IAAIR,YAAJ,EAAP;AACD,GAX2B;AAa5BS,EAAAA,QAAQ,EAAE,MAAM;AACd,WAAO,IAAIR,eAAJ,EAAP;AACD,GAf2B;AAiB5BS,EAAAA,KAAK,EAAE,MAAM;AACX,WAAO,IAAIjB,YAAJ,EAAP;AACD,GAnB2B;AAqB5BkB,EAAAA,SAAS,EAAE,MAAM;AACf,WAAO,IAAIb,gBAAJ,EAAP;AACD,GAvB2B;AAyB5Bc,EAAAA,UAAU,EAAE,MAAM;AAChB,WAAO,IAAIlB,iBAAJ,EAAP;AACD,GA3B2B;AA6B5BmB,EAAAA,MAAM,EAAE,MAAM;AACZ,WAAO,IAAIV,aAAJ,EAAP;AACD,GA/B2B;AAiC5BW,EAAAA,MAAM,EAAE,MAAM;AACZ,WAAO,IAAIV,aAAJ,EAAP;AACD,GAnC2B;;AAqC5B;AACF;AACA;AACA;AACEW,EAAAA,IAAI,EAAE,CAAC,GAAGC,QAAJ,KAA4B;AAChC,WAAO,IAAIrB,eAAJ,CAAoB,GAAGqB,QAAvB,CAAP;AACD,GA3C2B;;AA6C5B;AACF;AACA;AACEC,EAAAA,YAAY,CAAC,GAAGD,QAAJ,EAAyB;AACnC,WAAO,IAAInB,mBAAJ,CAAwB,GAAGmB,QAA3B,CAAP;AACD,GAlD2B;;AAoD5B;AACF;AACA;AACA;AACA;AACA;AACA;AACEE,EAAAA,SAAS,CAAC,GAAGF,QAAJ,EAAyB;AAChC,WAAO,IAAIpB,gBAAJ,CAAqB,GAAGoB,QAAxB,CAAP;AACD;;AA7D2B,CAAvB","sourcesContent":["import { FlingGesture } from './flingGesture';\nimport { ForceTouchGesture } from './forceTouchGesture';\nimport { Gesture } from './gesture';\nimport {\n ComposedGesture,\n ExclusiveGesture,\n SimultaneousGesture,\n} from './gestureComposition';\nimport { LongPressGesture } from './longPressGesture';\nimport { PanGesture } from './panGesture';\nimport { PinchGesture } from './pinchGesture';\nimport { RotationGesture } from './rotationGesture';\nimport { TapGesture } from './tapGesture';\nimport { NativeGesture } from './nativeGesture';\nimport { ManualGesture } from './manualGesture';\n\nexport const GestureObjects = {\n Tap: () => {\n return new TapGesture();\n },\n\n Pan: () => {\n return new PanGesture();\n },\n\n Pinch: () => {\n return new PinchGesture();\n },\n\n Rotation: () => {\n return new RotationGesture();\n },\n\n Fling: () => {\n return new FlingGesture();\n },\n\n LongPress: () => {\n return new LongPressGesture();\n },\n\n ForceTouch: () => {\n return new ForceTouchGesture();\n },\n\n Native: () => {\n return new NativeGesture();\n },\n\n Manual: () => {\n return new ManualGesture();\n },\n\n /**\n * Builds a composed gesture consisting of gestures provided as parameters.\n * The first one that becomes active cancels the rest of gestures.\n */\n Race: (...gestures: Gesture[]) => {\n return new ComposedGesture(...gestures);\n },\n\n /**\n * Builds a composed gesture that allows all base gestures to run simultaneously.\n */\n Simultaneous(...gestures: Gesture[]) {\n return new SimultaneousGesture(...gestures);\n },\n\n /**\n * Builds a composed gesture where only one of the provided gestures can become active.\n * Priority is decided through the order of gestures: the first one has higher priority\n * than the second one, second one has higher priority than the third one, and so on.\n * For example, to make a gesture that recognizes both single and double tap you need\n * to call Exclusive(doubleTap, singleTap).\n */\n Exclusive(...gestures: Gesture[]) {\n return new ExclusiveGesture(...gestures);\n },\n};\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/gestureStateManager.js b/lib/module/handlers/gestures/gestureStateManager.js new file mode 100644 index 0000000000..0865ac16c5 --- /dev/null +++ b/lib/module/handlers/gestures/gestureStateManager.js @@ -0,0 +1,48 @@ +import { Reanimated } from './reanimatedWrapper'; +import { State } from '../../State'; +export const GestureStateManager = { + create(handlerTag) { + 'worklet'; + + return { + begin: () => { + 'worklet'; + + if (Reanimated) { + Reanimated.setGestureState(handlerTag, State.BEGAN); + } else { + console.warn('react-native-reanimated is required in order to use synchronous state management'); + } + }, + activate: () => { + 'worklet'; + + if (Reanimated) { + Reanimated.setGestureState(handlerTag, State.ACTIVE); + } else { + console.warn('react-native-reanimated is required in order to use synchronous state management'); + } + }, + fail: () => { + 'worklet'; + + if (Reanimated) { + Reanimated.setGestureState(handlerTag, State.FAILED); + } else { + console.warn('react-native-reanimated is required in order to use synchronous state management'); + } + }, + end: () => { + 'worklet'; + + if (Reanimated) { + Reanimated.setGestureState(handlerTag, State.END); + } else { + console.warn('react-native-reanimated is required in order to use synchronous state management'); + } + } + }; + } + +}; +//# sourceMappingURL=gestureStateManager.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/gestureStateManager.js.map b/lib/module/handlers/gestures/gestureStateManager.js.map new file mode 100644 index 0000000000..712da77515 --- /dev/null +++ b/lib/module/handlers/gestures/gestureStateManager.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["gestureStateManager.ts"],"names":["Reanimated","State","GestureStateManager","create","handlerTag","begin","setGestureState","BEGAN","console","warn","activate","ACTIVE","fail","FAILED","end","END"],"mappings":"AAAA,SAASA,UAAT,QAA2B,qBAA3B;AACA,SAASC,KAAT,QAAsB,aAAtB;AASA,OAAO,MAAMC,mBAAmB,GAAG;AACjCC,EAAAA,MAAM,CAACC,UAAD,EAA8C;AAClD;;AACA,WAAO;AACLC,MAAAA,KAAK,EAAE,MAAM;AACX;;AACA,YAAIL,UAAJ,EAAgB;AACdA,UAAAA,UAAU,CAACM,eAAX,CAA2BF,UAA3B,EAAuCH,KAAK,CAACM,KAA7C;AACD,SAFD,MAEO;AACLC,UAAAA,OAAO,CAACC,IAAR,CACE,kFADF;AAGD;AACF,OAVI;AAYLC,MAAAA,QAAQ,EAAE,MAAM;AACd;;AACA,YAAIV,UAAJ,EAAgB;AACdA,UAAAA,UAAU,CAACM,eAAX,CAA2BF,UAA3B,EAAuCH,KAAK,CAACU,MAA7C;AACD,SAFD,MAEO;AACLH,UAAAA,OAAO,CAACC,IAAR,CACE,kFADF;AAGD;AACF,OArBI;AAuBLG,MAAAA,IAAI,EAAE,MAAM;AACV;;AACA,YAAIZ,UAAJ,EAAgB;AACdA,UAAAA,UAAU,CAACM,eAAX,CAA2BF,UAA3B,EAAuCH,KAAK,CAACY,MAA7C;AACD,SAFD,MAEO;AACLL,UAAAA,OAAO,CAACC,IAAR,CACE,kFADF;AAGD;AACF,OAhCI;AAkCLK,MAAAA,GAAG,EAAE,MAAM;AACT;;AACA,YAAId,UAAJ,EAAgB;AACdA,UAAAA,UAAU,CAACM,eAAX,CAA2BF,UAA3B,EAAuCH,KAAK,CAACc,GAA7C;AACD,SAFD,MAEO;AACLP,UAAAA,OAAO,CAACC,IAAR,CACE,kFADF;AAGD;AACF;AA3CI,KAAP;AA6CD;;AAhDgC,CAA5B","sourcesContent":["import { Reanimated } from './reanimatedWrapper';\nimport { State } from '../../State';\n\nexport interface GestureStateManagerType {\n begin: () => void;\n activate: () => void;\n fail: () => void;\n end: () => void;\n}\n\nexport const GestureStateManager = {\n create(handlerTag: number): GestureStateManagerType {\n 'worklet';\n return {\n begin: () => {\n 'worklet';\n if (Reanimated) {\n Reanimated.setGestureState(handlerTag, State.BEGAN);\n } else {\n console.warn(\n 'react-native-reanimated is required in order to use synchronous state management'\n );\n }\n },\n\n activate: () => {\n 'worklet';\n if (Reanimated) {\n Reanimated.setGestureState(handlerTag, State.ACTIVE);\n } else {\n console.warn(\n 'react-native-reanimated is required in order to use synchronous state management'\n );\n }\n },\n\n fail: () => {\n 'worklet';\n if (Reanimated) {\n Reanimated.setGestureState(handlerTag, State.FAILED);\n } else {\n console.warn(\n 'react-native-reanimated is required in order to use synchronous state management'\n );\n }\n },\n\n end: () => {\n 'worklet';\n if (Reanimated) {\n Reanimated.setGestureState(handlerTag, State.END);\n } else {\n console.warn(\n 'react-native-reanimated is required in order to use synchronous state management'\n );\n }\n },\n };\n },\n};\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/longPressGesture.js b/lib/module/handlers/gestures/longPressGesture.js new file mode 100644 index 0000000000..deb50cb801 --- /dev/null +++ b/lib/module/handlers/gestures/longPressGesture.js @@ -0,0 +1,24 @@ +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; } + +import { BaseGesture } from './gesture'; +export class LongPressGesture extends BaseGesture { + constructor() { + super(); + + _defineProperty(this, "config", {}); + + this.handlerName = 'LongPressGestureHandler'; + } + + minDuration(duration) { + this.config.minDurationMs = duration; + return this; + } + + maxDistance(distance) { + this.config.maxDist = distance; + return this; + } + +} +//# sourceMappingURL=longPressGesture.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/longPressGesture.js.map b/lib/module/handlers/gestures/longPressGesture.js.map new file mode 100644 index 0000000000..4c1ff04795 --- /dev/null +++ b/lib/module/handlers/gestures/longPressGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["longPressGesture.ts"],"names":["BaseGesture","LongPressGesture","constructor","handlerName","minDuration","duration","config","minDurationMs","maxDistance","distance","maxDist"],"mappings":";;AAAA,SAASA,WAAT,QAA+C,WAA/C;AAMA,OAAO,MAAMC,gBAAN,SAA+BD,WAA/B,CAAgF;AAGrFE,EAAAA,WAAW,GAAG;AACZ;;AADY,oCAF8C,EAE9C;;AAGZ,SAAKC,WAAL,GAAmB,yBAAnB;AACD;;AAEDC,EAAAA,WAAW,CAACC,QAAD,EAAmB;AAC5B,SAAKC,MAAL,CAAYC,aAAZ,GAA4BF,QAA5B;AACA,WAAO,IAAP;AACD;;AAEDG,EAAAA,WAAW,CAACC,QAAD,EAAmB;AAC5B,SAAKH,MAAL,CAAYI,OAAZ,GAAsBD,QAAtB;AACA,WAAO,IAAP;AACD;;AAjBoF","sourcesContent":["import { BaseGesture, BaseGestureConfig } from './gesture';\nimport {\n LongPressGestureConfig,\n LongPressGestureHandlerEventPayload,\n} from '../LongPressGestureHandler';\n\nexport class LongPressGesture extends BaseGesture {\n public config: BaseGestureConfig & LongPressGestureConfig = {};\n\n constructor() {\n super();\n\n this.handlerName = 'LongPressGestureHandler';\n }\n\n minDuration(duration: number) {\n this.config.minDurationMs = duration;\n return this;\n }\n\n maxDistance(distance: number) {\n this.config.maxDist = distance;\n return this;\n }\n}\n\nexport type LongPressGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/manualGesture.js b/lib/module/handlers/gestures/manualGesture.js new file mode 100644 index 0000000000..bb0909e671 --- /dev/null +++ b/lib/module/handlers/gestures/manualGesture.js @@ -0,0 +1,22 @@ +import { ContinousBaseGesture } from './gesture'; + +function changeEventCalculator(current, _previous) { + 'worklet'; + + return current; +} + +export class ManualGesture extends ContinousBaseGesture { + constructor() { + super(); + this.handlerName = 'ManualGestureHandler'; + } + + onChange(callback) { + // @ts-ignore TS being overprotective, Record is Record + this.handlers.changeEventCalculator = changeEventCalculator; + return super.onChange(callback); + } + +} +//# sourceMappingURL=manualGesture.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/manualGesture.js.map b/lib/module/handlers/gestures/manualGesture.js.map new file mode 100644 index 0000000000..0a1c4d741d --- /dev/null +++ b/lib/module/handlers/gestures/manualGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["manualGesture.ts"],"names":["ContinousBaseGesture","changeEventCalculator","current","_previous","ManualGesture","constructor","handlerName","onChange","callback","handlers"],"mappings":"AACA,SAASA,oBAAT,QAAqC,WAArC;;AAEA,SAASC,qBAAT,CACEC,OADF,EAEEC,SAFF,EAGE;AACA;;AACA,SAAOD,OAAP;AACD;;AAED,OAAO,MAAME,aAAN,SAA4BJ,oBAA5B,CAGL;AACAK,EAAAA,WAAW,GAAG;AACZ;AAEA,SAAKC,WAAL,GAAmB,sBAAnB;AACD;;AAEDC,EAAAA,QAAQ,CACNC,QADM,EAEN;AACA;AACA,SAAKC,QAAL,CAAcR,qBAAd,GAAsCA,qBAAtC;AACA,WAAO,MAAMM,QAAN,CAAeC,QAAf,CAAP;AACD;;AAbD","sourcesContent":["import { GestureUpdateEvent } from '../gestureHandlerCommon';\nimport { ContinousBaseGesture } from './gesture';\n\nfunction changeEventCalculator(\n current: GestureUpdateEvent>,\n _previous?: GestureUpdateEvent>\n) {\n 'worklet';\n return current;\n}\n\nexport class ManualGesture extends ContinousBaseGesture<\n Record,\n Record\n> {\n constructor() {\n super();\n\n this.handlerName = 'ManualGestureHandler';\n }\n\n onChange(\n callback: (event: GestureUpdateEvent>) => void\n ) {\n // @ts-ignore TS being overprotective, Record is Record\n this.handlers.changeEventCalculator = changeEventCalculator;\n return super.onChange(callback);\n }\n}\n\nexport type ManualGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/nativeGesture.js b/lib/module/handlers/gestures/nativeGesture.js new file mode 100644 index 0000000000..a6ad75d2fd --- /dev/null +++ b/lib/module/handlers/gestures/nativeGesture.js @@ -0,0 +1,24 @@ +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; } + +import { BaseGesture } from './gesture'; +export class NativeGesture extends BaseGesture { + constructor() { + super(); + + _defineProperty(this, "config", {}); + + this.handlerName = 'NativeViewGestureHandler'; + } + + shouldActivateOnStart(value) { + this.config.shouldActivateOnStart = value; + return this; + } + + disallowInterruption(value) { + this.config.disallowInterruption = value; + return this; + } + +} +//# sourceMappingURL=nativeGesture.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/nativeGesture.js.map b/lib/module/handlers/gestures/nativeGesture.js.map new file mode 100644 index 0000000000..d0343992d4 --- /dev/null +++ b/lib/module/handlers/gestures/nativeGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["nativeGesture.ts"],"names":["BaseGesture","NativeGesture","constructor","handlerName","shouldActivateOnStart","value","config","disallowInterruption"],"mappings":";;AAAA,SAA4BA,WAA5B,QAA+C,WAA/C;AAMA,OAAO,MAAMC,aAAN,SAA4BD,WAA5B,CAAyE;AAG9EE,EAAAA,WAAW,GAAG;AACZ;;AADY,oCAF+C,EAE/C;;AAGZ,SAAKC,WAAL,GAAmB,0BAAnB;AACD;;AAEDC,EAAAA,qBAAqB,CAACC,KAAD,EAAiB;AACpC,SAAKC,MAAL,CAAYF,qBAAZ,GAAoCC,KAApC;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,oBAAoB,CAACF,KAAD,EAAiB;AACnC,SAAKC,MAAL,CAAYC,oBAAZ,GAAmCF,KAAnC;AACA,WAAO,IAAP;AACD;;AAjB6E","sourcesContent":["import { BaseGestureConfig, BaseGesture } from './gesture';\nimport {\n NativeViewGestureConfig,\n NativeViewGestureHandlerPayload,\n} from '../NativeViewGestureHandler';\n\nexport class NativeGesture extends BaseGesture {\n public config: BaseGestureConfig & NativeViewGestureConfig = {};\n\n constructor() {\n super();\n\n this.handlerName = 'NativeViewGestureHandler';\n }\n\n shouldActivateOnStart(value: boolean) {\n this.config.shouldActivateOnStart = value;\n return this;\n }\n\n disallowInterruption(value: boolean) {\n this.config.disallowInterruption = value;\n return this;\n }\n}\n\nexport type NativeGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/panGesture.js b/lib/module/handlers/gestures/panGesture.js new file mode 100644 index 0000000000..d8eee85280 --- /dev/null +++ b/lib/module/handlers/gestures/panGesture.js @@ -0,0 +1,135 @@ +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; } + +import { ContinousBaseGesture } from './gesture'; + +function changeEventCalculator(current, previous) { + 'worklet'; + + let changePayload; + + if (previous === undefined) { + changePayload = { + changeX: current.translationX, + changeY: current.translationY + }; + } else { + changePayload = { + changeX: current.translationX - previous.translationX, + changeY: current.translationY - previous.translationY + }; + } + + return { ...current, + ...changePayload + }; +} + +export class PanGesture extends ContinousBaseGesture { + constructor() { + super(); + + _defineProperty(this, "config", {}); + + this.handlerName = 'PanGestureHandler'; + } + + activeOffsetY(offset) { + if (Array.isArray(offset)) { + this.config.activeOffsetYStart = offset[0]; + this.config.activeOffsetYEnd = offset[1]; + } else if (offset < 0) { + this.config.activeOffsetYStart = offset; + } else { + this.config.activeOffsetYEnd = offset; + } + + return this; + } + + activeOffsetX(offset) { + if (Array.isArray(offset)) { + this.config.activeOffsetXStart = offset[0]; + this.config.activeOffsetXEnd = offset[1]; + } else if (offset < 0) { + this.config.activeOffsetXStart = offset; + } else { + this.config.activeOffsetXEnd = offset; + } + + return this; + } + + failOffsetY(offset) { + if (Array.isArray(offset)) { + this.config.failOffsetYStart = offset[0]; + this.config.failOffsetYEnd = offset[1]; + } else if (offset < 0) { + this.config.failOffsetYStart = offset; + } else { + this.config.failOffsetYEnd = offset; + } + + return this; + } + + failOffsetX(offset) { + if (Array.isArray(offset)) { + this.config.failOffsetXStart = offset[0]; + this.config.failOffsetXEnd = offset[1]; + } else if (offset < 0) { + this.config.failOffsetXStart = offset; + } else { + this.config.failOffsetXEnd = offset; + } + + return this; + } + + minPointers(minPointers) { + this.config.minPointers = minPointers; + return this; + } + + maxPointers(maxPointers) { + this.config.maxPointers = maxPointers; + return this; + } + + minDistance(distance) { + this.config.minDist = distance; + return this; + } + + minVelocity(velocity) { + this.config.minVelocity = velocity; + return this; + } + + minVelocityX(velocity) { + this.config.minVelocityX = velocity; + return this; + } + + minVelocityY(velocity) { + this.config.minVelocityY = velocity; + return this; + } + + averageTouches(value) { + this.config.avgTouches = value; + return this; + } + + enableTrackpadTwoFingerGesture(value) { + this.config.enableTrackpadTwoFingerGesture = value; + return this; + } + + onChange(callback) { + // @ts-ignore TS being overprotective, PanGestureHandlerEventPayload is Record + this.handlers.changeEventCalculator = changeEventCalculator; + return super.onChange(callback); + } + +} +//# sourceMappingURL=panGesture.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/panGesture.js.map b/lib/module/handlers/gestures/panGesture.js.map new file mode 100644 index 0000000000..c837ffd85d --- /dev/null +++ b/lib/module/handlers/gestures/panGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["panGesture.ts"],"names":["ContinousBaseGesture","changeEventCalculator","current","previous","changePayload","undefined","changeX","translationX","changeY","translationY","PanGesture","constructor","handlerName","activeOffsetY","offset","Array","isArray","config","activeOffsetYStart","activeOffsetYEnd","activeOffsetX","activeOffsetXStart","activeOffsetXEnd","failOffsetY","failOffsetYStart","failOffsetYEnd","failOffsetX","failOffsetXStart","failOffsetXEnd","minPointers","maxPointers","minDistance","distance","minDist","minVelocity","velocity","minVelocityX","minVelocityY","averageTouches","value","avgTouches","enableTrackpadTwoFingerGesture","onChange","callback","handlers"],"mappings":";;AAAA,SAA4BA,oBAA5B,QAAwD,WAAxD;;AAYA,SAASC,qBAAT,CACEC,OADF,EAEEC,QAFF,EAGE;AACA;;AACA,MAAIC,aAAJ;;AACA,MAAID,QAAQ,KAAKE,SAAjB,EAA4B;AAC1BD,IAAAA,aAAa,GAAG;AACdE,MAAAA,OAAO,EAAEJ,OAAO,CAACK,YADH;AAEdC,MAAAA,OAAO,EAAEN,OAAO,CAACO;AAFH,KAAhB;AAID,GALD,MAKO;AACLL,IAAAA,aAAa,GAAG;AACdE,MAAAA,OAAO,EAAEJ,OAAO,CAACK,YAAR,GAAuBJ,QAAQ,CAACI,YAD3B;AAEdC,MAAAA,OAAO,EAAEN,OAAO,CAACO,YAAR,GAAuBN,QAAQ,CAACM;AAF3B,KAAhB;AAID;;AAED,SAAO,EAAE,GAAGP,OAAL;AAAc,OAAGE;AAAjB,GAAP;AACD;;AAED,OAAO,MAAMM,UAAN,SAAyBV,oBAAzB,CAGL;AAGAW,EAAAA,WAAW,GAAG;AACZ;;AADY,oCAFwC,EAExC;;AAGZ,SAAKC,WAAL,GAAmB,mBAAnB;AACD;;AAEDC,EAAAA,aAAa,CAACC,MAAD,EAA4B;AACvC,QAAIC,KAAK,CAACC,OAAN,CAAcF,MAAd,CAAJ,EAA2B;AACzB,WAAKG,MAAL,CAAYC,kBAAZ,GAAiCJ,MAAM,CAAC,CAAD,CAAvC;AACA,WAAKG,MAAL,CAA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A,QAAQ,CACNC,QADM,EAMN;AACA;AACA,SAAKC,QAAL,CAAc3C,qBAAd,GAAsCA,qBAAtC;AACA,WAAO,MAAMyC,QAAN,CAAeC,QAAf,CAAP;AACD;;AA3GD","sourcesContent":["import { BaseGestureConfig, ContinousBaseGesture } from './gesture';\nimport { GestureUpdateEvent } from '../gestureHandlerCommon';\nimport {\n PanGestureConfig,\n PanGestureHandlerEventPayload,\n} from '../PanGestureHandler';\n\ntype PanGestureChangeEventPayload = {\n changeX: number;\n changeY: number;\n};\n\nfunction changeEventCalculator(\n current: GestureUpdateEvent,\n previous?: GestureUpdateEvent\n) {\n 'worklet';\n let changePayload: PanGestureChangeEventPayload;\n if (previous === undefined) {\n changePayload = {\n changeX: current.translationX,\n changeY: current.translationY,\n };\n } else {\n changePayload = {\n changeX: current.translationX - previous.translationX,\n changeY: current.translationY - previous.translationY,\n };\n }\n\n return { ...current, ...changePayload };\n}\n\nexport class PanGesture extends ContinousBaseGesture<\n PanGestureHandlerEventPayload,\n PanGestureChangeEventPayload\n> {\n public config: BaseGestureConfig & PanGestureConfig = {};\n\n constructor() {\n super();\n\n this.handlerName = 'PanGestureHandler';\n }\n\n activeOffsetY(offset: number | number[]) {\n if (Array.isArray(offset)) {\n this.config.activeOffsetYStart = offset[0];\n this.config.activeOffsetYEnd = offset[1];\n } else if (offset < 0) {\n this.config.activeOffsetYStart = offset;\n } else {\n this.config.activeOffsetYEnd = offset;\n }\n return this;\n }\n\n activeOffsetX(offset: number | number[]) {\n if (Array.isArray(offset)) {\n this.config.activeOffsetXStart = offset[0];\n this.config.activeOffsetXEnd = offset[1];\n } else if (offset < 0) {\n this.config.activeOffsetXStart = offset;\n } else {\n this.config.activeOffsetXEnd = offset;\n }\n return this;\n }\n\n failOffsetY(offset: number | number[]) {\n if (Array.isArray(offset)) {\n this.config.failOffsetYStart = offset[0];\n this.config.failOffsetYEnd = offset[1];\n } else if (offset < 0) {\n this.config.failOffsetYStart = offset;\n } else {\n this.config.failOffsetYEnd = offset;\n }\n return this;\n }\n\n failOffsetX(offset: number | number[]) {\n if (Array.isArray(offset)) {\n this.config.failOffsetXStart = offset[0];\n this.config.failOffsetXEnd = offset[1];\n } else if (offset < 0) {\n this.config.failOffsetXStart = offset;\n } else {\n this.config.failOffsetXEnd = offset;\n }\n return this;\n }\n\n minPointers(minPointers: number) {\n this.config.minPointers = minPointers;\n return this;\n }\n\n maxPointers(maxPointers: number) {\n this.config.maxPointers = maxPointers;\n return this;\n }\n\n minDistance(distance: number) {\n this.config.minDist = distance;\n return this;\n }\n\n minVelocity(velocity: number) {\n this.config.minVelocity = velocity;\n return this;\n }\n\n minVelocityX(velocity: number) {\n this.config.minVelocityX = velocity;\n return this;\n }\n\n minVelocityY(velocity: number) {\n this.config.minVelocityY = velocity;\n return this;\n }\n\n averageTouches(value: boolean) {\n this.config.avgTouches = value;\n return this;\n }\n\n enableTrackpadTwoFingerGesture(value: boolean) {\n this.config.enableTrackpadTwoFingerGesture = value;\n return this;\n }\n\n onChange(\n callback: (\n event: GestureUpdateEvent<\n PanGestureHandlerEventPayload & PanGestureChangeEventPayload\n >\n ) => void\n ) {\n // @ts-ignore TS being overprotective, PanGestureHandlerEventPayload is Record\n this.handlers.changeEventCalculator = changeEventCalculator;\n return super.onChange(callback);\n }\n}\n\nexport type PanGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/pinchGesture.js b/lib/module/handlers/gestures/pinchGesture.js new file mode 100644 index 0000000000..08c9915239 --- /dev/null +++ b/lib/module/handlers/gestures/pinchGesture.js @@ -0,0 +1,36 @@ +import { ContinousBaseGesture } from './gesture'; + +function changeEventCalculator(current, previous) { + 'worklet'; + + let changePayload; + + if (previous === undefined) { + changePayload = { + scaleChange: current.scale + }; + } else { + changePayload = { + scaleChange: current.scale / previous.scale + }; + } + + return { ...current, + ...changePayload + }; +} + +export class PinchGesture extends ContinousBaseGesture { + constructor() { + super(); + this.handlerName = 'PinchGestureHandler'; + } + + onChange(callback) { + // @ts-ignore TS being overprotective, PinchGestureHandlerEventPayload is Record + this.handlers.changeEventCalculator = changeEventCalculator; + return super.onChange(callback); + } + +} +//# sourceMappingURL=pinchGesture.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/pinchGesture.js.map b/lib/module/handlers/gestures/pinchGesture.js.map new file mode 100644 index 0000000000..6bba657021 --- /dev/null +++ b/lib/module/handlers/gestures/pinchGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["pinchGesture.ts"],"names":["ContinousBaseGesture","changeEventCalculator","current","previous","changePayload","undefined","scaleChange","scale","PinchGesture","constructor","handlerName","onChange","callback","handlers"],"mappings":"AAAA,SAASA,oBAAT,QAAqC,WAArC;;AAQA,SAASC,qBAAT,CACEC,OADF,EAEEC,QAFF,EAGE;AACA;;AACA,MAAIC,aAAJ;;AACA,MAAID,QAAQ,KAAKE,SAAjB,EAA4B;AAC1BD,IAAAA,aAAa,GAAG;AACdE,MAAAA,WAAW,EAAEJ,OAAO,CAACK;AADP,KAAhB;AAGD,GAJD,MAIO;AACLH,IAAAA,aAAa,GAAG;AACdE,MAAAA,WAAW,EAAEJ,OAAO,CAACK,KAAR,GAAgBJ,QAAQ,CAACI;AADxB,KAAhB;AAGD;;AAED,SAAO,EAAE,GAAGL,OAAL;AAAc,OAAGE;AAAjB,GAAP;AACD;;AAED,OAAO,MAAMI,YAAN,SAA2BR,oBAA3B,CAGL;AACAS,EAAAA,WAAW,GAAG;AACZ;AAEA,SAAKC,WAAL,GAAmB,qBAAnB;AACD;;AAEDC,EAAAA,QAAQ,CACNC,QADM,EAMN;AACA;AACA,SAAKC,QAAL,CAAcZ,qBAAd,GAAsCA,qBAAtC;AACA,WAAO,MAAMU,QAAN,CAAeC,QAAf,CAAP;AACD;;AAjBD","sourcesContent":["import { ContinousBaseGesture } from './gesture';\nimport { PinchGestureHandlerEventPayload } from '../PinchGestureHandler';\nimport { GestureUpdateEvent } from '../gestureHandlerCommon';\n\ntype PinchGestureChangeEventPayload = {\n scaleChange: number;\n};\n\nfunction changeEventCalculator(\n current: GestureUpdateEvent,\n previous?: GestureUpdateEvent\n) {\n 'worklet';\n let changePayload: PinchGestureChangeEventPayload;\n if (previous === undefined) {\n changePayload = {\n scaleChange: current.scale,\n };\n } else {\n changePayload = {\n scaleChange: current.scale / previous.scale,\n };\n }\n\n return { ...current, ...changePayload };\n}\n\nexport class PinchGesture extends ContinousBaseGesture<\n PinchGestureHandlerEventPayload,\n PinchGestureChangeEventPayload\n> {\n constructor() {\n super();\n\n this.handlerName = 'PinchGestureHandler';\n }\n\n onChange(\n callback: (\n event: GestureUpdateEvent<\n PinchGestureHandlerEventPayload & PinchGestureChangeEventPayload\n >\n ) => void\n ) {\n // @ts-ignore TS being overprotective, PinchGestureHandlerEventPayload is Record\n this.handlers.changeEventCalculator = changeEventCalculator;\n return super.onChange(callback);\n }\n}\n\nexport type PinchGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/reanimatedWrapper.js b/lib/module/handlers/gestures/reanimatedWrapper.js new file mode 100644 index 0000000000..5afa76b5b8 --- /dev/null +++ b/lib/module/handlers/gestures/reanimatedWrapper.js @@ -0,0 +1,19 @@ +let Reanimated; + +try { + Reanimated = require('react-native-reanimated'); + + if (!Reanimated.setGestureState) { + Reanimated.setGestureState = () => { + 'worklet'; + + console.warn('Please use newer version of react-native-reanimated in order to control state of the gestures.'); + }; + } // When 'react-native-reanimated' is not available we want to + // quietly continue + // eslint-disable-next-line no-empty + +} catch (e) {} + +export { Reanimated }; +//# sourceMappingURL=reanimatedWrapper.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/reanimatedWrapper.js.map b/lib/module/handlers/gestures/reanimatedWrapper.js.map new file mode 100644 index 0000000000..2deec299c8 --- /dev/null +++ b/lib/module/handlers/gestures/reanimatedWrapper.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["reanimatedWrapper.ts"],"names":["Reanimated","require","setGestureState","console","warn","e"],"mappings":"AAUA,IAAIA,UAAJ;;AAkBA,IAAI;AACFA,EAAAA,UAAU,GAAGC,OAAO,CAAC,yBAAD,CAApB;;AAEA,MAAI,CAACD,UAAU,CAACE,eAAhB,EAAiC;AAC/BF,IAAAA,UAAU,CAACE,eAAX,GAA6B,MAAM;AACjC;;AACAC,MAAAA,OAAO,CAACC,IAAR,CACE,gGADF;AAGD,KALD;AAMD,GAVC,CAWF;AACA;AACA;;AACD,CAdD,CAcE,OAAOC,CAAP,EAAU,CAAE;;AAEd,SAASL,UAAT","sourcesContent":["import { ComponentClass } from 'react';\nimport {\n GestureUpdateEvent,\n GestureStateChangeEvent,\n} from '../gestureHandlerCommon';\n\nexport interface SharedValue {\n value: T;\n}\n\nlet Reanimated: {\n default: {\n // Slightly modified definition copied from 'react-native-reanimated'\n // eslint-disable-next-line @typescript-eslint/ban-types\n createAnimatedComponent

(\n component: ComponentClass

,\n options?: unknown\n ): ComponentClass

;\n };\n useEvent: (\n callback: (event: GestureUpdateEvent | GestureStateChangeEvent) => void,\n events: string[],\n rebuild: boolean\n ) => unknown;\n useSharedValue: (value: T) => SharedValue;\n setGestureState: (handlerTag: number, newState: number) => void;\n};\n\ntry {\n Reanimated = require('react-native-reanimated');\n\n if (!Reanimated.setGestureState) {\n Reanimated.setGestureState = () => {\n 'worklet';\n console.warn(\n 'Please use newer version of react-native-reanimated in order to control state of the gestures.'\n );\n };\n }\n // When 'react-native-reanimated' is not available we want to\n // quietly continue\n // eslint-disable-next-line no-empty\n} catch (e) {}\n\nexport { Reanimated };\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/rotationGesture.js b/lib/module/handlers/gestures/rotationGesture.js new file mode 100644 index 0000000000..3b642e89d2 --- /dev/null +++ b/lib/module/handlers/gestures/rotationGesture.js @@ -0,0 +1,36 @@ +import { ContinousBaseGesture } from './gesture'; + +function changeEventCalculator(current, previous) { + 'worklet'; + + let changePayload; + + if (previous === undefined) { + changePayload = { + rotationChange: current.rotation + }; + } else { + changePayload = { + rotationChange: current.rotation - previous.rotation + }; + } + + return { ...current, + ...changePayload + }; +} + +export class RotationGesture extends ContinousBaseGesture { + constructor() { + super(); + this.handlerName = 'RotationGestureHandler'; + } + + onChange(callback) { + // @ts-ignore TS being overprotective, RotationGestureHandlerEventPayload is Record + this.handlers.changeEventCalculator = changeEventCalculator; + return super.onChange(callback); + } + +} +//# sourceMappingURL=rotationGesture.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/rotationGesture.js.map b/lib/module/handlers/gestures/rotationGesture.js.map new file mode 100644 index 0000000000..b09f1f303e --- /dev/null +++ b/lib/module/handlers/gestures/rotationGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["rotationGesture.ts"],"names":["ContinousBaseGesture","changeEventCalculator","current","previous","changePayload","undefined","rotationChange","rotation","RotationGesture","constructor","handlerName","onChange","callback","handlers"],"mappings":"AAAA,SAASA,oBAAT,QAAqC,WAArC;;AAQA,SAASC,qBAAT,CACEC,OADF,EAEEC,QAFF,EAGE;AACA;;AACA,MAAIC,aAAJ;;AACA,MAAID,QAAQ,KAAKE,SAAjB,EAA4B;AAC1BD,IAAAA,aAAa,GAAG;AACdE,MAAAA,cAAc,EAAEJ,OAAO,CAACK;AADV,KAAhB;AAGD,GAJD,MAIO;AACLH,IAAAA,aAAa,GAAG;AACdE,MAAAA,cAAc,EAAEJ,OAAO,CAACK,QAAR,GAAmBJ,QAAQ,CAACI;AAD9B,KAAhB;AAGD;;AAED,SAAO,EAAE,GAAGL,OAAL;AAAc,OAAGE;AAAjB,GAAP;AACD;;AAED,OAAO,MAAMI,eAAN,SAA8BR,oBAA9B,CAGL;AACAS,EAAAA,WAAW,GAAG;AACZ;AAEA,SAAKC,WAAL,GAAmB,wBAAnB;AACD;;AAEDC,EAAAA,QAAQ,CACNC,QADM,EAMN;AACA;AACA,SAAKC,QAAL,CAAcZ,qBAAd,GAAsCA,qBAAtC;AACA,WAAO,MAAMU,QAAN,CAAeC,QAAf,CAAP;AACD;;AAjBD","sourcesContent":["import { ContinousBaseGesture } from './gesture';\nimport { RotationGestureHandlerEventPayload } from '../RotationGestureHandler';\nimport { GestureUpdateEvent } from '../gestureHandlerCommon';\n\ntype RotationGestureChangeEventPayload = {\n rotationChange: number;\n};\n\nfunction changeEventCalculator(\n current: GestureUpdateEvent,\n previous?: GestureUpdateEvent\n) {\n 'worklet';\n let changePayload: RotationGestureChangeEventPayload;\n if (previous === undefined) {\n changePayload = {\n rotationChange: current.rotation,\n };\n } else {\n changePayload = {\n rotationChange: current.rotation - previous.rotation,\n };\n }\n\n return { ...current, ...changePayload };\n}\n\nexport class RotationGesture extends ContinousBaseGesture<\n RotationGestureHandlerEventPayload,\n RotationGestureChangeEventPayload\n> {\n constructor() {\n super();\n\n this.handlerName = 'RotationGestureHandler';\n }\n\n onChange(\n callback: (\n event: GestureUpdateEvent<\n RotationGestureHandlerEventPayload & RotationGestureChangeEventPayload\n >\n ) => void\n ) {\n // @ts-ignore TS being overprotective, RotationGestureHandlerEventPayload is Record\n this.handlers.changeEventCalculator = changeEventCalculator;\n return super.onChange(callback);\n }\n}\n\nexport type RotationGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/module/handlers/gestures/tapGesture.js b/lib/module/handlers/gestures/tapGesture.js new file mode 100644 index 0000000000..5249fa6c95 --- /dev/null +++ b/lib/module/handlers/gestures/tapGesture.js @@ -0,0 +1,49 @@ +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; } + +import { BaseGesture } from './gesture'; +export class TapGesture extends BaseGesture { + constructor() { + super(); + + _defineProperty(this, "config", {}); + + this.handlerName = 'TapGestureHandler'; + } + + minPointers(minPointers) { + this.config.minPointers = minPointers; + return this; + } + + numberOfTaps(count) { + this.config.numberOfTaps = count; + return this; + } + + maxDistance(maxDist) { + this.config.maxDist = maxDist; + return this; + } + + maxDuration(duration) { + this.config.maxDurationMs = duration; + return this; + } + + maxDelay(delay) { + this.config.maxDelayMs = delay; + return this; + } + + maxDeltaX(delta) { + this.config.maxDeltaX = delta; + return this; + } + + maxDeltaY(delta) { + this.config.maxDeltaY = delta; + return this; + } + +} +//# sourceMappingURL=tapGesture.js.map \ No newline at end of file diff --git a/lib/module/handlers/gestures/tapGesture.js.map b/lib/module/handlers/gestures/tapGesture.js.map new file mode 100644 index 0000000000..e90ebfa8b3 --- /dev/null +++ b/lib/module/handlers/gestures/tapGesture.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["tapGesture.ts"],"names":["BaseGesture","TapGesture","constructor","handlerName","minPointers","config","numberOfTaps","count","maxDistance","maxDist","maxDuration","duration","maxDurationMs","maxDelay","delay","maxDelayMs","maxDeltaX","delta","maxDeltaY"],"mappings":";;AAAA,SAA4BA,WAA5B,QAA+C,WAA/C;AAMA,OAAO,MAAMC,UAAN,SAAyBD,WAAzB,CAAoE;AAGzEE,EAAAA,WAAW,GAAG;AACZ;;AADY,oCAFwC,EAExC;;AAGZ,SAAKC,WAAL,GAAmB,mBAAnB;AACD;;AAEDC,EAAAA,WAAW,CAACA,WAAD,EAAsB;AAC/B,SAAKC,MAAL,CAAYD,WAAZ,GAA0BA,WAA1B;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,YAAY,CAACC,KAAD,EAAgB;AAC1B,SAAKF,MAAL,CAAYC,YAAZ,GAA2BC,KAA3B;AACA,WAAO,IAAP;AACD;;AAEDC,EAAAA,WAAW,CAACC,OAAD,EAAkB;AAC3B,SAAKJ,MAAL,CAAYI,OAAZ,GAAsBA,OAAtB;AACA,WAAO,IAAP;AACD;;AAEDC,EAAAA,WAAW,CAACC,QAAD,EAAmB;AAC5B,SAAKN,MAAL,CAAYO,aAAZ,GAA4BD,QAA5B;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,QAAQ,CAACC,KAAD,EAAgB;AACtB,SAAKT,MAAL,CAAYU,UAAZ,GAAyBD,KAAzB;AACA,WAAO,IAAP;AACD;;AAEDE,EAAAA,SAAS,CAACC,KAAD,EAAgB;AACvB,SAAKZ,MAAL,CAAYW,SAAZ,GAAwBC,KAAxB;AACA,WAAO,IAAP;AACD;;AAEDC,EAAAA,SAAS,CAACD,KAAD,EAAgB;AACvB,SAAKZ,MAAL,CAAYa,SAAZ,GAAwBD,KAAxB;AACA,WAAO,IAAP;AACD;;AA1CwE","sourcesContent":["import { BaseGestureConfig, BaseGesture } from './gesture';\nimport {\n TapGestureConfig,\n TapGestureHandlerEventPayload,\n} from '../TapGestureHandler';\n\nexport class TapGesture extends BaseGesture {\n public config: BaseGestureConfig & TapGestureConfig = {};\n\n constructor() {\n super();\n\n this.handlerName = 'TapGestureHandler';\n }\n\n minPointers(minPointers: number) {\n this.config.minPointers = minPointers;\n return this;\n }\n\n numberOfTaps(count: number) {\n this.config.numberOfTaps = count;\n return this;\n }\n\n maxDistance(maxDist: number) {\n this.config.maxDist = maxDist;\n return this;\n }\n\n maxDuration(duration: number) {\n this.config.maxDurationMs = duration;\n return this;\n }\n\n maxDelay(delay: number) {\n this.config.maxDelayMs = delay;\n return this;\n }\n\n maxDeltaX(delta: number) {\n this.config.maxDeltaX = delta;\n return this;\n }\n\n maxDeltaY(delta: number) {\n this.config.maxDeltaY = delta;\n return this;\n }\n}\n\nexport type TapGestureType = InstanceType;\n"]} \ No newline at end of file diff --git a/lib/module/handlers/handlersRegistry.js b/lib/module/handlers/handlersRegistry.js new file mode 100644 index 0000000000..c09f86ae64 --- /dev/null +++ b/lib/module/handlers/handlersRegistry.js @@ -0,0 +1,16 @@ +export const handlerIDToTag = {}; +const handlers = new Map(); +let handlerTag = 1; +export function getNextHandlerTag() { + return handlerTag++; +} +export function registerHandler(handlerTag, handler) { + handlers.set(handlerTag, handler); +} +export function unregisterHandler(handlerTag) { + handlers.delete(handlerTag); +} +export function findHandler(handlerTag) { + return handlers.get(handlerTag); +} +//# sourceMappingURL=handlersRegistry.js.map \ No newline at end of file diff --git a/lib/module/handlers/handlersRegistry.js.map b/lib/module/handlers/handlersRegistry.js.map new file mode 100644 index 0000000000..50b77af409 --- /dev/null +++ b/lib/module/handlers/handlersRegistry.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["handlersRegistry.ts"],"names":["handlerIDToTag","handlers","Map","handlerTag","getNextHandlerTag","registerHandler","handler","set","unregisterHandler","delete","findHandler","get"],"mappings":"AAEA,OAAO,MAAMA,cAAsC,GAAG,EAA/C;AACP,MAAMC,QAAQ,GAAG,IAAIC,GAAJ,EAAjB;AAEA,IAAIC,UAAU,GAAG,CAAjB;AAEA,OAAO,SAASC,iBAAT,GAAqC;AAC1C,SAAOD,UAAU,EAAjB;AACD;AAED,OAAO,SAASE,eAAT,CAAyBF,UAAzB,EAA6CG,OAA7C,EAAmE;AACxEL,EAAAA,QAAQ,CAACM,GAAT,CAAaJ,UAAb,EAAyBG,OAAzB;AACD;AAED,OAAO,SAASE,iBAAT,CAA2BL,UAA3B,EAA+C;AACpDF,EAAAA,QAAQ,CAACQ,MAAT,CAAgBN,UAAhB;AACD;AAED,OAAO,SAASO,WAAT,CAAqBP,UAArB,EAAyC;AAC9C,SAAOF,QAAQ,CAACU,GAAT,CAAaR,UAAb,CAAP;AACD","sourcesContent":["import { GestureType } from './gestures/gesture';\n\nexport const handlerIDToTag: Record = {};\nconst handlers = new Map();\n\nlet handlerTag = 1;\n\nexport function getNextHandlerTag(): number {\n return handlerTag++;\n}\n\nexport function registerHandler(handlerTag: number, handler: GestureType) {\n handlers.set(handlerTag, handler);\n}\n\nexport function unregisterHandler(handlerTag: number) {\n handlers.delete(handlerTag);\n}\n\nexport function findHandler(handlerTag: number) {\n return handlers.get(handlerTag);\n}\n"]} \ No newline at end of file diff --git a/lib/module/index.js b/lib/module/index.js new file mode 100644 index 0000000000..2427a8fd5b --- /dev/null +++ b/lib/module/index.js @@ -0,0 +1,23 @@ +import { initialize } from './init'; +export { Directions } from './Directions'; +export { State } from './State'; +export { default as gestureHandlerRootHOC } from './gestureHandlerRootHOC'; +export { default as GestureHandlerRootView } from './GestureHandlerRootView'; +export { TapGestureHandler } from './handlers/TapGestureHandler'; +export { ForceTouchGestureHandler } from './handlers/ForceTouchGestureHandler'; +export { LongPressGestureHandler } from './handlers/LongPressGestureHandler'; +export { PanGestureHandler } from './handlers/PanGestureHandler'; +export { PinchGestureHandler } from './handlers/PinchGestureHandler'; +export { RotationGestureHandler } from './handlers/RotationGestureHandler'; +export { FlingGestureHandler } from './handlers/FlingGestureHandler'; +export { default as createNativeWrapper } from './handlers/createNativeWrapper'; +export { GestureDetector } from './handlers/gestures/GestureDetector'; +export { GestureObjects as Gesture } from './handlers/gestures/gestureObjects'; +export { NativeViewGestureHandler } from './handlers/NativeViewGestureHandler'; +export { RawButton, BaseButton, RectButton, BorderlessButton } from './components/GestureButtons'; +export { TouchableHighlight, TouchableNativeFeedback, TouchableOpacity, TouchableWithoutFeedback } from './components/touchables'; +export { ScrollView, Switch, TextInput, DrawerLayoutAndroid, FlatList } from './components/GestureComponents'; +export { default as Swipeable } from './components/Swipeable'; +export { default as DrawerLayout } from './components/DrawerLayout'; +initialize(); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/lib/module/index.js.map b/lib/module/index.js.map new file mode 100644 index 0000000000..8fb451c8df --- /dev/null +++ b/lib/module/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["index.ts"],"names":["initialize","Directions","State","default","gestureHandlerRootHOC","GestureHandlerRootView","TapGestureHandler","ForceTouchGestureHandler","LongPressGestureHandler","PanGestureHandler","PinchGestureHandler","RotationGestureHandler","FlingGestureHandler","createNativeWrapper","GestureDetector","GestureObjects","Gesture","NativeViewGestureHandler","RawButton","BaseButton","RectButton","BorderlessButton","TouchableHighlight","TouchableNativeFeedback","TouchableOpacity","TouchableWithoutFeedback","ScrollView","Switch","TextInput","DrawerLayoutAndroid","FlatList","Swipeable","DrawerLayout"],"mappings":"AAAA,SAASA,UAAT,QAA2B,QAA3B;AAEA,SAASC,UAAT,QAA2B,cAA3B;AACA,SAASC,KAAT,QAAsB,SAAtB;AACA,SAASC,OAAO,IAAIC,qBAApB,QAAiD,yBAAjD;AACA,SAASD,OAAO,IAAIE,sBAApB,QAAkD,0BAAlD;AA4CA,SAASC,iBAAT,QAAkC,8BAAlC;AACA,SAASC,wBAAT,QAAyC,qCAAzC;AACA,SAASC,uBAAT,QAAwC,oCAAxC;AACA,SAASC,iBAAT,QAAkC,8BAAlC;AACA,SAASC,mBAAT,QAAoC,gCAApC;AACA,SAASC,sBAAT,QAAuC,mCAAvC;AACA,SAASC,mBAAT,QAAoC,gCAApC;AACA,SAAST,OAAO,IAAIU,mBAApB,QAA+C,gCAA/C;AAKA,SAASC,eAAT,QAAgC,qCAAhC;AACA,SAASC,cAAc,IAAIC,OAA3B,QAA0C,oCAA1C;AAiBA,SAASC,wBAAT,QAAyC,qCAAzC;AAOA,SACEC,SADF,EAEEC,UAFF,EAGEC,UAHF,EAIEC,gBAJF,QAKO,6BALP;AAMA,SACEC,kBADF,EAEEC,uBAFF,EAGEC,gBAHF,EAIEC,wBAJF,QAKO,yBALP;AAMA,SACEC,UADF,EAEEC,MAFF,EAGEC,SAHF,EAIEC,mBAJF,EAKEC,QALF,QAMO,gCANP;AA8CA,SAAS3B,OAAO,IAAI4B,SAApB,QAAqC,wBAArC;AASA,SAAS5B,OAAO,IAAI6B,YAApB,QAAwC,2BAAxC;AAEAhC,UAAU","sourcesContent":["import { initialize } from './init';\n\nexport { Directions } from './Directions';\nexport { State } from './State';\nexport { default as gestureHandlerRootHOC } from './gestureHandlerRootHOC';\nexport { default as GestureHandlerRootView } from './GestureHandlerRootView';\nexport type {\n // event types\n GestureEvent,\n HandlerStateChangeEvent,\n // event payloads types\n GestureEventPayload,\n HandlerStateChangeEventPayload,\n // pointer events\n GestureTouchEvent,\n TouchData,\n // new api event types\n GestureUpdateEvent,\n GestureStateChangeEvent,\n} from './handlers/gestureHandlerCommon';\nexport type { GestureType } from './handlers/gestures/gesture';\nexport type {\n TapGestureHandlerEventPayload,\n TapGestureHandlerProps,\n} from './handlers/TapGestureHandler';\nexport type {\n ForceTouchGestureHandlerEventPayload,\n ForceTouchGestureHandlerProps,\n} from './handlers/ForceTouchGestureHandler';\nexport type {\n LongPressGestureHandlerEventPayload,\n LongPressGestureHandlerProps,\n} from './handlers/LongPressGestureHandler';\nexport type {\n PanGestureHandlerEventPayload,\n PanGestureHandlerProps,\n} from './handlers/PanGestureHandler';\nexport type {\n PinchGestureHandlerEventPayload,\n PinchGestureHandlerProps,\n} from './handlers/PinchGestureHandler';\nexport type {\n RotationGestureHandlerEventPayload,\n RotationGestureHandlerProps,\n} from './handlers/RotationGestureHandler';\nexport type {\n FlingGestureHandlerEventPayload,\n FlingGestureHandlerProps,\n} from './handlers/FlingGestureHandler';\nexport { TapGestureHandler } from './handlers/TapGestureHandler';\nexport { ForceTouchGestureHandler } from './handlers/ForceTouchGestureHandler';\nexport { LongPressGestureHandler } from './handlers/LongPressGestureHandler';\nexport { PanGestureHandler } from './handlers/PanGestureHandler';\nexport { PinchGestureHandler } from './handlers/PinchGestureHandler';\nexport { RotationGestureHandler } from './handlers/RotationGestureHandler';\nexport { FlingGestureHandler } from './handlers/FlingGestureHandler';\nexport { default as createNativeWrapper } from './handlers/createNativeWrapper';\nexport type {\n NativeViewGestureHandlerPayload,\n NativeViewGestureHandlerProps,\n} from './handlers/NativeViewGestureHandler';\nexport { GestureDetector } from './handlers/gestures/GestureDetector';\nexport { GestureObjects as Gesture } from './handlers/gestures/gestureObjects';\nexport type { TapGestureType as TapGesture } from './handlers/gestures/tapGesture';\nexport type { PanGestureType as PanGesture } from './handlers/gestures/panGesture';\nexport type { FlingGestureType as FlingGesture } from './handlers/gestures/flingGesture';\nexport type { LongPressGestureType as LongPressGesture } from './handlers/gestures/longPressGesture';\nexport type { PinchGestureType as PinchGesture } from './handlers/gestures/pinchGesture';\nexport type { RotationGestureType as RotationGesture } from './handlers/gestures/rotationGesture';\nexport type { ForceTouchGestureType as ForceTouchGesture } from './handlers/gestures/forceTouchGesture';\nexport type { NativeGestureType as NativeGesture } from './handlers/gestures/nativeGesture';\nexport type { ManualGestureType as ManualGesture } from './handlers/gestures/manualGesture';\nexport type {\n ComposedGestureType as ComposedGesture,\n RaceGestureType as RaceGesture,\n SimultaneousGestureType as SimultaneousGesture,\n ExclusiveGestureType as ExclusiveGesture,\n} from './handlers/gestures/gestureComposition';\nexport type { GestureStateManagerType as GestureStateManager } from './handlers/gestures/gestureStateManager';\nexport { NativeViewGestureHandler } from './handlers/NativeViewGestureHandler';\nexport type {\n RawButtonProps,\n BaseButtonProps,\n RectButtonProps,\n BorderlessButtonProps,\n} from './components/GestureButtons';\nexport {\n RawButton,\n BaseButton,\n RectButton,\n BorderlessButton,\n} from './components/GestureButtons';\nexport {\n TouchableHighlight,\n TouchableNativeFeedback,\n TouchableOpacity,\n TouchableWithoutFeedback,\n} from './components/touchables';\nexport {\n ScrollView,\n Switch,\n TextInput,\n DrawerLayoutAndroid,\n FlatList,\n} from './components/GestureComponents';\nexport type {\n //events\n GestureHandlerGestureEvent,\n GestureHandlerStateChangeEvent,\n //event payloads\n GestureHandlerGestureEventNativeEvent,\n GestureHandlerStateChangeNativeEvent,\n NativeViewGestureHandlerGestureEvent,\n NativeViewGestureHandlerStateChangeEvent,\n TapGestureHandlerGestureEvent,\n TapGestureHandlerStateChangeEvent,\n ForceTouchGestureHandlerGestureEvent,\n ForceTouchGestureHandlerStateChangeEvent,\n LongPressGestureHandlerGestureEvent,\n LongPressGestureHandlerStateChangeEvent,\n PanGestureHandlerGestureEvent,\n PanGestureHandlerStateChangeEvent,\n PinchGestureHandlerGestureEvent,\n PinchGestureHandlerStateChangeEvent,\n RotationGestureHandlerGestureEvent,\n RotationGestureHandlerStateChangeEvent,\n FlingGestureHandlerGestureEvent,\n FlingGestureHandlerStateChangeEvent,\n // handlers props\n NativeViewGestureHandlerProperties,\n TapGestureHandlerProperties,\n LongPressGestureHandlerProperties,\n PanGestureHandlerProperties,\n PinchGestureHandlerProperties,\n RotationGestureHandlerProperties,\n FlingGestureHandlerProperties,\n ForceTouchGestureHandlerProperties,\n // buttons props\n RawButtonProperties,\n BaseButtonProperties,\n RectButtonProperties,\n BorderlessButtonProperties,\n} from './handlers/gestureHandlerTypesCompat';\n\nexport { default as Swipeable } from './components/Swipeable';\nexport type {\n DrawerLayoutProps,\n DrawerPosition,\n DrawerState,\n DrawerType,\n DrawerLockMode,\n DrawerKeyboardDismissMode,\n} from './components/DrawerLayout';\nexport { default as DrawerLayout } from './components/DrawerLayout';\n\ninitialize();\n"]} \ No newline at end of file diff --git a/lib/module/init.js b/lib/module/init.js new file mode 100644 index 0000000000..0c32d06fba --- /dev/null +++ b/lib/module/init.js @@ -0,0 +1,5 @@ +import { startListening } from './handlers/gestures/eventReceiver'; +export function initialize() { + startListening(); +} +//# sourceMappingURL=init.js.map \ No newline at end of file diff --git a/lib/module/init.js.map b/lib/module/init.js.map new file mode 100644 index 0000000000..99f9d98d75 --- /dev/null +++ b/lib/module/init.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["init.ts"],"names":["startListening","initialize"],"mappings":"AAAA,SAASA,cAAT,QAA+B,mCAA/B;AAEA,OAAO,SAASC,UAAT,GAAsB;AAC3BD,EAAAA,cAAc;AACf","sourcesContent":["import { startListening } from './handlers/gestures/eventReceiver';\n\nexport function initialize() {\n startListening();\n}\n"]} \ No newline at end of file diff --git a/lib/module/mocks.js b/lib/module/mocks.js new file mode 100644 index 0000000000..2e63b72efa --- /dev/null +++ b/lib/module/mocks.js @@ -0,0 +1,54 @@ +import { TouchableHighlight, TouchableNativeFeedback, TouchableOpacity, TouchableWithoutFeedback, ScrollView, FlatList, Switch, TextInput, DrawerLayoutAndroid, View } from 'react-native'; +import { State } from './State'; +import { Directions } from './Directions'; + +const NOOP = () => {// do nothing +}; + +const PanGestureHandler = View; +const attachGestureHandler = NOOP; +const createGestureHandler = NOOP; +const dropGestureHandler = NOOP; +const updateGestureHandler = NOOP; +const NativeViewGestureHandler = View; +const TapGestureHandler = View; +const ForceTouchGestureHandler = View; +const LongPressGestureHandler = View; +const PinchGestureHandler = View; +const RotationGestureHandler = View; +const FlingGestureHandler = View; +const RawButton = TouchableNativeFeedback; +const BaseButton = TouchableNativeFeedback; +const RectButton = TouchableNativeFeedback; +const BorderlessButton = TouchableNativeFeedback; +export default { + TouchableHighlight, + TouchableNativeFeedback, + TouchableOpacity, + TouchableWithoutFeedback, + ScrollView, + FlatList, + Switch, + TextInput, + DrawerLayoutAndroid, + NativeViewGestureHandler, + TapGestureHandler, + ForceTouchGestureHandler, + LongPressGestureHandler, + PinchGestureHandler, + RotationGestureHandler, + FlingGestureHandler, + RawButton, + BaseButton, + RectButton, + BorderlessButton, + PanGestureHandler, + attachGestureHandler, + createGestureHandler, + dropGestureHandler, + updateGestureHandler, + // probably can be removed + Directions, + State +}; +//# sourceMappingURL=mocks.js.map \ No newline at end of file diff --git a/lib/module/mocks.js.map b/lib/module/mocks.js.map new file mode 100644 index 0000000000..5b64343473 --- /dev/null +++ b/lib/module/mocks.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["mocks.ts"],"names":["TouchableHighlight","TouchableNativeFeedback","TouchableOpacity","TouchableWithoutFeedback","ScrollView","FlatList","Switch","TextInput","DrawerLayoutAndroid","View","State","Directions","NOOP","PanGestureHandler","attachGestureHandler","createGestureHandler","dropGestureHandler","updateGestureHandler","NativeViewGestureHandler","TapGestureHandler","ForceTouchGestureHandler","LongPressGestureHandler","PinchGestureHandler","RotationGestureHandler","FlingGestureHandler","RawButton","BaseButton","RectButton","BorderlessButton"],"mappings":"AAAA,SACEA,kBADF,EAEEC,uBAFF,EAGEC,gBAHF,EAIEC,wBAJF,EAKEC,UALF,EAMEC,QANF,EAOEC,MAPF,EAQEC,SARF,EASEC,mBATF,EAUEC,IAVF,QAWO,cAXP;AAYA,SAASC,KAAT,QAAsB,SAAtB;AACA,SAASC,UAAT,QAA2B,cAA3B;;AAEA,MAAMC,IAAI,GAAG,MAAM,CACjB;AACD,CAFD;;AAGA,MAAMC,i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ithoutFeedback,\n ScrollView,\n FlatList,\n Switch,\n TextInput,\n DrawerLayoutAndroid,\n View,\n} from 'react-native';\nimport { State } from './State';\nimport { Directions } from './Directions';\n\nconst NOOP = () => {\n // do nothing\n};\nconst PanGestureHandler = View;\nconst attachGestureHandler = NOOP;\nconst createGestureHandler = NOOP;\nconst dropGestureHandler = NOOP;\nconst updateGestureHandler = NOOP;\nconst NativeViewGestureHandler = View;\nconst TapGestureHandler = View;\nconst ForceTouchGestureHandler = View;\nconst LongPressGestureHandler = View;\nconst PinchGestureHandler = View;\nconst RotationGestureHandler = View;\nconst FlingGestureHandler = View;\nconst RawButton = TouchableNativeFeedback;\nconst BaseButton = TouchableNativeFeedback;\nconst RectButton = TouchableNativeFeedback;\nconst BorderlessButton = TouchableNativeFeedback;\n\nexport default {\n TouchableHighlight,\n TouchableNativeFeedback,\n TouchableOpacity,\n TouchableWithoutFeedback,\n ScrollView,\n FlatList,\n Switch,\n TextInput,\n DrawerLayoutAndroid,\n NativeViewGestureHandler,\n TapGestureHandler,\n ForceTouchGestureHandler,\n LongPressGestureHandler,\n PinchGestureHandler,\n RotationGestureHandler,\n FlingGestureHandler,\n RawButton,\n BaseButton,\n RectButton,\n BorderlessButton,\n PanGestureHandler,\n attachGestureHandler,\n createGestureHandler,\n dropGestureHandler,\n updateGestureHandler,\n // probably can be removed\n Directions,\n State,\n} as const;\n"]} \ No newline at end of file diff --git a/lib/module/typeUtils.js b/lib/module/typeUtils.js new file mode 100644 index 0000000000..28039a80d3 --- /dev/null +++ b/lib/module/typeUtils.js @@ -0,0 +1,2 @@ + +//# sourceMappingURL=typeUtils.js.map \ No newline at end of file diff --git a/lib/module/typeUtils.js.map b/lib/module/typeUtils.js.map new file mode 100644 index 0000000000..9ffd4b22fc --- /dev/null +++ b/lib/module/typeUtils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":[],"names":[],"mappings":"","sourcesContent":[]} \ No newline at end of file diff --git a/lib/module/utils.js b/lib/module/utils.js new file mode 100644 index 0000000000..a1614e6468 --- /dev/null +++ b/lib/module/utils.js @@ -0,0 +1,8 @@ +export function toArray(object) { + if (!Array.isArray(object)) { + return [object]; + } + + return object; +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/lib/module/utils.js.map b/lib/module/utils.js.map new file mode 100644 index 0000000000..bcf0fb549c --- /dev/null +++ b/lib/module/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["utils.ts"],"names":["toArray","object","Array","isArray"],"mappings":"AAAA,OAAO,SAASA,OAAT,CAAoBC,MAApB,EAA0C;AAC/C,MAAI,CAACC,KAAK,CAACC,OAAN,CAAcF,MAAd,CAAL,EAA4B;AAC1B,WAAO,CAACA,MAAD,CAAP;AACD;;AAED,SAAOA,MAAP;AACD","sourcesContent":["export function toArray(object: T | T[]): T[] {\n if (!Array.isArray(object)) {\n return [object];\n }\n\n return object;\n}\n"]} \ No newline at end of file diff --git a/lib/module/web/DiscreteGestureHandler.js b/lib/module/web/DiscreteGestureHandler.js new file mode 100644 index 0000000000..57c405e096 --- /dev/null +++ b/lib/module/web/DiscreteGestureHandler.js @@ -0,0 +1,94 @@ +/* eslint-disable eslint-comments/no-unlimited-disable */ + +/* eslint-disable */ +import GestureHandler from './GestureHandler'; +import { TEST_MAX_IF_NOT_NAN } from './utils'; + +class DiscreteGestureHandler extends GestureHandler { + get isDiscrete() { + return true; + } + + get shouldEnableGestureOnSetup() { + return true; + } + + shouldFailUnderCustomCriteria({ + x, + y, + deltaX, + deltaY + }, { + maxDeltaX, + maxDeltaY, + maxDistSq, + shouldCancelWhenOutside + }) { + if (shouldCancelWhenOutside) { + if (!this.isPointInView({ + x, + y + })) { + return true; + } + } + + return TEST_MAX_IF_NOT_NAN(Math.abs(deltaX), maxDeltaX) || TEST_MAX_IF_NOT_NAN(Math.abs(deltaY), maxDeltaY) || TEST_MAX_IF_NOT_NAN(Math.abs(deltaY * deltaY + deltaX * deltaX), maxDistSq); + } + + transformNativeEvent({ + center: { + x, + y + } + }) { + // @ts-ignore FIXME(TS) + const rect = this.view.getBoundingClientRect(); + return { + absoluteX: x, + absoluteY: y, + x: x - rect.left, + y: y - rect.top + }; + } + + isGestureEnabledForEvent({ + minPointers, + maxPointers, + maxDeltaX, + maxDeltaY, + maxDistSq, + shouldCancelWhenOutside + }, _recognizer, { + maxPointers: pointerLength, + center, + deltaX, + deltaY + }) { + const validPointerCount = pointerLength >= minPointers && pointerLength <= maxPointers; + + if (this.shouldFailUnderCustomCriteria({ ...center, + deltaX, + deltaY + }, { + maxDeltaX, + maxDeltaY, + maxDistSq, + shouldCancelWhenOutside + }) || // A user probably won't land a multi-pointer tap on the first tick (so we cannot just cancel each time) + // but if the gesture is running and the user adds or subtracts another pointer then it should fail. + !validPointerCount && this.isGestureRunning) { + return { + failed: true + }; + } + + return { + success: validPointerCount + }; + } + +} + +export default DiscreteGestureHandler; +//# sourceMappingURL=DiscreteGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/web/DiscreteGestureHandler.js.map b/lib/module/web/DiscreteGestureHandler.js.map new file mode 100644 index 0000000000..25d1d75a79 --- /dev/null +++ b/lib/module/web/DiscreteGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["DiscreteGestureHandler.ts"],"names":["GestureHandler","TEST_MAX_IF_NOT_NAN","DiscreteGestureHandler","isDiscrete","shouldEnableGestureOnSetup","shouldFailUnderCustomCriteria","x","y","deltaX","deltaY","maxDeltaX","maxDeltaY","maxDistSq","shouldCancelWhenOutside","isPointInView","Math","abs","transformNativeEvent","center","rect","view","getBoundingClientRect","absoluteX","absoluteY","left","top","isGestureEnabledForEvent","minPointers","maxPointers","_recognizer","pointerLength","validPointerCount","isGestureRunning","failed","success"],"mappings":"AAAA;;AACA;AACA,OAAOA,cAAP,MAA2B,kBAA3B;AACA,SAASC,mBAAT,QAAoC,SAApC;;AAEA,MAAeC,sBAAf,SAA8CF,cAA9C,CAA6D;AAC7C,MAAVG,UAAU,GAAG;AACf,WAAO,IAAP;AACD;;A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;AAKEC,IAAAA,SALF;AAMEC,IAAAA;AANF,GADsB,EAStBgB,WATsB,EAUtB;AAAED,IAAAA,WAAW,EAAEE,aAAf;AAA8BZ,IAAAA,MAA9B;AAAsCV,IAAAA,MAAtC;AAA8CC,IAAAA;AAA9C,GAVsB,EAWtB;AACA,UAAMsB,iBAAiB,GACrBD,aAAa,IAAIH,WAAjB,IAAgCG,aAAa,IAAIF,WADnD;;AAGA,QACE,KAAKvB,6BAAL,CACE,EAAE,GAAGa,MAAL;AAAaV,MAAAA,MAAb;AAAqBC,MAAAA;AAArB,KADF,EAEE;AACEC,MAAAA,SADF;AAEEC,MAAAA,SAFF;AAGEC,MAAAA,SAHF;AAIEC,MAAAA;AAJF,KAFF,KASA;AACA;AACC,KAACkB,iBAAD,IAAsB,KAAKC,gBAZ9B,EAaE;AACA,aAAO;AAAEC,QAAAA,MAAM,EAAE;AAAV,OAAP;AACD;;AAED,WAAO;AAAEC,MAAAA,OAAO,EAAEH;AAAX,KAAP;AACD;;AAzE0D;;AA4E7D,eAAe7B,sBAAf","sourcesContent":["/* eslint-disable eslint-comments/no-unlimited-disable */\n/* eslint-disable */\nimport GestureHandler from './GestureHandler';\nimport { TEST_MAX_IF_NOT_NAN } from './utils';\n\nabstract class DiscreteGestureHandler extends GestureHandler {\n get isDiscrete() {\n return true;\n }\n\n get shouldEnableGestureOnSetup() {\n return true;\n }\n\n shouldFailUnderCustomCriteria(\n { x, y, deltaX, deltaY }: any,\n { maxDeltaX, maxDeltaY, maxDistSq, shouldCancelWhenOutside }: any\n ) {\n if (shouldCancelWhenOutside) {\n if (!this.isPointInView({ x, y })) {\n return true;\n }\n }\n return (\n TEST_MAX_IF_NOT_NAN(Math.abs(deltaX), maxDeltaX) ||\n TEST_MAX_IF_NOT_NAN(Math.abs(deltaY), maxDeltaY) ||\n TEST_MAX_IF_NOT_NAN(\n Math.abs(deltaY * deltaY + deltaX * deltaX),\n maxDistSq\n )\n );\n }\n\n transformNativeEvent({ center: { x, y } }: any) {\n // @ts-ignore FIXME(TS)\n const rect = this.view!.getBoundingClientRect();\n\n return {\n absoluteX: x,\n absoluteY: y,\n x: x - rect.left,\n y: y - rect.top,\n };\n }\n\n isGestureEnabledForEvent(\n {\n minPointers,\n maxPointers,\n maxDeltaX,\n maxDeltaY,\n maxDistSq,\n shouldCancelWhenOutside,\n }: any,\n _recognizer: any,\n { maxPointers: pointerLength, center, deltaX, deltaY }: any\n ) {\n const validPointerCount =\n pointerLength >= minPointers && pointerLength <= maxPointers;\n\n if (\n this.shouldFailUnderCustomCriteria(\n { ...center, deltaX, deltaY },\n {\n maxDeltaX,\n maxDeltaY,\n maxDistSq,\n shouldCancelWhenOutside,\n }\n ) ||\n // A user probably won't land a multi-pointer tap on the first tick (so we cannot just cancel each time)\n // but if the gesture is running and the user adds or subtracts another pointer then it should fail.\n (!validPointerCount && this.isGestureRunning)\n ) {\n return { failed: true };\n }\n\n return { success: validPointerCount };\n }\n}\n\nexport default DiscreteGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/module/web/DraggingGestureHandler.js b/lib/module/web/DraggingGestureHandler.js new file mode 100644 index 0000000000..a652f1dc5b --- /dev/null +++ b/lib/module/web/DraggingGestureHandler.js @@ -0,0 +1,40 @@ +/* eslint-disable eslint-comments/no-unlimited-disable */ + +/* eslint-disable */ +import GestureHandler from './GestureHandler'; +import { PixelRatio } from 'react-native'; + +class DraggingGestureHandler extends GestureHandler { + get shouldEnableGestureOnSetup() { + return true; + } + + transformNativeEvent({ + deltaX, + deltaY, + velocityX, + velocityY, + center: { + x, + y + } + }) { + // @ts-ignore FIXME(TS) + const rect = this.view.getBoundingClientRect(); + const ratio = PixelRatio.get(); + return { + translationX: deltaX - (this.__initialX || 0), + translationY: deltaY - (this.__initialY || 0), + absoluteX: x, + absoluteY: y, + velocityX: velocityX * ratio, + velocityY: velocityY * ratio, + x: x - rect.left, + y: y - rect.top + }; + } + +} + +export default DraggingGestureHandler; +//# sourceMappingURL=DraggingGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/web/DraggingGestureHandler.js.map b/lib/module/web/DraggingGestureHandler.js.map new file mode 100644 index 0000000000..3a9ce9b780 --- /dev/null +++ b/lib/module/web/DraggingGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["DraggingGestureHandler.ts"],"names":["GestureHandler","PixelRatio","DraggingGestureHandler","shouldEnableGestureOnSetup","transformNativeEvent","deltaX","deltaY","velocityX","velocityY","center","x","y","rect","view","getBoundingClientRect","ratio","get","translationX","__initialX","translationY","__initialY","absoluteX","absoluteY","left","top"],"mappings":"AAAA;;AACA;AACA,OAAOA,cAAP,MAA+C,kBAA/C;AACA,SAASC,UAAT,QAA2B,cAA3B;;AAEA,MAAeC,sBAAf,SAA8CF,cAA9C,CAA6D;AAC7B,MAA1BG,0BAA0B,GAAG;AAC/B,WAAO,IAAP;AACD;;AAEDC,EAAAA,oBAAoB,CAAC;AACnBC,IAAAA,MADmB;AAEnBC,IAAAA,MAFmB;AAGnBC,IAAAA,SAHmB;AAInBC,IAAAA,SAJmB;AAKnBC,IAAAA,MAAM,EAAE;AAAEC,MAAAA,CAAF;AAAKC,MAAAA;AAAL;AALW,GAAD,EAMD;AACjB;AACA,UAAMC,IAAI,GAAG,KAAKC,IAAL,CAAWC,qBAAX,EAAb;AACA,UAAMC,KAAK,GAAGd,UAAU,CAACe,GAAX,EAAd;AACA,WAAO;AACLC,MAAAA,YAAY,EAAEZ,MAAM,IAAI,KAAKa,UAAL,IAAmB,CAAvB,CADf;AAELC,MAAAA,YAAY,EAAEb,MAAM,IAAI,KAAKc,UAAL,IAAmB,CAAvB,CAFf;AAGLC,MAAAA,SAAS,EAAEX,CAHN;AAILY,MAAAA,SAAS,EAAEX,CAJN;AAKLJ,MAAAA,SAAS,EAAEA,SAAS,GAAGQ,KALlB;AAMLP,MAAAA,SAAS,EAAEA,SAAS,GAAGO,KANlB;AAOLL,MAAAA,CAAC,EAAEA,CAAC,GAAGE,IAAI,CAACW,IAPP;AAQLZ,MAAAA,CAAC,EAAEA,CAAC,GAAGC,IAAI,CAACY;AARP,KAAP;AAUD;;AAzB0D;;AA4B7D,eAAetB,sBAAf","sourcesContent":["/* eslint-disable eslint-comments/no-unlimited-disable */\n/* eslint-disable */\nimport GestureHandler, { HammerInputExt } from './GestureHandler';\nimport { PixelRatio } from 'react-native';\n\nabstract class DraggingGestureHandler extends GestureHandler {\n get shouldEnableGestureOnSetup() {\n return true;\n }\n\n transformNativeEvent({\n deltaX,\n deltaY,\n velocityX,\n velocityY,\n center: { x, y },\n }: HammerInputExt) {\n // @ts-ignore FIXME(TS)\n const rect = this.view!.getBoundingClientRect();\n const ratio = PixelRatio.get();\n return {\n translationX: deltaX - (this.__initialX || 0),\n translationY: deltaY - (this.__initialY || 0),\n absoluteX: x,\n absoluteY: y,\n velocityX: velocityX * ratio,\n velocityY: velocityY * ratio,\n x: x - rect.left,\n y: y - rect.top,\n };\n }\n}\n\nexport default DraggingGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/module/web/Errors.js b/lib/module/web/Errors.js new file mode 100644 index 0000000000..f88789ae30 --- /dev/null +++ b/lib/module/web/Errors.js @@ -0,0 +1,7 @@ +export class GesturePropError extends Error { + constructor(name, value, expectedType) { + super(`Invalid property \`${name}: ${value}\` expected \`${expectedType}\``); + } + +} +//# sourceMappingURL=Errors.js.map \ No newline at end of file diff --git a/lib/module/web/Errors.js.map b/lib/module/web/Errors.js.map new file mode 100644 index 0000000000..fad94acd54 --- /dev/null +++ b/lib/module/web/Errors.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["Errors.ts"],"names":["GesturePropError","Error","constructor","name","value","expectedType"],"mappings":"AAAA,OAAO,MAAMA,gBAAN,SAA+BC,KAA/B,CAAqC;AAC1CC,EAAAA,WAAW,CAACC,IAAD,EAAeC,KAAf,EAA+BC,YAA/B,EAAqD;AAC9D,UACG,sBAAqBF,IAAK,KAAIC,KAAM,iBAAgBC,YAAa,IADpE;AAGD;;AALyC","sourcesContent":["export class GesturePropError extends Error {\n constructor(name: string, value: unknown, expectedType: string) {\n super(\n `Invalid property \\`${name}: ${value}\\` expected \\`${expectedType}\\``\n );\n }\n}\n"]} \ No newline at end of file diff --git a/lib/module/web/FlingGestureHandler.js b/lib/module/web/FlingGestureHandler.js new file mode 100644 index 0000000000..4eeb510f73 --- /dev/null +++ b/lib/module/web/FlingGestureHandler.js @@ -0,0 +1,156 @@ +/* eslint-disable eslint-comments/no-unlimited-disable */ + +/* eslint-disable */ +import Hammer from '@egjs/hammerjs'; +import { Direction } from './constants'; +import { GesturePropError } from './Errors'; +import DraggingGestureHandler from './DraggingGestureHandler'; +import { isnan } from './utils'; + +class FlingGestureHandler extends DraggingGestureHandler { + get name() { + return 'swipe'; + } + + get NativeGestureClass() { + return Hammer.Swipe; + } + + onGestureActivated(event) { + this.sendEvent({ ...event, + eventType: Hammer.INPUT_MOVE, + isFinal: false, + isFirst: true + }); + this.isGestureRunning = false; + this.hasGestureFailed = false; + this.sendEvent({ ...event, + eventType: Hammer.INPUT_END, + isFinal: true + }); + } + + onRawEvent(ev) { + super.onRawEvent(ev); + + if (this.hasGestureFailed) { + return; + } // Hammer doesn't send a `cancel` event for taps. + // Manually fail the event. + + + if (ev.isFinal) { + setTimeout(() => { + if (this.isGestureRunning) { + this.cancelEvent(ev); + } + }); + } else if (!this.hasGestureFailed && !this.isGestureRunning) { + // Tap Gesture start event + const gesture = this.hammer.get(this.name); // @ts-ignore FIXME(TS) + + if (gesture.options.enable(gesture, ev)) { + this.onStart(ev); + this.sendEvent(ev); + } + } + } + + getHammerConfig() { + return { + // @ts-ignore FIXME(TS) + pointers: this.config.numberOfPointers, + direction: this.getDirection() + }; + } + + getTargetDirections(direction) { + const directions = []; + + if (direction & Direction.RIGHT) { + directions.push(Hammer.DIRECTION_RIGHT); + } + + if (direction & Direction.LEFT) { + directions.push(Hammer.DIRECTION_LEFT); + } + + if (direction & Direction.UP) { + directions.push(Hammer.DIRECTION_UP); + } + + if (direction & Direction.DOWN) { + directions.push(Hammer.DIRECTION_DOWN); + } // const hammerDirection = directions.reduce((a, b) => a | b, 0); + + + return directions; + } + + getDirection() { + // @ts-ignore FIXME(TS) + const { + direction + } = this.getConfig(); + let directions = []; + + if (direction & Direction.RIGHT) { + directions.push(Hammer.DIRECTION_HORIZONTAL); + } + + if (direction & Direction.LEFT) { + directions.push(Hammer.DIRECTION_HORIZONTAL); + } + + if (direction & Direction.UP) { + directions.push(Hammer.DIRECTION_VERTICAL); + } + + if (direction & Direction.DOWN) { + directions.push(Hammer.DIRECTION_VERTICAL); + } + + directions = [...new Set(directions)]; + if (directions.length === 0) return Hammer.DIRECTION_NONE; + if (directions.length === 1) return directions[0]; + return Hammer.DIRECTION_ALL; + } + + isGestureEnabledForEvent({ + numberOfPointers + }, _recognizer, { + maxPointers: pointerLength + }) { + const validPointerCount = pointerLength === numberOfPointers; + + if (!validPointerCount && this.isGestureRunning) { + return { + failed: true + }; + } + + return { + success: validPointerCount + }; + } + + updateGestureConfig({ + numberOfPointers = 1, + direction, + ...props + }) { + if (isnan(direction) || typeof direction !== 'number') { + throw new GesturePropError('direction', direction, 'number'); + } + + return super.updateGestureConfig({ + numberOfPointers, + direction, + ...props + }); + } + +} + +export default FlingGestureHandler; +//# sourceMappingURL=FlingGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/web/FlingGestureHandler.js.map b/lib/module/web/FlingGestureHandler.js.map new file mode 100644 index 0000000000..a6336ec21c --- /dev/null +++ b/lib/module/web/FlingGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["FlingGestureHandler.ts"],"names":["Hammer","Direction","GesturePropError","DraggingGestureHandler","isnan","FlingGestureHandler","name","NativeGestureClass","Swipe","onGestureActivated","event","sendEvent","eventType","INPUT_MOVE","isFinal","isFirst","isGestureRunning","hasGestureFailed","INPUT_END","onRawEvent","ev","setTimeout","cancelEvent","gesture","hammer","get","options","enable","onStart","getHammerConfig","pointers","config","numberOfPointers","direction","getDirection","getTargetDirections","directions","RIGHT","push","DIRECTION_RIGHT","LEFT","DIRECTION_LEFT","UP","DIRECTION_UP","DOWN","DIRECTION_DOWN","getConfig","DIRECTION_HORIZONTAL","DIRECTION_VERTICAL","Set","length","DIRECTION_NONE","DIRECTION_ALL","isGestureEnabledForEvent","_recognizer","maxPointers","pointerLength","validPointerCount","failed","success","updateGestureConfig","props"],"mappings":"AAAA;;AACA;AACA,OAAOA,MAAP,MAAmB,gBAAnB;AAEA,SAASC,SAAT,QAA0B,aAA1B;AACA,SAASC,gBAAT,QAAiC,UAAjC;AACA,OAAOC,sBAAP,MAAmC,0BAAnC;AACA,SAASC,KAAT,QAAsB,SAAtB;;AAGA,MAAMC,mBAAN,SAAkCF,sBAAlC,CAAyD;AAC/C,MAAJG,IAAI,GAAG;AACT,WAAO,OAAP;AACD;;AAEqB,MAAlBC,kBAAkB,GAAG;AACvB,WAAOP,MAAM,CAACQ,KAAd;AACD;;AAEDC,EAAAA,kBAAkB,CAACC,KAAD,EAAwB;AACxC,SAAKC,SAAL,CAAe,EACb,GAAGD,KADU;AAEbE,MAAAA,SAAS,EAAEZ,MAAM,CAACa,UAFL;AAGbC,MAAAA,OAAO,EAAE,KAHI;AAIbC,MAAAA,OAAO,EAAE;AAJI,KAAf;AAMA,SAAKC,gBAAL,GAAwB,KAAxB;AACA,SAAKC,gBAAL,GAAwB,KAAxB;AACA,SAAKN,SAAL,CAAe,EACb,GAAGD,KADU;AAEbE,MAAAA,SAAS,EAAEZ,MAAM,CAACkB,SAFL;AAGbJ,MAAAA,OAAO,EAAE;AAHI,KAAf;AAKD;;AAEDK,EAAAA,UAAU,CAACC,EAAD,EAAqB;AAC7B,UAAMD,UAAN,CAAiBC,EAAjB;;AACA,QAAI,KAAKH,gBAAT,EAA2B;AACzB;AACD,KAJ4B,CAK7B;AACA;;;AACA,QAAIG,EAAE,CAACN,OAAP,EAAgB;AACdO,MAAAA,UAAU,CAAC,MAAM;AACf,YAAI,KAAKL,gBAAT,EAA2B;AACzB,eAAKM,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AAAE5B,IAAAA,gBAAgB,GAAG,CAArB;AAAwBC,IAAAA,SAAxB;AAAmC,OAAG4B;AAAtC,GAAD,EAAqD;AACtE,QAAIzD,KAAK,CAAC6B,SAAD,CAAL,IAAoB,OAAOA,SAAP,KAAqB,QAA7C,EAAuD;AACrD,YAAM,IAAI/B,gBAAJ,CAAqB,WAArB,EAAkC+B,SAAlC,EAA6C,QAA7C,CAAN;AACD;;AACD,WAAO,MAAM2B,mBAAN,CAA0B;AAC/B5B,MAAAA,gBAD+B;AAE/BC,MAAAA,SAF+B;AAG/B,SAAG4B;AAH4B,KAA1B,CAAP;AAKD;;AAxHsD;;AA2HzD,eAAexD,mBAAf","sourcesContent":["/* eslint-disable eslint-comments/no-unlimited-disable */\n/* eslint-disable */\nimport Hammer from '@egjs/hammerjs';\n\nimport { Direction } from './constants';\nimport { GesturePropError } from './Errors';\nimport DraggingGestureHandler from './DraggingGestureHandler';\nimport { isnan } from './utils';\nimport { HammerInputExt } from './GestureHandler';\n\nclass FlingGestureHandler extends DraggingGestureHandler {\n get name() {\n return 'swipe';\n }\n\n get NativeGestureClass() {\n return Hammer.Swipe;\n }\n\n onGestureActivated(event: HammerInputExt) {\n this.sendEvent({\n ...event,\n eventType: Hammer.INPUT_MOVE,\n isFinal: false,\n isFirst: true,\n });\n this.isGestureRunning = false;\n this.hasGestureFailed = false;\n this.sendEvent({\n ...event,\n eventType: Hammer.INPUT_END,\n isFinal: true,\n });\n }\n\n onRawEvent(ev: HammerInputExt) {\n super.onRawEvent(ev);\n if (this.hasGestureFailed) {\n return;\n }\n // Hammer doesn't send a `cancel` event for taps.\n // Manually fail the event.\n if (ev.isFinal) {\n setTimeout(() => {\n if (this.isGestureRunning) {\n this.cancelEvent(ev);\n }\n });\n } else if (!this.hasGestureFailed && !this.isGestureRunning) {\n // Tap Gesture start event\n const gesture = this.hammer!.get(this.name);\n // @ts-ignore FIXME(TS)\n if (gesture.options.enable(gesture, ev)) {\n this.onStart(ev);\n this.sendEvent(ev);\n }\n }\n }\n\n getHammerConfig() {\n return {\n // @ts-ignore FIXME(TS)\n pointers: this.config.numberOfPointers,\n direction: this.getDirection(),\n };\n }\n\n getTargetDirections(direction: number) {\n const directions = [];\n if (direction & Direction.RIGHT) {\n directions.push(Hammer.DIRECTION_RIGHT);\n }\n if (direction & Direction.LEFT) {\n directions.push(Hammer.DIRECTION_LEFT);\n }\n if (direction & Direction.UP) {\n directions.push(Hammer.DIRECTION_UP);\n }\n if (direction & Direction.DOWN) {\n directions.push(Hammer.DIRECTION_DOWN);\n }\n // const hammerDirection = directions.reduce((a, b) => a | b, 0);\n return directions;\n }\n\n getDirection() {\n // @ts-ignore FIXME(TS)\n const { direction } = this.getConfig();\n\n let directions = [];\n if (direction & Direction.RIGHT) {\n directions.push(Hammer.DIRECTION_HORIZONTAL);\n }\n if (direction & Direction.LEFT) {\n directions.push(Hammer.DIRECTION_HORIZONTAL);\n }\n if (direction & Direction.UP) {\n directions.push(Hammer.DIRECTION_VERTICAL);\n }\n if (direction & Direction.DOWN) {\n directions.push(Hammer.DIRECTION_VERTICAL);\n }\n directions = [...new Set(directions)];\n\n if (directions.length === 0) return Hammer.DIRECTION_NONE;\n if (directions.length === 1) return directions[0];\n return Hammer.DIRECTION_ALL;\n }\n\n isGestureEnabledForEvent(\n { numberOfPointers }: any,\n _recognizer: any,\n { maxPointers: pointerLength }: any\n ) {\n const validPointerCount = pointerLength === numberOfPointers;\n if (!validPointerCount && this.isGestureRunning) {\n return { failed: true };\n }\n return { success: validPointerCount };\n }\n\n updateGestureConfig({ numberOfPointers = 1, direction, ...props }: any) {\n if (isnan(direction) || typeof direction !== 'number') {\n throw new GesturePropError('direction', direction, 'number');\n }\n return super.updateGestureConfig({\n numberOfPointers,\n direction,\n ...props,\n });\n }\n}\n\nexport default FlingGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/module/web/GestureHandler.js b/lib/module/web/GestureHandler.js new file mode 100644 index 0000000000..f086cc4396 --- /dev/null +++ b/lib/module/web/GestureHandler.js @@ -0,0 +1,518 @@ +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; } + +/* eslint-disable eslint-comments/no-unlimited-disable */ + +/* eslint-disable */ +import Hammer from '@egjs/hammerjs'; +import { findNodeHandle } from 'react-native'; +import { State } from '../State'; +import { EventMap } from './constants'; +import * as NodeManager from './NodeManager'; // TODO(TS) Replace with HammerInput if https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50438/files is merged + +let gestureInstances = 0; + +class GestureHandler { + get id() { + return `${this.name}${this.gestureInstance}`; + } + + get isDiscrete() { + return false; + } + + get shouldEnableGestureOnSetup() { + throw new Error('Must override GestureHandler.shouldEnableGestureOnSetup'); + } + + constructor() { + _defineProperty(this, "handlerTag", void 0); + + _defineProperty(this, "isGestureRunning", false); + + _defineProperty(this, "view", null); + + _defineProperty(this, "hasCustomActivationCriteria", void 0); + + _defineProperty(this, "hasGestureFailed", false); + + _defineProperty(this, "hammer", null); + + _defineProperty(this, "initialRotation", null); + + _defineProperty(this, "__initialX", void 0); + + _defineProperty(this, "__initialY", void 0); + + _defineProperty(this, "config", {}); + + _defineProperty(this, "previousState", State.UNDETERMINED); + + _defineProperty(this, "pendingGestures", {}); + + _defineProperty(this, "oldState", State.UNDETERMINED); + + _defineProperty(this, "lastSentState", null); + + _defineProperty(this, "gestureInstance", void 0); + + _defineProperty(this, "_stillWaiting", void 0); + + _defineProperty(this, "propsRef", void 0); + + _defineProperty(this, "ref", void 0); + + _defineProperty(this, "clearSelfAsPending", () => { + if (Array.isArray(this.config.waitFor)) { + for (const gesture of this.config.waitFor) { + gesture.removePendingGesture(this.id); + } + } + }); + + _defineProperty(this, "destroy", () => { + this.clearSelfAsPending(); + + if (this.hammer) { + this.hammer.stop(false); + this.hammer.destroy(); + } + + this.hammer = null; + }); + + _defineProperty(this, "isPointInView", ({ + x, + y + }) => { + // @ts-ignore FIXME(TS) + const rect = this.view.getBoundingClientRect(); + const pointerInside = x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom; + return pointerInside; + }); + + _defineProperty(this, "sendEvent", nativeEvent => { + const { + onGestureHandlerEvent, + onGestureHandlerStateChange + } = this.propsRef.current; + const event = this.transformEventData(nativeEvent); + invokeNullableMethod(onGestureHandlerEvent, event); + + if (this.lastSentState !== event.nativeEvent.state) { + this.lastSentState = event.nativeEvent.state; + invokeNullableMethod(onGestureHandlerStateChange, event); + } + }); + + _defineProperty(this, "sync", () => { + const gesture = this.hammer.get(this.name); + if (!gesture) return; + + const enable = (recognizer, inputData) => { + if (!this.config.enabled) { + this.isGestureRunning = false; + this.hasGestureFailed = false; + return false; + } // Prevent events before the system is ready. + + + if (!inputData || !recognizer.options || typeof inputData.maxPointers === 'undefined') { + return this.shouldEnableGestureOnSetup; + } + + if (this.hasGestureFailed) { + return false; + } + + if (!this.isDiscrete) { + if (this.isGestureRunning) { + return true; + } // The built-in hammer.js "waitFor" doesn't work across multiple views. + // Only process if there are views to wait for. + + + this._stillWaiting = this._getPendingGestures(); // This gesture should continue waiting. + + if (this._stillWaiting.length) { + // Check to see if one of the gestures you're waiting for has started. + // If it has then the gesture should fail. + for (const gesture of this._stillWaiting) { + // When the target gesture has started, this gesture must force fail. + if (!gesture.isDiscrete && gesture.isGestureRunning) { + this.hasGestureFailed = true; + this.isGestureRunning = false; + return false; + } + } // This gesture shouldn't start until the others have finished. + + + return false; + } + } // Use default behaviour + + + if (!this.hasCustomActivationCriteria) { + return true; + } + + const deltaRotation = this.initialRotation == null ? 0 : inputData.rotation - this.initialRotation; // @ts-ignore FIXME(TS) + + const { + success, + failed + } = this.isGestureEnabledForEvent(this.getConfig(), recognizer, { ...inputData, + deltaRotation + }); + + if (failed) { + this.simulateCancelEvent(inputData); + this.hasGestureFailed = true; + } + + return success; + }; + + const params = this.getHammerConfig(); // @ts-ignore FIXME(TS) + + gesture.set({ ...params, + enable + }); + }); + + this.gestureInstance = gestureInstances++; + this.hasCustomActivationCriteria = false; + } + + getConfig() { + return this.config; + } + + onWaitingEnded(_gesture) {} + + removePendingGesture(id) { + delete this.pendingGestures[id]; + } + + addPendingGesture(gesture) { + this.pendingGestures[gesture.id] = gesture; + } + + isGestureEnabledForEvent(_config, _recognizer, _event) { + return { + success: true + }; + } + + get NativeGestureClass() { + throw new Error('Must override GestureHandler.NativeGestureClass'); + } + + updateHasCustomActivationCriteria(_config) { + return true; + } + + updateGestureConfig({ + enabled = true, + ...props + }) { + this.clearSelfAsPending(); + this.config = ensureConfig({ + enabled, + ...props + }); + this.hasCustomActivationCriteria = this.updateHasCustomActivationCriteria(this.config); + + if (Array.isArray(this.config.waitFor)) { + for (const gesture of this.config.waitFor) { + gesture.addPendingGesture(this); + } + } + + if (this.hammer) { + this.sync(); + } + + return this.config; + } + + getState(type) { + // @ts-ignore TODO(TS) check if this is needed + if (type == 0) { + return 0; + } + + return EventMap[type]; + } + + transformEventData(event) { + const { + eventType, + maxPointers: numberOfPointers + } = event; // const direction = DirectionMap[ev.direction]; + + const changedTouch = event.changedPointers[0]; + const pointerInside = this.isPointInView({ + x: changedTouch.clientX, + y: changedTouch.clientY + }); // TODO(TS) Remove cast after https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50966 is merged. + + const state = this.getState(eventType); + + if (state !== this.previousState) { + this.oldState = this.previousState; + this.previousState = state; + } + + return { + nativeEvent: { + numberOfPointers, + state, + pointerInside, + ...this.transformNativeEvent(event), + // onHandlerStateChange only + handlerTag: this.handlerTag, + target: this.ref, + oldState: this.oldState + }, + timeStamp: Date.now() + }; + } + + transformNativeEvent(_event) { + return {}; + } + + cancelPendingGestures(event) { + for (const gesture of Object.values(this.pendingGestures)) { + if (gesture && gesture.isGestureRunning) { + gesture.hasGestureFailed = true; + gesture.cancelEvent(event); + } + } + } + + notifyPendingGestures() { + for (const gesture of Object.values(this.pendingGestures)) { + if (gesture) { + gesture.onWaitingEnded(this); + } + } + } // FIXME event is undefined in runtime when firstly invoked (see Draggable example), check other functions taking event as input + + + onGestureEnded(event) { + this.isGestureRunning = false; + this.cancelPendingGestures(event); + } + + forceInvalidate(event) { + if (this.isGestureRunning) { + this.hasGestureFailed = true; + this.cancelEvent(event); + } + } + + cancelEvent(event) { + this.notifyPendingGestures(); + this.sendEvent({ ...event, + eventType: Hammer.INPUT_CANCEL, + isFinal: true + }); + this.onGestureEnded(event); + } + + onRawEvent({ + isFirst + }) { + if (isFirst) { + this.hasGestureFailed = false; + } + } + + setView(ref, propsRef) { + if (ref == null) { + this.destroy(); + this.view = null; + return; + } + + this.propsRef = propsRef; + this.ref = ref; + this.view = findNodeHandle(ref); + this.hammer = new Hammer.Manager(this.view); + this.oldState = State.UNDETERMINED; + this.previousState = State.UNDETERMINED; + this.lastSentState = null; + const { + NativeGestureClass + } = this; // @ts-ignore TODO(TS) + + const gesture = new NativeGestureClass(this.getHammerConfig()); + this.hammer.add(gesture); + this.hammer.on('hammer.input', ev => { + if (!this.config.enabled) { + this.hasGestureFailed = false; + this.isGestureRunning = false; + return; + } + + this.onRawEvent(ev); // TODO: Bacon: Check against something other than null + // The isFirst value is not called when the first rotation is calculated. + + if (this.initialRotation === null && ev.rotation !== 0) { + this.initialRotation = ev.rotation; + } + + if (ev.isFinal) { + // in favor of a willFail otherwise the last frame of the gesture will be captured. + setTimeout(() => { + this.initialRotation = null; + this.hasGestureFailed = false; + }); + } + }); + this.setupEvents(); + this.sync(); + } + + setupEvents() { + // TODO(TS) Hammer types aren't exactly that what we get in runtime + if (!this.isDiscrete) { + this.hammer.on(`${this.name}start`, event => this.onStart(event)); + this.hammer.on(`${this.name}end ${this.name}cancel`, event => { + this.onGestureEnded(event); + }); + } + + this.hammer.on(this.name, ev => this.onGestureActivated(ev)); // TODO(TS) remove cast after https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50438 is merged + } + + onStart({ + deltaX, + deltaY, + rotation + }) { + // Reset the state for the next gesture + this.oldState = State.UNDETERMINED; + this.previousState = State.UNDETERMINED; + this.lastSentState = null; + this.isGestureRunning = true; + this.__initialX = deltaX; + this.__initialY = deltaY; + this.initialRotation = rotation; + } + + onGestureActivated(ev) { + this.sendEvent(ev); + } + + onSuccess() {} + + _getPendingGestures() { + if (Array.isArray(this.config.waitFor) && this.config.waitFor.length) { + // Get the list of gestures that this gesture is still waiting for. + // Use `=== false` in case a ref that isn't a gesture handler is used. + const stillWaiting = this.config.waitFor.filter(({ + hasGestureFailed + }) => hasGestureFailed === false); + return stillWaiting; + } + + return []; + } + + getHammerConfig() { + const pointers = this.config.minPointers === this.config.maxPointers ? this.config.minPointers : 0; + return { + pointers + }; + } + + simulateCancelEvent(_inputData) {} + +} // TODO(TS) investigate this method +// Used for sending data to a callback or AnimatedEvent + + +function invokeNullableMethod(method, event) { + if (method) { + if (typeof method === 'function') { + method(event); + } else { + // For use with reanimated's AnimatedEvent + if ('__getHandler' in method && typeof method.__getHandler === 'function') { + const handler = method.__getHandler(); + + invokeNullableMethod(handler, event); + } else { + if ('__nodeConfig' in method) { + const { + argMapping + } = method.__nodeConfig; + + if (Array.isArray(argMapping)) { + for (const [index, [key, value]] of argMapping.entries()) { + if (key in event.nativeEvent) { + // @ts-ignore fix method type + const nativeValue = event.nativeEvent[key]; + + if (value && value.setValue) { + // Reanimated API + value.setValue(nativeValue); + } else { + // RN Animated API + method.__nodeConfig.argMapping[index] = [key, nativeValue]; + } + } + } + } + } + } + } + } +} // Validate the props + + +function ensureConfig(config) { + const props = { ...config + }; // TODO(TS) We use ! to assert that if property is present then value is not empty (null, undefined) + + if ('minDist' in config) { + props.minDist = config.minDist; + props.minDistSq = props.minDist * props.minDist; + } + + if ('minVelocity' in config) { + props.minVelocity = config.minVelocity; + props.minVelocitySq = props.minVelocity * props.minVelocity; + } + + if ('maxDist' in config) { + props.maxDist = config.maxDist; + props.maxDistSq = config.maxDist * config.maxDist; + } + + if ('waitFor' in config) { + props.waitFor = asArray(config.waitFor).map(({ + handlerTag + }) => NodeManager.getHandler(handlerTag)).filter(v => v); + } else { + props.waitFor = null; + } + + const configProps = ['minPointers', 'maxPointers', 'minDist', 'maxDist', 'maxDistSq', 'minVelocitySq', 'minDistSq', 'minVelocity', 'failOffsetXStart', 'failOffsetYStart', 'failOffsetXEnd', 'failOffsetYEnd', 'activeOffsetXStart', 'activeOffsetXEnd', 'activeOffsetYStart', 'activeOffsetYEnd']; + configProps.forEach(prop => { + if (typeof props[prop] === 'undefined') { + props[prop] = Number.NaN; + } + }); + return props; // TODO(TS) how to convince TS that props are filled? +} + +function asArray(value) { + // TODO(TS) use config.waitFor type + return value == null ? [] : Array.isArray(value) ? value : [value]; +} + +export default GestureHandler; +//# sourceMappingURL=GestureHandler.js.map \ No newline at end of file diff --git a/lib/module/web/GestureHandler.js.map b/lib/module/web/GestureHandler.js.map new file mode 100644 index 0000000000..85813d529f --- /dev/null +++ b/lib/module/web/GestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["GestureHandler.ts"],"names":["Hammer","findNodeHandle","State","EventMap","NodeManager","gestureInstances","GestureHandler","id","name","gestureInstance","isDiscrete","shouldEnableGestureOnSetup","Error","constructor","UNDETERMINED","Array","isArray","config","waitFor","gesture","removePendingGesture","clearSelfAsPending","hammer","stop","destroy","x","y","rect","view","getBoundingClientRect","pointerInside","left","right","top","bottom","nativeEvent","onGestureHandlerEvent","onGestureHandlerStateChange","propsRef","current","event","transformEventData","invokeNullableMethod","lastSentState","state","get","enable","recognizer","inputData","enabled","isGestureRunning","hasGestureFailed","options","maxPointers","_stillWaiting","_getPendingGestures","length","hasCustomActivationCriteria","deltaRotation","initialRotation","rotation","success","failed","isGestureEnabledForEvent","getConfig","simulateCancelEvent","params","getHammerConfig","set","onWaitingEnded","_gesture","pendingGestures","addPendingGesture","_config","_recognizer","_event","NativeGestureClass","updateHasCustomActivationCriteria","updateGestureConfig","props","ensureConfig","sync","getState","type","eventType","numberOfPointers","changedTouch","changedPointers","isPointInView","clientX","clientY","previousState","oldState","transformNativeEvent","handlerTag","target","ref","timeStamp","Date","now","cancelPendingGestures","Object","values","cancelEvent","notifyPendingGestures","onGestureEnded","forceInvalidate","sendEvent","INPUT_CANCEL","isFinal","onRawEvent","isFirst","setView","Manager","add","on","ev","setTimeout","setupEvents","onStart","onGestureActivated","deltaX","deltaY","__initialX","__initialY","onSuccess","stillWaiting","filter","pointers","minPointers","_inputData","method","__getHandler","handler","argMapping","__nodeConfig","index","key","value","entries","nativeValue","setValue","minDist","minDistSq","minVelocity","minVelocitySq","maxDist","maxDistSq","asArray","map","getHandler","v","configProps","forEach","prop","Number","NaN"],"mappings":";;AAAA;;AACA;AACA,OAAOA,MAAP,MAAmB,gBAAnB;AACA,SAASC,cAAT,QAA+B,cAA/B;AAEA,SAASC,KAAT,QAAsB,UAAtB;AACA,SAASC,QAAT,QAAyB,aAAzB;AACA,OAAO,KAAKC,WAAZ,MAA6B,eAA7B,C,CAEA;;AA0BA,IAAIC,gBAAgB,GAAG,CAAvB;;AAEA,MAAeC,cAAf,CAA8B;AAsBtB,MAAFC,EAAE,GAAG;AACP,WAAQ,GAAE,KAAKC,IAAK,GAAE,KAAKC,eAAgB,EAA3C;AACD;;AAEa,MAAVC,UAAU,GAAG;AACf,WAAO,KAAP;AACD;;AAE6B,MAA1BC,0BAA0B,GAAY;AACxC,UAAM,IAAIC,KAAJ,CAAU,yDAAV,CAAN;AACD;;AAEDC,EAAAA,WAAW,GAAG;AAAA;;AAAA,8CAhCY,KAgCZ;;AAAA,kCA/Be,IA+Bf;;AAAA;;AAAA,8CA7Be,KA6Bf;;AAAA,oCA5B2B,IA4B3B;;AAAA,6CA3B6B,IA2B7B;;AAAA;;AAAA;;AAAA,oCAxBa,EAwBb;;AAAA,2CAvBmBX,KAAK,CAACY,YAuBzB;;AAAA,6CAtBkC,EAsBlC;;AAAA,sCArBYZ,KAAK,CAACY,YAqBlB;;AAAA,2CApBwB,IAoBxB;;AAAA;;AAAA;;AAAA;;AAAA;;AAAA,gDAmCO,MAAM;AACzB,UAAIC,KAAK,CAAC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A,KAAD,CAA3D;AACD;;AAED,eAAepI,cAAf","sourcesContent":["/* eslint-disable eslint-comments/no-unlimited-disable */\n/* eslint-disable */\nimport Hammer from '@egjs/hammerjs';\nimport { findNodeHandle } from 'react-native';\n\nimport { State } from '../State';\nimport { EventMap } from './constants';\nimport * as NodeManager from './NodeManager';\n\n// TODO(TS) Replace with HammerInput if https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50438/files is merged\nexport type HammerInputExt = Omit;\n\nexport type Config = Partial<{\n enabled: boolean;\n minPointers: number;\n maxPointers: number;\n minDist: number;\n minDistSq: number;\n minVelocity: number;\n minVelocitySq: number;\n maxDist: number;\n maxDistSq: number;\n failOffsetXStart: number;\n failOffsetYStart: number;\n failOffsetXEnd: number;\n failOffsetYEnd: number;\n activeOffsetXStart: number;\n activeOffsetXEnd: number;\n activeOffsetYStart: number;\n activeOffsetYEnd: number;\n waitFor: any[] | null;\n}>;\n\ntype NativeEvent = ReturnType;\n\nlet gestureInstances = 0;\n\nabstract class GestureHandler {\n public handlerTag: any;\n public isGestureRunning = false;\n public view: number | null = null;\n protected hasCustomActivationCriteria: boolean;\n protected hasGestureFailed = false;\n protected hammer: HammerManager | null = null;\n protected initialRotation: number | null = null;\n protected __initialX: any;\n protected __initialY: any;\n protected config: Config = {};\n protected previousState: State = State.UNDETERMINED;\n private pendingGestures: Record = {};\n private oldState: State = State.UNDETERMINED;\n private lastSentState: State | null = null;\n private gestureInstance: number;\n private _stillWaiting: any;\n private propsRef: any;\n private ref: any;\n\n abstract get name(): string;\n\n get id() {\n return `${this.name}${this.gestureInstance}`;\n }\n\n get isDiscrete() {\n return false;\n }\n\n get shouldEnableGestureOnSetup(): boolean {\n throw new Error('Must override GestureHandler.shouldEnableGestureOnSetup');\n }\n\n constructor() {\n this.gestureInstance = gestureInstances++;\n this.hasCustomActivationCriteria = false;\n }\n\n getConfig() {\n return this.config;\n }\n\n onWaitingEnded(_gesture: this) {}\n\n removePendingGesture(id: string) {\n delete this.pendingGestures[id];\n }\n\n addPendingGesture(gesture: this) {\n this.pendingGestures[gesture.id] = gesture;\n }\n\n isGestureEnabledForEvent(\n _config: any,\n _recognizer: any,\n _event: any\n ): { failed?: boolean; success?: boolean } {\n return { success: true };\n }\n\n get NativeGestureClass(): RecognizerStatic {\n throw new Error('Must override GestureHandler.NativeGestureClass');\n }\n\n updateHasCustomActivationCriteria(_config: Config) {\n return true;\n }\n\n clearSelfAsPending = () => {\n if (Array.isArray(this.config.waitFor)) {\n for (const gesture of this.config.waitFor) {\n gesture.removePendingGesture(this.id);\n }\n }\n };\n\n updateGestureConfig({ enabled = true, ...props }) {\n this.clearSelfAsPending();\n\n this.config = ensureConfig({ enabled, ...props });\n this.hasCustomActivationCriteria = this.updateHasCustomActivationCriteria(\n this.config\n );\n if (Array.isArray(this.config.waitFor)) {\n for (const gesture of this.config.waitFor) {\n gesture.addPendingGesture(this);\n }\n }\n\n if (this.hammer) {\n this.sync();\n }\n return this.config;\n }\n\n destroy = () => {\n this.clearSelfAsPending();\n\n if (this.hammer) {\n this.hammer.stop(false);\n this.hammer.destroy();\n }\n this.hammer = null;\n };\n\n isPointInView = ({ x, y }: { x: number; y: number }) => {\n // @ts-ignore FIXME(TS)\n const rect = this.view!.getBoundingClientRect();\n const pointerInside =\n x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;\n return pointerInside;\n };\n\n getState(type: keyof typeof EventMap): State {\n // @ts-ignore TODO(TS) check if this is needed\n if (type == 0) {\n return 0;\n }\n return EventMap[type];\n }\n\n transformEventData(event: HammerInputExt) {\n const { eventType, maxPointers: numberOfPointers } = event;\n // const direction = DirectionMap[ev.direction];\n const changedTouch = event.changedPointers[0];\n const pointerInside = this.isPointInView({\n x: changedTouch.clientX,\n y: changedTouch.clientY,\n });\n\n // TODO(TS) Remove cast after https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50966 is merged.\n const state = this.getState(eventType as 1 | 2 | 4 | 8);\n if (state !== this.previousState) {\n this.oldState = this.previousState;\n this.previousState = state;\n }\n\n return {\n nativeEvent: {\n numberOfPointers,\n state,\n pointerInside,\n ...this.transformNativeEvent(event),\n // onHandlerStateChange only\n handlerTag: this.handlerTag,\n target: this.ref,\n oldState: this.oldState,\n },\n timeStamp: Date.now(),\n };\n }\n\n transformNativeEvent(_event: HammerInputExt) {\n return {};\n }\n\n sendEvent = (nativeEvent: HammerInputExt) => {\n const {\n onGestureHandlerEvent,\n onGestureHandlerStateChange,\n } = this.propsRef.current;\n\n const event = this.transformEventData(nativeEvent);\n\n invokeNullableMethod(onGestureHandlerEvent, event);\n if (this.lastSentState !== event.nativeEvent.state) {\n this.lastSentState = event.nativeEvent.state as State;\n invokeNullableMethod(onGestureHandlerStateChange, event);\n }\n };\n\n cancelPendingGestures(event: HammerInputExt) {\n for (const gesture of Object.values(this.pendingGestures)) {\n if (gesture && gesture.isGestureRunning) {\n gesture.hasGestureFailed = true;\n gesture.cancelEvent(event);\n }\n }\n }\n\n notifyPendingGestures() {\n for (const gesture of Object.values(this.pendingGestures)) {\n if (gesture) {\n gesture.onWaitingEnded(this);\n }\n }\n }\n\n // FIXME event is undefined in runtime when firstly invoked (see Draggable example), check other functions taking event as input\n onGestureEnded(event: HammerInputExt) {\n this.isGestureRunning = false;\n this.cancelPendingGestures(event);\n }\n\n forceInvalidate(event: HammerInputExt) {\n if (this.isGestureRunning) {\n this.hasGestureFailed = true;\n this.cancelEvent(event);\n }\n }\n\n cancelEvent(event: HammerInputExt) {\n this.notifyPendingGestures();\n this.sendEvent({\n ...event,\n eventType: Hammer.INPUT_CANCEL,\n isFinal: true,\n });\n this.onGestureEnded(event);\n }\n\n onRawEvent({ isFirst }: HammerInputExt) {\n if (isFirst) {\n this.hasGestureFailed = false;\n }\n }\n\n setView(ref: Parameters['0'], propsRef: any) {\n if (ref == null) {\n this.destroy();\n this.view = null;\n return;\n }\n\n this.propsRef = propsRef;\n this.ref = ref;\n\n this.view = findNodeHandle(ref);\n this.hammer = new Hammer.Manager(this.view as any);\n\n this.oldState = State.UNDETERMINED;\n this.previousState = State.UNDETERMINED;\n this.lastSentState = null;\n\n const { NativeGestureClass } = this;\n // @ts-ignore TODO(TS)\n const gesture = new NativeGestureClass(this.getHammerConfig());\n this.hammer.add(gesture);\n\n this.hammer.on('hammer.input', (ev: HammerInput) => {\n if (!this.config.enabled) {\n this.hasGestureFailed = false;\n this.isGestureRunning = false;\n return;\n }\n\n this.onRawEvent((ev as unknown) as HammerInputExt);\n\n // TODO: Bacon: Check against something other than null\n // The isFirst value is not called when the first rotation is calculated.\n if (this.initialRotation === null && ev.rotation !== 0) {\n this.initialRotation = ev.rotation;\n }\n if (ev.isFinal) {\n // in favor of a willFail otherwise the last frame of the gesture will be captured.\n setTimeout(() => {\n this.initialRotation = null;\n this.hasGestureFailed = false;\n });\n }\n });\n\n this.setupEvents();\n this.sync();\n }\n\n setupEvents() {\n // TODO(TS) Hammer types aren't exactly that what we get in runtime\n if (!this.isDiscrete) {\n this.hammer!.on(`${this.name}start`, (event: HammerInput) =>\n this.onStart((event as unknown) as HammerInputExt)\n );\n this.hammer!.on(\n `${this.name}end ${this.name}cancel`,\n (event: HammerInput) => {\n this.onGestureEnded((event as unknown) as HammerInputExt);\n }\n );\n }\n this.hammer!.on(this.name, (ev: HammerInput) =>\n this.onGestureActivated((ev as unknown) as HammerInputExt)\n ); // TODO(TS) remove cast after https://github.com/DefinitelyTyped/DefinitelyTyped/pull/50438 is merged\n }\n\n onStart({ deltaX, deltaY, rotation }: HammerInputExt) {\n // Reset the state for the next gesture\n this.oldState = State.UNDETERMINED;\n this.previousState = State.UNDETERMINED;\n this.lastSentState = null;\n\n this.isGestureRunning = true;\n this.__initialX = deltaX;\n this.__initialY = deltaY;\n this.initialRotation = rotation;\n }\n\n onGestureActivated(ev: HammerInputExt) {\n this.sendEvent(ev);\n }\n\n onSuccess() {}\n\n _getPendingGestures() {\n if (Array.isArray(this.config.waitFor) && this.config.waitFor.length) {\n // Get the list of gestures that this gesture is still waiting for.\n // Use `=== false` in case a ref that isn't a gesture handler is used.\n const stillWaiting = this.config.waitFor.filter(\n ({ hasGestureFailed }) => hasGestureFailed === false\n );\n return stillWaiting;\n }\n return [];\n }\n\n getHammerConfig() {\n const pointers =\n this.config.minPointers === this.config.maxPointers\n ? this.config.minPointers\n : 0;\n return {\n pointers,\n };\n }\n\n sync = () => {\n const gesture = this.hammer!.get(this.name);\n if (!gesture) return;\n\n const enable = (recognizer: any, inputData: any) => {\n if (!this.config.enabled) {\n this.isGestureRunning = false;\n this.hasGestureFailed = false;\n return false;\n }\n\n // Prevent events before the system is ready.\n if (\n !inputData ||\n !recognizer.options ||\n typeof inputData.maxPointers === 'undefined'\n ) {\n return this.shouldEnableGestureOnSetup;\n }\n\n if (this.hasGestureFailed) {\n return false;\n }\n\n if (!this.isDiscrete) {\n if (this.isGestureRunning) {\n return true;\n }\n // The built-in hammer.js \"waitFor\" doesn't work across multiple views.\n // Only process if there are views to wait for.\n this._stillWaiting = this._getPendingGestures();\n // This gesture should continue waiting.\n if (this._stillWaiting.length) {\n // Check to see if one of the gestures you're waiting for has started.\n // If it has then the gesture should fail.\n for (const gesture of this._stillWaiting) {\n // When the target gesture has started, this gesture must force fail.\n if (!gesture.isDiscrete && gesture.isGestureRunning) {\n this.hasGestureFailed = true;\n this.isGestureRunning = false;\n return false;\n }\n }\n // This gesture shouldn't start until the others have finished.\n return false;\n }\n }\n\n // Use default behaviour\n if (!this.hasCustomActivationCriteria) {\n return true;\n }\n\n const deltaRotation =\n this.initialRotation == null\n ? 0\n : inputData.rotation - this.initialRotation;\n // @ts-ignore FIXME(TS)\n const { success, failed } = this.isGestureEnabledForEvent(\n this.getConfig(),\n recognizer,\n {\n ...inputData,\n deltaRotation,\n }\n );\n\n if (failed) {\n this.simulateCancelEvent(inputData);\n this.hasGestureFailed = true;\n }\n return success;\n };\n\n const params = this.getHammerConfig();\n // @ts-ignore FIXME(TS)\n gesture.set({ ...params, enable });\n };\n\n simulateCancelEvent(_inputData: any) {}\n}\n\n// TODO(TS) investigate this method\n// Used for sending data to a callback or AnimatedEvent\nfunction invokeNullableMethod(\n method:\n | ((event: NativeEvent) => void)\n | { __getHandler: () => (event: NativeEvent) => void }\n | { __nodeConfig: { argMapping: any } },\n event: NativeEvent\n) {\n if (method) {\n if (typeof method === 'function') {\n method(event);\n } else {\n // For use with reanimated's AnimatedEvent\n if (\n '__getHandler' in method &&\n typeof method.__getHandler === 'function'\n ) {\n const handler = method.__getHandler();\n invokeNullableMethod(handler, event);\n } else {\n if ('__nodeConfig' in method) {\n const { argMapping } = method.__nodeConfig;\n if (Array.isArray(argMapping)) {\n for (const [index, [key, value]] of argMapping.entries()) {\n if (key in event.nativeEvent) {\n // @ts-ignore fix method type\n const nativeValue = event.nativeEvent[key];\n if (value && value.setValue) {\n // Reanimated API\n value.setValue(nativeValue);\n } else {\n // RN Animated API\n method.__nodeConfig.argMapping[index] = [key, nativeValue];\n }\n }\n }\n }\n }\n }\n }\n }\n}\n\n// Validate the props\nfunction ensureConfig(config: Config): Required {\n const props = { ...config };\n\n // TODO(TS) We use ! to assert that if property is present then value is not empty (null, undefined)\n if ('minDist' in config) {\n props.minDist = config.minDist;\n props.minDistSq = props.minDist! * props.minDist!;\n }\n if ('minVelocity' in config) {\n props.minVelocity = config.minVelocity;\n props.minVelocitySq = props.minVelocity! * props.minVelocity!;\n }\n if ('maxDist' in config) {\n props.maxDist = config.maxDist;\n props.maxDistSq = config.maxDist! * config.maxDist!;\n }\n if ('waitFor' in config) {\n props.waitFor = asArray(config.waitFor)\n .map(({ handlerTag }: { handlerTag: number }) =>\n NodeManager.getHandler(handlerTag)\n )\n .filter((v) => v);\n } else {\n props.waitFor = null;\n }\n\n const configProps = [\n 'minPointers',\n 'maxPointers',\n 'minDist',\n 'maxDist',\n 'maxDistSq',\n 'minVelocitySq',\n 'minDistSq',\n 'minVelocity',\n 'failOffsetXStart',\n 'failOffsetYStart',\n 'failOffsetXEnd',\n 'failOffsetYEnd',\n 'activeOffsetXStart',\n 'activeOffsetXEnd',\n 'activeOffsetYStart',\n 'activeOffsetYEnd',\n ] as const;\n configProps.forEach((prop: typeof configProps[number]) => {\n if (typeof props[prop] === 'undefined') {\n props[prop] = Number.NaN;\n }\n });\n return props as Required; // TODO(TS) how to convince TS that props are filled?\n}\n\nfunction asArray(value: T | T[]) {\n // TODO(TS) use config.waitFor type\n return value == null ? [] : Array.isArray(value) ? value : [value];\n}\n\nexport default GestureHandler;\n"]} \ No newline at end of file diff --git a/lib/module/web/IndiscreteGestureHandler.js b/lib/module/web/IndiscreteGestureHandler.js new file mode 100644 index 0000000000..404d299dd3 --- /dev/null +++ b/lib/module/web/IndiscreteGestureHandler.js @@ -0,0 +1,44 @@ +import GestureHandler from './GestureHandler'; +/** + * The base class for **Rotation** and **Pinch** gesture handlers. + */ + +class IndiscreteGestureHandler extends GestureHandler { + get shouldEnableGestureOnSetup() { + return false; + } + + updateGestureConfig({ + minPointers = 2, + maxPointers = 2, + ...props + }) { + return super.updateGestureConfig({ + minPointers, + maxPointers, + ...props + }); + } + + isGestureEnabledForEvent({ + minPointers, + maxPointers + }, _recognizer, { + maxPointers: pointerLength + }) { + if (pointerLength > maxPointers) { + return { + failed: true + }; + } + + const validPointerCount = pointerLength >= minPointers; + return { + success: validPointerCount + }; + } + +} + +export default IndiscreteGestureHandler; +//# sourceMappingURL=IndiscreteGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/web/IndiscreteGestureHandler.js.map b/lib/module/web/IndiscreteGestureHandler.js.map new file mode 100644 index 0000000000..e69b58797d --- /dev/null +++ b/lib/module/web/IndiscreteGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["IndiscreteGestureHandler.ts"],"names":["GestureHandler","IndiscreteGestureHandler","shouldEnableGestureOnSetup","updateGestureConfig","minPointers","maxPointers","props","isGestureEnabledForEvent","_recognizer","pointerLength","failed","validPointerCount","success"],"mappings":"AAAA,OAAOA,cAAP,MAA2B,kBAA3B;AAEA;AACA;AACA;;AACA,MAAeC,wBAAf,SAAgDD,cAAhD,CAA+D;AAC/B,MAA1BE,0BAA0B,GAAG;AAC/B,WAAO,KAAP;AACD;;AAEDC,EAAAA,mBAAmB,CAAC;AAAEC,IAAAA,WAAW,GAAG,CAAhB;AAAmBC,IAAAA,WAAW,GAAG,CAAjC;AAAoC,OAAGC;AAAvC,GAAD,EAAiD;AAClE,WAAO,MAAMH,mBAAN,CAA0B;AAC/BC,MAAAA,WAD+B;AAE/BC,MAAAA,WAF+B;AAG/B,SAAGC;AAH4B,KAA1B,CAAP;AAKD;;AAEDC,EAAAA,wBAAwB,CACtB;AAAEH,IAAAA,WAAF;AAAeC,IAAAA;AAAf,GADsB,EAEtBG,WAFsB,EAGtB;AAAEH,IAAAA,WAAW,EAAEI;AAAf,GAHsB,EAItB;AACA,QAAIA,aAAa,GAAGJ,WAApB,EAAiC;AAC/B,aAAO;AAAEK,QAAAA,MAAM,EAAE;AAAV,OAAP;AACD;;AACD,UAAMC,iBAAiB,GAAGF,aAAa,IAAIL,WAA3C;AACA,WAAO;AACLQ,MAAAA,OAAO,EAAED;AADJ,KAAP;AAGD;;AAzB4D;;AA2B/D,eAAeV,wBAAf","sourcesContent":["import GestureHandler from './GestureHandler';\n\n/**\n * The base class for **Rotation** and **Pinch** gesture handlers.\n */\nabstract class IndiscreteGestureHandler extends GestureHandler {\n get shouldEnableGestureOnSetup() {\n return false;\n }\n\n updateGestureConfig({ minPointers = 2, maxPointers = 2, ...props }) {\n return super.updateGestureConfig({\n minPointers,\n maxPointers,\n ...props,\n });\n }\n\n isGestureEnabledForEvent(\n { minPointers, maxPointers }: any,\n _recognizer: any,\n { maxPointers: pointerLength }: any\n ) {\n if (pointerLength > maxPointers) {\n return { failed: true };\n }\n const validPointerCount = pointerLength >= minPointers;\n return {\n success: validPointerCount,\n };\n }\n}\nexport default IndiscreteGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/module/web/LongPressGestureHandler.js b/lib/module/web/LongPressGestureHandler.js new file mode 100644 index 0000000000..4483a495c2 --- /dev/null +++ b/lib/module/web/LongPressGestureHandler.js @@ -0,0 +1,58 @@ +/* eslint-disable eslint-comments/no-unlimited-disable */ + +/* eslint-disable */ +import Hammer from '@egjs/hammerjs'; +import { State } from '../State'; +import PressGestureHandler from './PressGestureHandler'; +import { isnan, isValidNumber } from './utils'; + +class LongPressGestureHandler extends PressGestureHandler { + get minDurationMs() { + // @ts-ignore FIXNE(TS) + return isnan(this.config.minDurationMs) ? 251 : this.config.minDurationMs; + } + + get maxDist() { + // @ts-ignore FIXNE(TS) + return isnan(this.config.maxDist) ? 9 : this.config.maxDist; + } + + updateHasCustomActivationCriteria({ + maxDistSq + }) { + return !isValidNumber(maxDistSq); + } + + getConfig() { + if (!this.hasCustomActivationCriteria) { + // Default config + // If no params have been defined then this config should emulate the native gesture as closely as possible. + return { + shouldCancelWhenOutside: true, + maxDistSq: 10 + }; + } + + return this.config; + } + + getHammerConfig() { + return { ...super.getHammerConfig(), + // threshold: this.maxDist, + time: this.minDurationMs + }; + } + + getState(type) { + return { + [Hammer.INPUT_START]: State.ACTIVE, + [Hammer.INPUT_MOVE]: State.ACTIVE, + [Hammer.INPUT_END]: State.END, + [Hammer.INPUT_CANCEL]: State.FAILED + }[type]; + } + +} + +export default LongPressGestureHandler; +//# sourceMappingURL=LongPressGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/web/LongPressGestureHandler.js.map b/lib/module/web/LongPressGestureHandler.js.map new file mode 100644 index 0000000000..9414082278 --- /dev/null +++ b/lib/module/web/LongPressGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["LongPressGestureHandler.ts"],"names":["Hammer","State","PressGestureHandler","isnan","isValidNumber","LongPressGestureHandler","minDurationMs","config","maxDist","updateHasCustomActivationCriteria","maxDistSq","getConfig","hasCustomActivationCriteria","shouldCancelWhenOutside","getHammerConfig","time","getState","type","INPUT_START","ACTIVE","INPUT_MOVE","INPUT_END","END","INPUT_CANCEL","FAILED"],"mappings":"AAAA;;AAC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AAMD;;AA1CuD;;AA6C1D,eAAeZ,uBAAf","sourcesContent":["/* eslint-disable eslint-comments/no-unlimited-disable */\n/* eslint-disable */\nimport Hammer from '@egjs/hammerjs';\n\nimport { State } from '../State';\nimport PressGestureHandler from './PressGestureHandler';\nimport { isnan, isValidNumber } from './utils';\nimport { Config } from './GestureHandler';\nimport { HammerInputNames } from './constants';\n\nclass LongPressGestureHandler extends PressGestureHandler {\n get minDurationMs(): number {\n // @ts-ignore FIXNE(TS)\n return isnan(this.config.minDurationMs) ? 251 : this.config.minDurationMs;\n }\n\n get maxDist() {\n // @ts-ignore FIXNE(TS)\n return isnan(this.config.maxDist) ? 9 : this.config.maxDist;\n }\n\n updateHasCustomActivationCriteria({ maxDistSq }: Config) {\n return !isValidNumber(maxDistSq);\n }\n\n getConfig() {\n if (!this.hasCustomActivationCriteria) {\n // Default config\n // If no params have been defined then this config should emulate the native gesture as closely as possible.\n return {\n shouldCancelWhenOutside: true,\n maxDistSq: 10,\n };\n }\n return this.config;\n }\n\n getHammerConfig() {\n return {\n ...super.getHammerConfig(),\n // threshold: this.maxDist,\n time: this.minDurationMs,\n };\n }\n\n getState(type: keyof typeof HammerInputNames) {\n return {\n [Hammer.INPUT_START]: State.ACTIVE,\n [Hammer.INPUT_MOVE]: State.ACTIVE,\n [Hammer.INPUT_END]: State.END,\n [Hammer.INPUT_CANCEL]: State.FAILED,\n }[type];\n }\n}\n\nexport default LongPressGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/module/web/NativeViewGestureHandler.js b/lib/module/web/NativeViewGestureHandler.js new file mode 100644 index 0000000000..328509a518 --- /dev/null +++ b/lib/module/web/NativeViewGestureHandler.js @@ -0,0 +1,45 @@ +import DiscreteGestureHandler from './DiscreteGestureHandler'; +import * as NodeManager from './NodeManager'; +import PressGestureHandler from './PressGestureHandler'; +import { TEST_MIN_IF_NOT_NAN, VEC_LEN_SQ } from './utils'; + +class NativeViewGestureHandler extends PressGestureHandler { + onRawEvent(ev) { + super.onRawEvent(ev); + + if (!ev.isFinal) { + // if (this.ref instanceof ScrollView) { + if (TEST_MIN_IF_NOT_NAN(VEC_LEN_SQ({ + x: ev.deltaX, + y: ev.deltaY + }), 10)) { + // @ts-ignore FIXME(TS) config type + if (this.config.disallowInterruption) { + const gestures = Object.values(NodeManager.getNodes()).filter(gesture => { + const { + handlerTag, + view, + isGestureRunning + } = gesture; + return (// Check if this gesture isn't self + handlerTag !== this.handlerTag && // Ensure the gesture needs to be cancelled + isGestureRunning && // ScrollView can cancel discrete gestures like taps and presses + gesture instanceof DiscreteGestureHandler && // Ensure a view exists and is a child of the current view + view && // @ts-ignore FIXME(TS) view type + this.view.contains(view) + ); + }); // Cancel all of the gestures that passed the filter + + for (const gesture of gestures) { + // TODO: Bacon: Send some cached event. + gesture.forceInvalidate(ev); + } + } + } + } + } + +} + +export default NativeViewGestureHandler; +//# sourceMappingURL=NativeViewGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/web/NativeViewGestureHandler.js.map b/lib/module/web/NativeViewGestureHandler.js.map new file mode 100644 index 0000000000..e71fcf62ab --- /dev/null +++ b/lib/module/web/NativeViewGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["NativeViewGestureHandler.ts"],"names":["DiscreteGestureHandler","NodeManager","PressGestureHandler","TEST_MIN_IF_NOT_NAN","VEC_LEN_SQ","NativeViewGestureHandler","onRawEvent","ev","isFinal","x","deltaX","y","deltaY","config","disallowInterruption","gestures","Object","values","getNodes","filter","gesture","handlerTag","view","isGestureRunning","contains","forceInvalidate"],"mappings":"AAAA,OAAOA,sBAAP,MAAmC,0BAAnC;AAEA,OAAO,KAAKC,WAAZ,MAA6B,eAA7B;AACA,OAAOC,mBAAP,MAAgC,uBAAhC;AACA,SAASC,mBAAT,EAA8BC,UAA9B,QAAgD,SAAhD;;AAEA,MAAMC,wBAAN,SAAuCH,mBAAvC,CAA2D;AACzDI,EAAAA,UAAU,CAACC,EAAD,EAAqB;AAC7B,UAAMD,UAAN,CAAiBC,EAAjB;;AACA,QAAI,CAACA,EAAE,CAACC,OAAR,EAAiB;AACf;AACA,UAAIL,mBAAmB,CAACC,UAAU,CAAC;AAAEK,QAAAA,CAAC,EAAEF,EAAE,CAACG,MAAR;AAAgBC,QAAAA,CAAC,EAAEJ,EAAE,CAACK;AAAtB,OAAD,CAAX,EAA6C,EAA7C,CAAvB,EAAyE;AACvE;AACA,YAAI,KAAKC,MAAL,CAAYC,oBAAhB,EAAsC;AACpC,gBAAMC,QAAQ,GAAGC,MAAM,CAACC,MAAP,CAAchB,WAAW,CAACiB,QAAZ,EAAd,EAAsCC,MAAtC,CACdC,OAAD,IAAa;AACX,kBAAM;AAAEC,cAAAA,UAAF;AAAcC,cAAAA,IAAd;AAAoBC,cAAAA;AAApB,gBAAyCH,OAA/C;AACA,mBACE;AACAC,cAAAA,UAAU,KAAK,KAAKA,UAApB,IACA;AACAE,cAAAA,gBAFA,IAGA;AACAH,cAAAA,OAAO,YAAYpB,sBAJnB,IAKA;AACAsB,cAAAA,IANA,IAOA;AACA,mBAAKA,IAAL,CAAUE,QAAV,CAAmBF,IAAnB;AAVF;AAYD,WAfc,CAAjB,CADoC,CAkBpC;;AACA,eAAK,MAAMF,OAAX,IAAsBL,QAAtB,EAAgC;AAC9B;AACAK,YAAAA,OAAO,CAACK,eAAR,CAAwBlB,EAAxB;AACD;AACF;AACF;AACF;AACF;;AAjCwD;;AAoC3D,eAAeF,wBAAf","sourcesContent":["import DiscreteGestureHandler from './DiscreteGestureHandler';\nimport { HammerInputExt } from './GestureHandler';\nimport * as NodeManager from './NodeManager';\nimport PressGestureHandler from './PressGestureHandler';\nimport { TEST_MIN_IF_NOT_NAN, VEC_LEN_SQ } from './utils';\n\nclass NativeViewGestureHandler extends PressGestureHandler {\n onRawEvent(ev: HammerInputExt) {\n super.onRawEvent(ev);\n if (!ev.isFinal) {\n // if (this.ref instanceof ScrollView) {\n if (TEST_MIN_IF_NOT_NAN(VEC_LEN_SQ({ x: ev.deltaX, y: ev.deltaY }), 10)) {\n // @ts-ignore FIXME(TS) config type\n if (this.config.disallowInterruption) {\n const gestures = Object.values(NodeManager.getNodes()).filter(\n (gesture) => {\n const { handlerTag, view, isGestureRunning } = gesture;\n return (\n // Check if this gesture isn't self\n handlerTag !== this.handlerTag &&\n // Ensure the gesture needs to be cancelled\n isGestureRunning &&\n // ScrollView can cancel discrete gestures like taps and presses\n gesture instanceof DiscreteGestureHandler &&\n // Ensure a view exists and is a child of the current view\n view &&\n // @ts-ignore FIXME(TS) view type\n this.view.contains(view)\n );\n }\n );\n // Cancel all of the gestures that passed the filter\n for (const gesture of gestures) {\n // TODO: Bacon: Send some cached event.\n gesture.forceInvalidate(ev);\n }\n }\n }\n }\n }\n}\n\nexport default NativeViewGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/module/web/NodeManager.js b/lib/module/web/NodeManager.js new file mode 100644 index 0000000000..2567ef0f49 --- /dev/null +++ b/lib/module/web/NodeManager.js @@ -0,0 +1,30 @@ +const gestures = {}; +export function getHandler(tag) { + if (tag in gestures) return gestures[tag]; + throw new Error(`No handler for tag ${tag}`); +} +export function createGestureHandler(handlerTag, handler) { + if (handlerTag in gestures) { + throw new Error(`Handler with tag ${handlerTag} already exists`); + } + + gestures[handlerTag] = handler; // @ts-ignore no types for web handlers yet + + gestures[handlerTag].handlerTag = handlerTag; +} +export function dropGestureHandler(handlerTag) { + // Since React 18, there are cases where componentWillUnmount gets called twice in a row + // so skip this if the tag was already removed. + if (!(handlerTag in gestures)) { + return; + } + + getHandler(handlerTag).destroy(); // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + + delete gestures[handlerTag]; +} +export function getNodes() { + return { ...gestures + }; +} +//# sourceMappingURL=NodeManager.js.map \ No newline at end of file diff --git a/lib/module/web/NodeManager.js.map b/lib/module/web/NodeManager.js.map new file mode 100644 index 0000000000..01de22bd9e --- /dev/null +++ b/lib/module/web/NodeManager.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["NodeManager.ts"],"names":["gestures","getHandler","tag","Error","createGestureHandler","handlerTag","handler","dropGestureHandler","destroy","getNodes"],"mappings":"AAGA,MAAMA,QAAgE,GAAG,EAAzE;AAEA,OAAO,SAASC,UAAT,CAAoBC,GAApB,EAAiC;AACtC,MAAIA,GAAG,IAAIF,QAAX,EAAqB,OAAOA,QAAQ,CAACE,GAAD,CAAf;AAErB,QAAM,IAAIC,KAAJ,CAAW,sBAAqBD,GAAI,EAApC,CAAN;AACD;AAED,OAAO,SAASE,oBAAT,CACLC,UADK,EAELC,OAFK,EAGL;AACA,MAAID,UAAU,IAAIL,QAAlB,EAA4B;AAC1B,UAAM,IAAIG,KAAJ,CAAW,oBAAmBE,UAAW,iBAAzC,CAAN;AACD;;AACDL,EAAAA,QAAQ,CAACK,UAAD,CAAR,GAAuBC,OAAvB,CAJA,CAKA;;AACAN,EAAAA,QAAQ,CAACK,UAAD,CAAR,CAAqBA,UAArB,GAAkCA,UAAlC;AACD;AAED,OAAO,SAASE,kBAAT,CAA4BF,UAA5B,EAAgD;AACrD;AACA;AACA,MAAI,EAAEA,UAAU,IAAIL,QAAhB,CAAJ,EAA+B;AAC7B;AACD;;AACDC,EAAAA,UAAU,CAACI,UAAD,CAAV,CAAuBG,OAAvB,GANqD,CAOrD;;AACA,SAAOR,QAAQ,CAACK,UAAD,CAAf;AACD;AAED,OAAO,SAASI,QAAT,GAAoB;AACzB,SAAO,EAAE,GAAGT;AAAL,GAAP;AACD","sourcesContent":["import { ValueOf } from '../typeUtils';\nimport { Gestures } from '../RNGestureHandlerModule.web';\n\nconst gestures: Record>> = {};\n\nexport function getHandler(tag: number) {\n if (tag in gestures) return gestures[tag];\n\n throw new Error(`No handler for tag ${tag}`);\n}\n\nexport function createGestureHandler(\n handlerTag: number,\n handler: InstanceType>\n) {\n if (handlerTag in gestures) {\n throw new Error(`Handler with tag ${handlerTag} already exists`);\n }\n gestures[handlerTag] = handler;\n // @ts-ignore no types for web handlers yet\n gestures[handlerTag].handlerTag = handlerTag;\n}\n\nexport function dropGestureHandler(handlerTag: number) {\n // Since React 18, there are cases where componentWillUnmount gets called twice in a row\n // so skip this if the tag was already removed.\n if (!(handlerTag in gestures)) {\n return;\n }\n getHandler(handlerTag).destroy();\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete gestures[handlerTag];\n}\n\nexport function getNodes() {\n return { ...gestures };\n}\n"]} \ No newline at end of file diff --git a/lib/module/web/PanGestureHandler.js b/lib/module/web/PanGestureHandler.js new file mode 100644 index 0000000000..db0bf7f85d --- /dev/null +++ b/lib/module/web/PanGestureHandler.js @@ -0,0 +1,175 @@ +import Hammer from '@egjs/hammerjs'; +import { MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD, MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD } from './constants'; +import DraggingGestureHandler from './DraggingGestureHandler'; +import { isValidNumber, isnan, TEST_MIN_IF_NOT_NAN, VEC_LEN_SQ } from './utils'; +import { State } from '../State'; + +class PanGestureHandler extends DraggingGestureHandler { + get name() { + return 'pan'; + } + + get NativeGestureClass() { + return Hammer.Pan; + } + + getHammerConfig() { + return { ...super.getHammerConfig(), + direction: this.getDirection() + }; + } + + getState(type) { + const nextState = super.getState(type); // Ensure that the first state sent is `BEGAN` and not `ACTIVE` + + if (this.previousState === State.UNDETERMINED && nextState === State.ACTIVE) { + return State.BEGAN; + } + + return nextState; + } + + getDirection() { + const config = this.getConfig(); + const { + activeOffsetXStart, + activeOffsetXEnd, + activeOffsetYStart, + activeOffsetYEnd, + minDist + } = config; + let directions = []; + let horizontalDirections = []; + + if (!isnan(minDist)) { + return Hammer.DIRECTION_ALL; + } + + if (!isnan(activeOffsetXStart)) horizontalDirections.push(Hammer.DIRECTION_LEFT); + if (!isnan(activeOffsetXEnd)) horizontalDirections.push(Hammer.DIRECTION_RIGHT); + if (horizontalDirections.length === 2) horizontalDirections = [Hammer.DIRECTION_HORIZONTAL]; + directions = directions.concat(horizontalDirections); + let verticalDirections = []; + if (!isnan(activeOffsetYStart)) verticalDirections.push(Hammer.DIRECTION_UP); + if (!isnan(activeOffsetYEnd)) verticalDirections.push(Hammer.DIRECTION_DOWN); + if (verticalDirections.length === 2) verticalDirections = [Hammer.DIRECTION_VERTICAL]; + directions = directions.concat(verticalDirections); + + if (!directions.length) { + return Hammer.DIRECTION_NONE; + } + + if (directions[0] === Hammer.DIRECTION_HORIZONTAL && directions[1] === Hammer.DIRECTION_VERTICAL) { + return Hammer.DIRECTION_ALL; + } + + if (horizontalDirections.length && verticalDirections.length) { + return Hammer.DIRECTION_ALL; + } + + return directions[0]; + } + + getConfig() { + if (!this.hasCustomActivationCriteria) { + // Default config + // If no params have been defined then this config should emulate the native gesture as closely as possible. + return { + minDistSq: 10 + }; + } + + return this.config; + } + + shouldFailUnderCustomCriteria({ + deltaX, + deltaY + }, criteria) { + return !isnan(criteria.failOffsetXStart) && deltaX < criteria.failOffsetXStart || !isnan(criteria.failOffsetXEnd) && deltaX > criteria.failOffsetXEnd || !isnan(criteria.failOffsetYStart) && deltaY < criteria.failOffsetYStart || !isnan(criteria.failOffsetYEnd) && deltaY > criteria.failOffsetYEnd; + } + + shouldActivateUnderCustomCriteria({ + deltaX, + deltaY, + velocity + }, criteria) { + return !isnan(criteria.activeOffsetXStart) && deltaX < criteria.activeOffsetXStart || !isnan(criteria.activeOffsetXEnd) && deltaX > criteria.activeOffsetXEnd || !isnan(criteria.activeOffsetYStart) && deltaY < criteria.activeOffsetYStart || !isnan(criteria.activeOffsetYEnd) && deltaY > criteria.activeOffsetYEnd || TEST_MIN_IF_NOT_NAN(VEC_LEN_SQ({ + x: deltaX, + y: deltaY + }), criteria.minDistSq) || TEST_MIN_IF_NOT_NAN(velocity.x, criteria.minVelocityX) || TEST_MIN_IF_NOT_NAN(velocity.y, criteria.minVelocityY) || TEST_MIN_IF_NOT_NAN(VEC_LEN_SQ(velocity), criteria.minVelocitySq); + } + + shouldMultiFingerPanFail({ + pointerLength, + scale, + deltaRotation + }) { + if (pointerLength <= 1) { + return false; + } // Test if the pan had too much pinching or rotating. + + + const deltaScale = Math.abs(scale - 1); + const absDeltaRotation = Math.abs(deltaRotation); + + if (deltaScale > MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD) { + // > If the threshold doesn't seem right. + // You can log the value which it failed at here: + return true; + } + + if (absDeltaRotation > MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD) { + // > If the threshold doesn't seem right. + // You can log the value which it failed at here: + return true; + } + + return false; + } + + updateHasCustomActivationCriteria(criteria) { + return isValidNumber(criteria.minDistSq) || isValidNumber(criteria.minVelocityX) || isValidNumber(criteria.minVelocityY) || isValidNumber(criteria.minVelocitySq) || isValidNumber(criteria.activeOffsetXStart) || isValidNumber(criteria.activeOffsetXEnd) || isValidNumber(criteria.activeOffsetYStart) || isValidNumber(criteria.activeOffsetYEnd); + } + + isGestureEnabledForEvent(props, _recognizer, inputData) { + if (this.shouldFailUnderCustomCriteria(inputData, props)) { + return { + failed: true + }; + } + + const velocity = { + x: inputData.velocityX, + y: inputData.velocityY + }; + + if (this.hasCustomActivationCriteria && this.shouldActivateUnderCustomCriteria({ + deltaX: inputData.deltaX, + deltaY: inputData.deltaY, + velocity + }, props)) { + if (this.shouldMultiFingerPanFail({ + pointerLength: inputData.maxPointers, + scale: inputData.scale, + deltaRotation: inputData.deltaRotation + })) { + return { + failed: true + }; + } + + return { + success: true + }; + } + + return { + success: false + }; + } + +} + +export default PanGestureHandler; +//# sourceMappingURL=PanGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/web/PanGestureHandler.js.map b/lib/module/web/PanGestureHandler.js.map new file mode 100644 index 0000000000..cb1568eea4 --- /dev/null +++ b/lib/module/web/PanGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PanGestureHandler.ts"],"names":["Hammer","MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD","MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD","DraggingGestureHandler","isValidNumber","isnan","TEST_MIN_IF_NOT_NAN","VEC_LEN_SQ","State","PanGestureHandler","name","NativeGestureClass","Pan","getHammerConfig","direction","getDirection","getState","type","nextState","previousState","UNDETERMINED","ACTIVE","BEGAN","config","getConfig","activeOffsetXStart","activeOffsetXEnd","activeOffsetYStart","activeOffsetYEnd","minDist","directions","horizontalDirections","DIRECTION_ALL","push","DIRECTION_LEFT","DIRECTION_RIGHT","length","DIRECTION_HORIZONTAL","concat","verticalDirections","DIRECTION_UP","DIRECTION_DOWN","DIRECTION_VERTICAL","DIRECTION_NONE","hasCustomActivationCriteria","minDistSq","shouldFailUnderCustomCriteria","deltaX","deltaY","criteria","failOffsetXStart","failOffsetXEnd","failOffsetYStart","failOffsetYEnd","shouldActivateUnderCustomCriteria","velocity","x","y","minVelocityX","minVelocityY","minVelocitySq","shouldMultiFingerPanFail","pointerLength","scale","deltaRotation","deltaScale","Math","abs","absDeltaRotation","updateHasCustomActivationCriteria","isGestureEnabledForEvent","props","_recognizer","inputData","failed","velocityX","velocityY","maxPointers","success"],"mappings":"AAAA,OAAOA,MAAP,MAAmB,gBAAnB;AAEA,SAEEC,oCAFF,EAGEC,uCAHF,QAIO,aAJP;AAKA,OAAOC,sBAAP,MAAmC,0BAAnC;AACA,SAASC,aAAT,EAAwBC,KAAxB,EAA+BC,mBAA/B,EAAoDC,UAApD,QAAsE,SAAtE;AACA,SAASC,KAAT,QAAsB,UAAtB;;AAGA,MAAMC,iBAAN,SAAgCN,sBAAhC,CAAuD;AAC7C,MAAJO,IAAI,GAAG;AACT,WAAO,KAAP;AACD;;AAEqB,MAAlBC,kBAAkB,GAAG;AACvB,WAAOX,MAAM,CAACY,GAAd;AACD;;AAEDC,EAAAA,eAAe,GAAG;AAChB,WAAO,EACL,GAAG,MAAMA,eAAN,EADE;AAELC,MAAAA,SAAS,EAAE,KAAKC,YAAL;AAFN,KAAP;AAID;;AAEDC,EAAAA,QAAQ,CAACC,IAAD,EAA8B;AACpC,UAAMC,SAAS,GAAG,MAAMF,QAAN,CAAeC,IAAf,CAAl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KAFW;AAG5BC,QAAAA,aAAa,EAAES,SAAS,CAACT;AAHG,OAA9B,CADF,EAME;AACA,eAAO;AACLU,UAAAA,MAAM,EAAE;AADH,SAAP;AAGD;;AACD,aAAO;AAAEI,QAAAA,OAAO,EAAE;AAAX,OAAP;AACD;;AACD,WAAO;AAAEA,MAAAA,OAAO,EAAE;AAAX,KAAP;AACD;;AA5MoD;;AA+MvD,eAAerE,iBAAf","sourcesContent":["import Hammer from '@egjs/hammerjs';\n\nimport {\n EventMap,\n MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD,\n MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD,\n} from './constants';\nimport DraggingGestureHandler from './DraggingGestureHandler';\nimport { isValidNumber, isnan, TEST_MIN_IF_NOT_NAN, VEC_LEN_SQ } from './utils';\nimport { State } from '../State';\n\nimport { Config, HammerInputExt } from './GestureHandler';\nclass PanGestureHandler extends DraggingGestureHandler {\n get name() {\n return 'pan';\n }\n\n get NativeGestureClass() {\n return Hammer.Pan;\n }\n\n getHammerConfig() {\n return {\n ...super.getHammerConfig(),\n direction: this.getDirection(),\n };\n }\n\n getState(type: keyof typeof EventMap) {\n const nextState = super.getState(type);\n // Ensure that the first state sent is `BEGAN` and not `ACTIVE`\n if (\n this.previousState === State.UNDETERMINED &&\n nextState === State.ACTIVE\n ) {\n return State.BEGAN;\n }\n return nextState;\n }\n\n getDirection() {\n const config = this.getConfig();\n const {\n activeOffsetXStart,\n activeOffsetXEnd,\n activeOffsetYStart,\n activeOffsetYEnd,\n minDist,\n } = config;\n let directions: number[] = [];\n let horizontalDirections = [];\n\n if (!isnan(minDist)) {\n return Hammer.DIRECTION_ALL;\n }\n\n if (!isnan(activeOffsetXStart))\n horizontalDirections.push(Hammer.DIRECTION_LEFT);\n if (!isnan(activeOffsetXEnd))\n horizontalDirections.push(Hammer.DIRECTION_RIGHT);\n if (horizontalDirections.length === 2)\n horizontalDirections = [Hammer.DIRECTION_HORIZONTAL];\n\n directions = directions.concat(horizontalDirections);\n let verticalDirections = [];\n\n if (!isnan(activeOffsetYStart))\n verticalDirections.push(Hammer.DIRECTION_UP);\n if (!isnan(activeOffsetYEnd))\n verticalDirections.push(Hammer.DIRECTION_DOWN);\n\n if (verticalDirections.length === 2)\n verticalDirections = [Hammer.DIRECTION_VERTICAL];\n\n directions = directions.concat(verticalDirections);\n\n if (!directions.length) {\n return Hammer.DIRECTION_NONE;\n }\n if (\n directions[0] === Hammer.DIRECTION_HORIZONTAL &&\n directions[1] === Hammer.DIRECTION_VERTICAL\n ) {\n return Hammer.DIRECTION_ALL;\n }\n if (horizontalDirections.length && verticalDirections.length) {\n return Hammer.DIRECTION_ALL;\n }\n\n return directions[0];\n }\n\n getConfig() {\n if (!this.hasCustomActivationCriteria) {\n // Default config\n // If no params have been defined then this config should emulate the native gesture as closely as possible.\n return {\n minDistSq: 10,\n };\n }\n return this.config;\n }\n\n shouldFailUnderCustomCriteria(\n { deltaX, deltaY }: HammerInputExt,\n criteria: any\n ) {\n return (\n (!isnan(criteria.failOffsetXStart) &&\n deltaX < criteria.failOffsetXStart) ||\n (!isnan(criteria.failOffsetXEnd) && deltaX > criteria.failOffsetXEnd) ||\n (!isnan(criteria.failOffsetYStart) &&\n deltaY < criteria.failOffsetYStart) ||\n (!isnan(criteria.failOffsetYEnd) && deltaY > criteria.failOffsetYEnd)\n );\n }\n\n shouldActivateUnderCustomCriteria(\n { deltaX, deltaY, velocity }: any,\n criteria: any\n ) {\n return (\n (!isnan(criteria.activeOffsetXStart) &&\n deltaX < criteria.activeOffsetXStart) ||\n (!isnan(criteria.activeOffsetXEnd) &&\n deltaX > criteria.activeOffsetXEnd) ||\n (!isnan(criteria.activeOffsetYStart) &&\n deltaY < criteria.activeOffsetYStart) ||\n (!isnan(criteria.activeOffsetYEnd) &&\n deltaY > criteria.activeOffsetYEnd) ||\n TEST_MIN_IF_NOT_NAN(\n VEC_LEN_SQ({ x: deltaX, y: deltaY }),\n criteria.minDistSq\n ) ||\n TEST_MIN_IF_NOT_NAN(velocity.x, criteria.minVelocityX) ||\n TEST_MIN_IF_NOT_NAN(velocity.y, criteria.minVelocityY) ||\n TEST_MIN_IF_NOT_NAN(VEC_LEN_SQ(velocity), criteria.minVelocitySq)\n );\n }\n\n shouldMultiFingerPanFail({\n pointerLength,\n scale,\n deltaRotation,\n }: {\n deltaRotation: number;\n pointerLength: number;\n scale: number;\n }) {\n if (pointerLength <= 1) {\n return false;\n }\n\n // Test if the pan had too much pinching or rotating.\n const deltaScale = Math.abs(scale - 1);\n const absDeltaRotation = Math.abs(deltaRotation);\n if (deltaScale > MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD) {\n // > If the threshold doesn't seem right.\n // You can log the value which it failed at here:\n return true;\n }\n if (absDeltaRotation > MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD) {\n // > If the threshold doesn't seem right.\n // You can log the value which it failed at here:\n return true;\n }\n\n return false;\n }\n\n updateHasCustomActivationCriteria(\n criteria: Config & { minVelocityX?: number; minVelocityY?: number }\n ) {\n return (\n isValidNumber(criteria.minDistSq) ||\n isValidNumber(criteria.minVelocityX) ||\n isValidNumber(criteria.minVelocityY) ||\n isValidNumber(criteria.minVelocitySq) ||\n isValidNumber(criteria.activeOffsetXStart) ||\n isValidNumber(criteria.activeOffsetXEnd) ||\n isValidNumber(criteria.activeOffsetYStart) ||\n isValidNumber(criteria.activeOffsetYEnd)\n );\n }\n\n isGestureEnabledForEvent(\n props: any,\n _recognizer: any,\n inputData: HammerInputExt & { deltaRotation: number }\n ) {\n if (this.shouldFailUnderCustomCriteria(inputData, props)) {\n return { failed: true };\n }\n\n const velocity = { x: inputData.velocityX, y: inputData.velocityY };\n if (\n this.hasCustomActivationCriteria &&\n this.shouldActivateUnderCustomCriteria(\n { deltaX: inputData.deltaX, deltaY: inputData.deltaY, velocity },\n props\n )\n ) {\n if (\n this.shouldMultiFingerPanFail({\n pointerLength: inputData.maxPointers,\n scale: inputData.scale,\n deltaRotation: inputData.deltaRotation,\n })\n ) {\n return {\n failed: true,\n };\n }\n return { success: true };\n }\n return { success: false };\n }\n}\n\nexport default PanGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/module/web/PinchGestureHandler.js b/lib/module/web/PinchGestureHandler.js new file mode 100644 index 0000000000..3821d8579d --- /dev/null +++ b/lib/module/web/PinchGestureHandler.js @@ -0,0 +1,29 @@ +import Hammer from '@egjs/hammerjs'; +import IndiscreteGestureHandler from './IndiscreteGestureHandler'; + +class PinchGestureHandler extends IndiscreteGestureHandler { + get name() { + return 'pinch'; + } + + get NativeGestureClass() { + return Hammer.Pinch; + } + + transformNativeEvent({ + scale, + velocity, + center + }) { + return { + focalX: center.x, + focalY: center.y, + velocity, + scale + }; + } + +} + +export default PinchGestureHandler; +//# sourceMappingURL=PinchGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/web/PinchGestureHandler.js.map b/lib/module/web/PinchGestureHandler.js.map new file mode 100644 index 0000000000..15875b079f --- /dev/null +++ b/lib/module/web/PinchGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PinchGestureHandler.ts"],"names":["Hammer","IndiscreteGestureHandler","PinchGestureHandler","name","NativeGestureClass","Pinch","transformNativeEvent","scale","velocity","center","focalX","x","focalY","y"],"mappings":"AAAA,OAAOA,MAAP,MAAmB,gBAAnB;AAGA,OAAOC,wBAAP,MAAqC,4BAArC;;AAEA,MAAMC,mBAAN,SAAkCD,wBAAlC,CAA2D;AACjD,MAAJE,IAAI,GAAG;AACT,WAAO,OAAP;AACD;;AAEqB,MAAlBC,kBAAkB,GAAG;AACvB,WAAOJ,MAAM,CAACK,KAAd;AACD;;AAEDC,EAAAA,oBAAoB,CAAC;AAAEC,IAAAA,KAAF;AAASC,IAAAA,QAAT;AAAmBC,IAAAA;AAAnB,GAAD,EAA8C;AAChE,WAAO;AACLC,MAAAA,MAAM,EAAED,MAAM,CAACE,CADV;AAELC,MAAAA,MAAM,EAAEH,MAAM,CAACI,CAFV;AAGLL,MAAAA,QAHK;AAILD,MAAAA;AAJK,KAAP;AAMD;;AAhBwD;;AAmB3D,eAAeL,mBAAf","sourcesContent":["import Hammer from '@egjs/hammerjs';\nimport { HammerInputExt } from './GestureHandler';\n\nimport IndiscreteGestureHandler from './IndiscreteGestureHandler';\n\nclass PinchGestureHandler extends IndiscreteGestureHandler {\n get name() {\n return 'pinch';\n }\n\n get NativeGestureClass() {\n return Hammer.Pinch;\n }\n\n transformNativeEvent({ scale, velocity, center }: HammerInputExt) {\n return {\n focalX: center.x,\n focalY: center.y,\n velocity,\n scale,\n };\n }\n}\n\nexport default PinchGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/module/web/PressGestureHandler.js b/lib/module/web/PressGestureHandler.js new file mode 100644 index 0000000000..4e580c4549 --- /dev/null +++ b/lib/module/web/PressGestureHandler.js @@ -0,0 +1,174 @@ +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; } + +import Hammer from '@egjs/hammerjs'; +import { State } from '../State'; +import { CONTENT_TOUCHES_DELAY, CONTENT_TOUCHES_QUICK_TAP_END_DELAY } from './constants'; +import DiscreteGestureHandler from './DiscreteGestureHandler'; +import { fireAfterInterval, isValidNumber, isnan } from './utils'; + +class PressGestureHandler extends DiscreteGestureHandler { + constructor(...args) { + super(...args); + + _defineProperty(this, "visualFeedbackTimer", void 0); + + _defineProperty(this, "initialEvent", null); + + _defineProperty(this, "shouldDelayTouches", true); + } + + get name() { + return 'press'; + } + + get minDurationMs() { + // @ts-ignore FIXME(TS) + return isnan(this.config.minDurationMs) ? 5 : this.config.minDurationMs; + } + + get maxDist() { + return isnan(this.config.maxDist) ? 9 : this.config.maxDist; + } + + get NativeGestureClass() { + return Hammer.Press; + } + + simulateCancelEvent(inputData) { + // Long press never starts so we can't rely on the running event boolean. + this.hasGestureFailed = true; + this.cancelEvent(inputData); + } + + updateHasCustomActivationCriteria({ + shouldCancelWhenOutside, + maxDistSq + }) { + return shouldCancelWhenOutside || !isValidNumber(maxDistSq); + } + + getState(type) { + return { + [Hammer.INPUT_START]: State.BEGAN, + [Hammer.INPUT_MOVE]: State.ACTIVE, + [Hammer.INPUT_END]: State.END, + [Hammer.INPUT_CANCEL]: State.CANCELLED + }[type]; + } + + getConfig() { + if (!this.hasCustomActivationCriteria) { + // Default config + // If no params have been defined then this config should emulate the native gesture as closely as possible. + return { + shouldCancelWhenOutside: true, + maxDistSq: 10 + }; + } + + return this.config; + } + + getHammerConfig() { + return { ...super.getHammerConfig(), + // threshold: this.maxDist, + time: this.minDurationMs + }; + } + + onGestureActivated(ev) { + this.onGestureStart(ev); + } + + shouldDelayTouchForEvent({ + pointerType + }) { + // Don't disable event for mouse input + return this.shouldDelayTouches && pointerType === 'touch'; + } + + onGestureStart(ev) { + this.isGestureRunning = true; + clearTimeout(this.visualFeedbackTimer); + this.initialEvent = ev; + this.visualFeedbackTimer = fireAfterInterval(() => { + this.sendGestureStartedEvent(this.initialEvent); + this.initialEvent = null; + }, this.shouldDelayTouchForEvent(ev) && CONTENT_TOUCHES_DELAY); + } + + sendGestureStartedEvent(ev) { + clearTimeout(this.visualFeedbackTimer); + this.visualFeedbackTimer = null; + this.sendEvent({ ...ev, + eventType: Hammer.INPUT_MOVE, + isFirst: true + }); + } + + forceInvalidate(event) { + super.forceInvalidate(event); + clearTimeout(this.visualFeedbackTimer); + this.visualFeedbackTimer = null; + this.initialEvent = null; + } + + onRawEvent(ev) { + super.onRawEvent(ev); + + if (this.isGestureRunning) { + if (ev.isFinal) { + let timeout; + + if (this.visualFeedbackTimer) { + // Aesthetic timing for a quick tap. + // We haven't activated the tap right away to emulate iOS `delaysContentTouches` + // Now we must send the initial activation event and wait a set amount of time before firing the end event. + timeout = CONTENT_TOUCHES_QUICK_TAP_END_DELAY; + this.sendGestureStartedEvent(this.initialEvent); + this.initialEvent = null; + } + + fireAfterInterval(() => { + this.sendEvent({ ...ev, + eventType: Hammer.INPUT_END, + isFinal: true + }); // @ts-ignore -- this should explicitly support undefined + + this.onGestureEnded(); + }, timeout); + } else { + this.sendEvent({ ...ev, + eventType: Hammer.INPUT_MOVE, + isFinal: false + }); + } + } + } + + updateGestureConfig({ + shouldActivateOnStart = false, + disallowInterruption = false, + shouldCancelWhenOutside = true, + minDurationMs = Number.NaN, + maxDist = Number.NaN, + minPointers = 1, + maxPointers = 1, + ...props + }) { + return super.updateGestureConfig({ + shouldActivateOnStart, + disallowInterruption, + shouldCancelWhenOutside, + minDurationMs, + maxDist, + minPointers, + maxPointers, + ...props + }); + } + +} + +export default PressGestureHandler; +//# sourceMappingURL=PressGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/web/PressGestureHandler.js.map b/lib/module/web/PressGestureHandler.js.map new file mode 100644 index 0000000000..de2f7f7914 --- /dev/null +++ b/lib/module/web/PressGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["PressGestureHandler.ts"],"names":["Hammer","State","CONTENT_TOUCHES_DELAY","CONTENT_TOUCHES_QUICK_TAP_END_DELAY","DiscreteGestureHandler","fireAfterInterval","isValidNumber","isnan","PressGestureHandler","name","minDurationMs","config","maxDist","NativeGestureClass","Press","simulateCancelEvent","inputData","hasGestureFailed","cancelEvent","updateHasCustomActivationCriteria","shouldCancelWhenOutside","maxDistSq","getState","type","INPUT_START","BEGAN","INPUT_MOVE","ACTIVE","INPUT_END","END","INPUT_CANCEL","CANCELLED","getConfig","hasCustomActivationCriteria","getHammerConfig","time","onGestureActivated","ev","onGestureStart","shouldDelayTouchForEvent","pointerType","shouldDelayTouches","isGestureRunning","clearTimeout","visualFeedbackTimer","initialEvent","sendGestureStartedEvent","sendEvent","eventType","isFirst","forceInvalidate","event","onRawEvent","isFinal","timeout","onGestureEnded","updateGestureConfig","shouldActivateOnStart","disallowInterruption","Number","NaN","minPointers","maxPointers","props"],"mappings":";;AAAA,OAAOA,MAAP,MAAmB,gBAAnB;AAEA,SAASC,KAAT,QAAsB,UAAtB;AACA,SACEC,qB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C,MAAAA,qBAD+B;AAE/BC,MAAAA,oBAF+B;AAG/BtC,MAAAA,uBAH+B;AAI/BV,MAAAA,aAJ+B;AAK/BE,MAAAA,OAL+B;AAM/BiD,MAAAA,WAN+B;AAO/BC,MAAAA,WAP+B;AAQ/B,SAAGC;AAR4B,KAA1B,CAAP;AAUD;;AAxJsD;;AA0JzD,eAAevD,mBAAf","sourcesContent":["import Hammer from '@egjs/hammerjs';\n\nimport { State } from '../State';\nimport {\n CONTENT_TOUCHES_DELAY,\n CONTENT_TOUCHES_QUICK_TAP_END_DELAY,\n HammerInputNames,\n} from './constants';\nimport DiscreteGestureHandler from './DiscreteGestureHandler';\nimport { Config, HammerInputExt } from './GestureHandler';\nimport { fireAfterInterval, isValidNumber, isnan } from './utils';\n\nclass PressGestureHandler extends DiscreteGestureHandler {\n private visualFeedbackTimer: any;\n private initialEvent: HammerInputExt | null = null;\n get name() {\n return 'press';\n }\n\n get minDurationMs() {\n // @ts-ignore FIXME(TS)\n return isnan(this.config.minDurationMs) ? 5 : this.config.minDurationMs;\n }\n\n get maxDist() {\n return isnan(this.config.maxDist) ? 9 : this.config.maxDist;\n }\n\n get NativeGestureClass() {\n return Hammer.Press;\n }\n\n shouldDelayTouches = true;\n\n simulateCancelEvent(inputData: HammerInputExt) {\n // Long press never starts so we can't rely on the running event boolean.\n this.hasGestureFailed = true;\n this.cancelEvent(inputData);\n }\n\n updateHasCustomActivationCriteria({\n shouldCancelWhenOutside,\n maxDistSq,\n }: Config & { shouldCancelWhenOutside: boolean }) {\n return shouldCancelWhenOutside || !isValidNumber(maxDistSq);\n }\n\n getState(type: keyof typeof HammerInputNames): State {\n return {\n [Hammer.INPUT_START]: State.BEGAN,\n [Hammer.INPUT_MOVE]: State.ACTIVE,\n [Hammer.INPUT_END]: State.END,\n [Hammer.INPUT_CANCEL]: State.CANCELLED,\n }[type];\n }\n\n getConfig() {\n if (!this.hasCustomActivationCriteria) {\n // Default config\n // If no params have been defined then this config should emulate the native gesture as closely as possible.\n return {\n shouldCancelWhenOutside: true,\n maxDistSq: 10,\n };\n }\n return this.config;\n }\n\n getHammerConfig() {\n return {\n ...super.getHammerConfig(),\n // threshold: this.maxDist,\n time: this.minDurationMs,\n };\n }\n\n onGestureActivated(ev: HammerInputExt) {\n this.onGestureStart(ev);\n }\n\n shouldDelayTouchForEvent({ pointerType }: HammerInputExt) {\n // Don't disable event for mouse input\n return this.shouldDelayTouches && pointerType === 'touch';\n }\n\n onGestureStart(ev: HammerInputExt) {\n this.isGestureRunning = true;\n clearTimeout(this.visualFeedbackTimer);\n this.initialEvent = ev;\n this.visualFeedbackTimer = fireAfterInterval(() => {\n this.sendGestureStartedEvent(this.initialEvent as HammerInputExt);\n this.initialEvent = null;\n }, this.shouldDelayTouchForEvent(ev) && CONTENT_TOUCHES_DELAY);\n }\n\n sendGestureStartedEvent(ev: HammerInputExt) {\n clearTimeout(this.visualFeedbackTimer);\n this.visualFeedbackTimer = null;\n this.sendEvent({\n ...ev,\n eventType: Hammer.INPUT_MOVE,\n isFirst: true,\n });\n }\n\n forceInvalidate(event: HammerInputExt) {\n super.forceInvalidate(event);\n clearTimeout(this.visualFeedbackTimer);\n this.visualFeedbackTimer = null;\n this.initialEvent = null;\n }\n\n onRawEvent(ev: HammerInputExt) {\n super.onRawEvent(ev);\n if (this.isGestureRunning) {\n if (ev.isFinal) {\n let timeout;\n if (this.visualFeedbackTimer) {\n // Aesthetic timing for a quick tap.\n // We haven't activated the tap right away to emulate iOS `delaysContentTouches`\n // Now we must send the initial activation event and wait a set amount of time before firing the end event.\n timeout = CONTENT_TOUCHES_QUICK_TAP_END_DELAY;\n this.sendGestureStartedEvent(this.initialEvent as HammerInputExt);\n this.initialEvent = null;\n }\n fireAfterInterval(() => {\n this.sendEvent({\n ...ev,\n eventType: Hammer.INPUT_END,\n isFinal: true,\n });\n // @ts-ignore -- this should explicitly support undefined\n this.onGestureEnded();\n }, timeout);\n } else {\n this.sendEvent({\n ...ev,\n eventType: Hammer.INPUT_MOVE,\n isFinal: false,\n });\n }\n }\n }\n\n updateGestureConfig({\n shouldActivateOnStart = false,\n disallowInterruption = false,\n shouldCancelWhenOutside = true,\n minDurationMs = Number.NaN,\n maxDist = Number.NaN,\n minPointers = 1,\n maxPointers = 1,\n ...props\n }) {\n return super.updateGestureConfig({\n shouldActivateOnStart,\n disallowInterruption,\n shouldCancelWhenOutside,\n minDurationMs,\n maxDist,\n minPointers,\n maxPointers,\n ...props,\n });\n }\n}\nexport default PressGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/module/web/RotationGestureHandler.js b/lib/module/web/RotationGestureHandler.js new file mode 100644 index 0000000000..42f97ccbc8 --- /dev/null +++ b/lib/module/web/RotationGestureHandler.js @@ -0,0 +1,32 @@ +import Hammer from '@egjs/hammerjs'; +import { DEG_RAD } from './constants'; +import IndiscreteGestureHandler from './IndiscreteGestureHandler'; + +class RotationGestureHandler extends IndiscreteGestureHandler { + get name() { + return 'rotate'; + } + + get NativeGestureClass() { + return Hammer.Rotate; + } + + transformNativeEvent({ + rotation, + velocity, + center + }) { + var _this$initialRotation; + + return { + rotation: (rotation - ((_this$initialRotation = this.initialRotation) !== null && _this$initialRotation !== void 0 ? _this$initialRotation : 0)) * DEG_RAD, + anchorX: center.x, + anchorY: center.y, + velocity + }; + } + +} + +export default RotationGestureHandler; +//# sourceMappingURL=RotationGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/web/RotationGestureHandler.js.map b/lib/module/web/RotationGestureHandler.js.map new file mode 100644 index 0000000000..fb7b3c3dcc --- /dev/null +++ b/lib/module/web/RotationGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["RotationGestureHandler.ts"],"names":["Hammer","DEG_RAD","IndiscreteGestureHandler","RotationGestureHandler","name","NativeGestureClass","Rotate","transformNativeEvent","rotation","velocity","center","initialRotation","anchorX","x","anchorY","y"],"mappings":"AAAA,OAAOA,MAAP,MAAmB,gBAAnB;AAEA,SAASC,OAAT,QAAwB,aAAxB;AAEA,OAAOC,wBAAP,MAAqC,4BAArC;;AAEA,MAAMC,sBAAN,SAAqCD,wBAArC,CAA8D;AACpD,MAAJE,IAAI,GAAG;AACT,WAAO,QAAP;AACD;;AAEqB,MAAlBC,kBAAkB,GAAG;AACvB,WAAOL,MAAM,CAACM,MAAd;AACD;;AAEDC,EAAAA,oBAAoB,CAAC;AAAEC,IAAAA,QAAF;AAAYC,IAAAA,QAAZ;AAAsBC,IAAAA;AAAtB,GAAD,EAAiD;AAAA;;AACnE,WAAO;AACLF,MAAAA,QAAQ,EAAE,CAACA,QAAQ,6BAAI,KAAKG,eAAT,yEAA4B,CAA5B,CAAT,IAA2CV,OADhD;AAELW,MAAAA,OAAO,EAAEF,MAAM,CAACG,CAFX;AAGLC,MAAAA,OAAO,EAAEJ,MAAM,CAACK,CAHX;AAILN,MAAAA;AAJK,KAAP;AAMD;;AAhB2D;;AAkB9D,eAAeN,sBAAf","sourcesContent":["import Hammer from '@egjs/hammerjs';\n\nimport { DEG_RAD } from './constants';\nimport { HammerInputExt } from './GestureHandler';\nimport IndiscreteGestureHandler from './IndiscreteGestureHandler';\n\nclass RotationGestureHandler extends IndiscreteGestureHandler {\n get name() {\n return 'rotate';\n }\n\n get NativeGestureClass() {\n return Hammer.Rotate;\n }\n\n transformNativeEvent({ rotation, velocity, center }: HammerInputExt) {\n return {\n rotation: (rotation - (this.initialRotation ?? 0)) * DEG_RAD,\n anchorX: center.x,\n anchorY: center.y,\n velocity,\n };\n }\n}\nexport default RotationGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/module/web/TapGestureHandler.js b/lib/module/web/TapGestureHandler.js new file mode 100644 index 0000000000..ed067cd47b --- /dev/null +++ b/lib/module/web/TapGestureHandler.js @@ -0,0 +1,180 @@ +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; } + +import Hammer from '@egjs/hammerjs'; +import DiscreteGestureHandler from './DiscreteGestureHandler'; +import { isnan } from './utils'; + +class TapGestureHandler extends DiscreteGestureHandler { + constructor(...args) { + super(...args); + + _defineProperty(this, "_shouldFireEndEvent", null); + + _defineProperty(this, "_timer", void 0); + + _defineProperty(this, "_multiTapTimer", void 0); + + _defineProperty(this, "onSuccessfulTap", ev => { + if (this._getPendingGestures().length) { + this._shouldFireEndEvent = ev; + return; + } + + if (ev.eventType === Hammer.INPUT_END) { + this.sendEvent({ ...ev, + eventType: Hammer.INPUT_MOVE + }); + } // When handler gets activated it will turn into State.END immediately. + + + this.sendEvent({ ...ev, + isFinal: true + }); + this.onGestureEnded(ev); + }); + } + + // TODO unused? + get name() { + return 'tap'; + } + + get NativeGestureClass() { + return Hammer.Tap; + } + + get maxDelayMs() { + // @ts-ignore TODO(TS) trace down config + return isnan(this.config.maxDelayMs) ? 300 : this.config.maxDelayMs; + } + + simulateCancelEvent(inputData) { + if (this.isGestureRunning) { + this.cancelEvent(inputData); + } + } + + onGestureActivated(ev) { + if (this.isGestureRunning) { + this.onSuccessfulTap(ev); + } + } + + onRawEvent(ev) { + super.onRawEvent(ev); // Attempt to create a touch-down event by checking if a valid tap hasn't started yet, then validating the input. + + if (!this.hasGestureFailed && !this.isGestureRunning && // Prevent multi-pointer events from misfiring. + !ev.isFinal) { + // Tap Gesture start event + const gesture = this.hammer.get(this.name); // @ts-ignore TODO(TS) trace down config + + if (gesture.options.enable(gesture, ev)) { + clearTimeout(this._multiTapTimer); + this.onStart(ev); + this.sendEvent(ev); + } + } + + if (ev.isFinal && ev.maxPointers > 1) { + setTimeout(() => { + // Handle case where one finger presses slightly + // after the first finger on a multi-tap event + if (this.isGestureRunning) { + this.cancelEvent(ev); + } + }); + } + + if (this.hasGestureFailed) { + return; + } // Hammer doesn't send a `cancel` event for taps. + // Manually fail the event. + + + if (ev.isFinal) { + // Handle case where one finger presses slightly + // after the first finger on a multi-tap event + if (ev.maxPointers > 1) { + setTimeout(() => { + if (this.isGestureRunning) { + this.cancelEvent(ev); + } + }); + } // Clear last timer + + + clearTimeout(this._timer); // Create time out for multi-taps. + + this._timer = setTimeout(() => { + this.hasGestureFailed = true; + this.cancelEvent(ev); + }, this.maxDelayMs); + } else if (!this.hasGestureFailed && !this.isGestureRunning) { + // Tap Gesture start event + const gesture = this.hammer.get(this.name); // @ts-ignore TODO(TS) trace down config + + if (gesture.options.enable(gesture, ev)) { + clearTimeout(this._multiTapTimer); + this.onStart(ev); + this.sendEvent(ev); + } + } + } + + getHammerConfig() { + return { ...super.getHammerConfig(), + event: this.name, + // @ts-ignore TODO(TS) trace down config + taps: isnan(this.config.numberOfTaps) ? 1 : this.config.numberOfTaps, + interval: this.maxDelayMs, + time: // @ts-ignore TODO(TS) trace down config + isnan(this.config.maxDurationMs) || this.config.maxDurationMs == null ? 250 : // @ts-ignore TODO(TS) trace down config + this.config.maxDurationMs + }; + } + + updateGestureConfig({ + shouldCancelWhenOutside = true, + maxDeltaX = Number.NaN, + maxDeltaY = Number.NaN, + numberOfTaps = 1, + minDurationMs = 525, + maxDelayMs = Number.NaN, + // eslint-disable-next-line @typescript-eslint/no-unused-vars -- TODO possibly forgotten to use in updateGestureConfig? + maxDurationMs = Number.NaN, + maxDist = 2, + minPointers = 1, + maxPointers = 1, + ...props + }) { + return super.updateGestureConfig({ + shouldCancelWhenOutside, + numberOfTaps, + maxDeltaX, + maxDeltaY, + minDurationMs, + maxDelayMs, + maxDist, + minPointers, + maxPointers, + ...props + }); + } + + onGestureEnded(...props) { + clearTimeout(this._timer); // @ts-ignore TODO(TS) check how onGestureEnded works + + super.onGestureEnded(...props); + } + + onWaitingEnded(_gesture) { + if (this._shouldFireEndEvent) { + this.onSuccessfulTap(this._shouldFireEndEvent); + this._shouldFireEndEvent = null; + } + } + +} + +export default TapGestureHandler; +//# sourceMappingURL=TapGestureHandler.js.map \ No newline at end of file diff --git a/lib/module/web/TapGestureHandler.js.map b/lib/module/web/TapGestureHandler.js.map new file mode 100644 index 0000000000..4145c77f47 --- /dev/null +++ b/lib/module/web/TapGestureHandler.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["TapGestureHandler.ts"],"names":["Hammer","DiscreteGestureHandler","isnan","TapGestureHandler","ev","_getPendingGestures","length","_shouldFireEndEvent","eventType","INPUT_END","sendEvent","INPUT_MOVE","isFinal","onGestureEnded","name","NativeGestureClass","Tap","maxDelayMs","config","simulateCancelEvent","inputData","isGestureRunning","cancelEvent","onGestureActivated","onSuccessfulTap","onRawEvent","hasGestureFailed","gesture","hammer","get","options","enable","clearTimeout","_multiTapTimer","onStart","maxPointers","setTimeout","_timer","getHammerConfig","event","taps","numberOfTaps","interval","time","maxDurationMs","updateGestureConfig","shouldCancelWhenOutside","maxDeltaX","Number","NaN","maxDeltaY","minDurationMs","maxDist","minPointers","props","onWaitingEnded","_gesture"],"mappings":";;AAAA,OAAOA,MAAP,MAAmB,gBAAnB;AAEA,OAAOC,sBAAP,MAAmC,0BAAnC;AAEA,SAASC,KAAT,QAAsB,SAAtB;;AAEA,MAAMC,iBAAN,SAAgCF,sBAAhC,CAAuD;AAAA;AAAA;;AAAA,iDACA,IADA;;AAAA;;AAAA;;AAAA,6CA6BlCG,EAAD,IAAwB;AACxC,UAAI,KAAKC,mBAAL,GAA2BC,MAA/B,EAAuC;AACrC,aAAKC,mBAAL,GAA2BH,EAA3B;AACA;AACD;;AACD,UAAIA,EAAE,CAACI,SAAH,KAAiBR,MAAM,CAACS,SAA5B,EAAuC;AACrC,aAAKC,SAAL,CAAe,EAAE,GAAGN,EAAL;AAASI,UAAAA,SAAS,EAAER,MAAM,CAACW;AAA3B,SAAf;AACD,OAPuC,CAQxC;;;AACA,WAAKD,SAAL,CAAe,EAAE,GAAGN,EAAL;AAASQ,QAAAA,OAAO,EAAE;AAAlB,OAAf;AACA,WAAKC,cAAL,CAAoBT,EAApB;AACD,KAxCoD;AAAA;;AAGxB;AACrB,MAAJU,IAAI,GAAG;AACT,WAAO,KAAP;AACD;;AAEqB,MAAlBC,kBAAkB,GAAG;AACvB,WAAOf,M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js';\n\nimport DiscreteGestureHandler from './DiscreteGestureHandler';\nimport { HammerInputExt } from './GestureHandler';\nimport { isnan } from './utils';\n\nclass TapGestureHandler extends DiscreteGestureHandler {\n private _shouldFireEndEvent: HammerInputExt | null = null;\n private _timer: any;\n private _multiTapTimer: any; // TODO unused?\n get name() {\n return 'tap';\n }\n\n get NativeGestureClass() {\n return Hammer.Tap;\n }\n\n get maxDelayMs() {\n // @ts-ignore TODO(TS) trace down config\n return isnan(this.config.maxDelayMs) ? 300 : this.config.maxDelayMs;\n }\n\n simulateCancelEvent(inputData: HammerInputExt) {\n if (this.isGestureRunning) {\n this.cancelEvent(inputData);\n }\n }\n\n onGestureActivated(ev: HammerInputExt) {\n if (this.isGestureRunning) {\n this.onSuccessfulTap(ev);\n }\n }\n\n onSuccessfulTap = (ev: HammerInputExt) => {\n if (this._getPendingGestures().length) {\n this._shouldFireEndEvent = ev;\n return;\n }\n if (ev.eventType === Hammer.INPUT_END) {\n this.sendEvent({ ...ev, eventType: Hammer.INPUT_MOVE });\n }\n // When handler gets activated it will turn into State.END immediately.\n this.sendEvent({ ...ev, isFinal: true });\n this.onGestureEnded(ev);\n };\n\n onRawEvent(ev: HammerInput) {\n super.onRawEvent(ev);\n\n // Attempt to create a touch-down event by checking if a valid tap hasn't started yet, then validating the input.\n if (\n !this.hasGestureFailed &&\n !this.isGestureRunning &&\n // Prevent multi-pointer events from misfiring.\n !ev.isFinal\n ) {\n // Tap Gesture start event\n const gesture = this.hammer!.get(this.name);\n // @ts-ignore TODO(TS) trace down config\n if (gesture.options.enable(gesture, ev)) {\n clearTimeout(this._multiTapTimer);\n\n this.onStart(ev);\n this.sendEvent(ev);\n }\n }\n if (ev.isFinal && ev.maxPointers > 1) {\n setTimeout(() => {\n // Handle case where one finger presses slightly\n // after the first finger on a multi-tap event\n if (this.isGestureRunning) {\n this.cancelEvent(ev);\n }\n });\n }\n\n if (this.hasGestureFailed) {\n return;\n }\n // Hammer doesn't send a `cancel` event for taps.\n // Manually fail the event.\n if (ev.isFinal) {\n // Handle case where one finger presses slightly\n // after the first finger on a multi-tap event\n if (ev.maxPointers > 1) {\n setTimeout(() => {\n if (this.isGestureRunning) {\n this.cancelEvent(ev);\n }\n });\n }\n\n // Clear last timer\n clearTimeout(this._timer);\n // Create time out for multi-taps.\n this._timer = setTimeout(() => {\n this.hasGestureFailed = true;\n this.cancelEvent(ev);\n }, this.maxDelayMs);\n } else if (!this.hasGestureFailed && !this.isGestureRunning) {\n // Tap Gesture start event\n const gesture = this.hammer!.get(this.name);\n // @ts-ignore TODO(TS) trace down config\n if (gesture.options.enable(gesture, ev)) {\n clearTimeout(this._multiTapTimer);\n\n this.onStart(ev);\n this.sendEvent(ev);\n }\n }\n }\n\n getHammerConfig() {\n return {\n ...super.getHammerConfig(),\n event: this.name,\n // @ts-ignore TODO(TS) trace down config\n taps: isnan(this.config.numberOfTaps) ? 1 : this.config.numberOfTaps,\n interval: this.maxDelayMs,\n time:\n // @ts-ignore TODO(TS) trace down config\n isnan(this.config.maxDurationMs) || this.config.maxDurationMs == null\n ? 250\n : // @ts-ignore TODO(TS) trace down config\n this.config.maxDurationMs,\n };\n }\n\n updateGestureConfig({\n shouldCancelWhenOutside = true,\n maxDeltaX = Number.NaN,\n maxDeltaY = Number.NaN,\n numberOfTaps = 1,\n minDurationMs = 525,\n maxDelayMs = Number.NaN,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars -- TODO possibly forgotten to use in updateGestureConfig?\n maxDurationMs = Number.NaN,\n maxDist = 2,\n minPointers = 1,\n maxPointers = 1,\n ...props\n }) {\n return super.updateGestureConfig({\n shouldCancelWhenOutside,\n numberOfTaps,\n maxDeltaX,\n maxDeltaY,\n minDurationMs,\n maxDelayMs,\n maxDist,\n minPointers,\n maxPointers,\n ...props,\n });\n }\n\n onGestureEnded(...props: any) {\n clearTimeout(this._timer);\n // @ts-ignore TODO(TS) check how onGestureEnded works\n super.onGestureEnded(...props);\n }\n\n onWaitingEnded(_gesture: any) {\n if (this._shouldFireEndEvent) {\n this.onSuccessfulTap(this._shouldFireEndEvent);\n this._shouldFireEndEvent = null;\n }\n }\n}\nexport default TapGestureHandler;\n"]} \ No newline at end of file diff --git a/lib/module/web/constants.js b/lib/module/web/constants.js new file mode 100644 index 0000000000..5944bdd91a --- /dev/null +++ b/lib/module/web/constants.js @@ -0,0 +1,43 @@ +import Hammer from '@egjs/hammerjs'; +import { State } from '../State'; +export const CONTENT_TOUCHES_DELAY = 240; +export const CONTENT_TOUCHES_QUICK_TAP_END_DELAY = 50; +export const MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD = 0.1; +export const MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD = 7; +export const DEG_RAD = Math.PI / 180; // Map Hammer values to RNGH + +export const EventMap = { + [Hammer.INPUT_START]: State.BEGAN, + [Hammer.INPUT_MOVE]: State.ACTIVE, + [Hammer.INPUT_END]: State.END, + [Hammer.INPUT_CANCEL]: State.FAILED +}; +export const Direction = { + RIGHT: 1, + LEFT: 2, + UP: 4, + DOWN: 8 +}; +export const DirectionMap = { + [Hammer.DIRECTION_RIGHT]: Direction.RIGHT, + [Hammer.DIRECTION_LEFT]: Direction.LEFT, + [Hammer.DIRECTION_UP]: Direction.UP, + [Hammer.DIRECTION_DOWN]: Direction.DOWN +}; +export const HammerInputNames = { + [Hammer.INPUT_START]: 'START', + [Hammer.INPUT_MOVE]: 'MOVE', + [Hammer.INPUT_END]: 'END', + [Hammer.INPUT_CANCEL]: 'CANCEL' +}; +export const HammerDirectionNames = { + [Hammer.DIRECTION_HORIZONTAL]: 'HORIZONTAL', + [Hammer.DIRECTION_UP]: 'UP', + [Hammer.DIRECTION_DOWN]: 'DOWN', + [Hammer.DIRECTION_VERTICAL]: 'VERTICAL', + [Hammer.DIRECTION_NONE]: 'NONE', + [Hammer.DIRECTION_ALL]: 'ALL', + [Hammer.DIRECTION_RIGHT]: 'RIGHT', + [Hammer.DIRECTION_LEFT]: 'LEFT' +}; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/lib/module/web/constants.js.map b/lib/module/web/constants.js.map new file mode 100644 index 0000000000..56a31eb7fd --- /dev/null +++ b/lib/module/web/constants.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["constants.ts"],"names":["Hammer","State","CONTENT_TOUCHES_DELAY","CONTENT_TOUCHES_QUICK_TAP_END_DELAY","MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD","MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD","DEG_RAD","Math","PI","EventMap","INPUT_START","BEGAN","INPUT_MOVE","ACTIVE","INPUT_END","END","INPUT_CANCEL","FAILED","Direction","RIGHT","LEFT","UP","DOWN","DirectionMap","DIRECTION_RIGHT","DIRECTION_LEFT","DIRECTION_UP","DIRECTION_DOWN","HammerInputNames","HammerDirectionNames","DIRECTION_HORIZONTAL","DIRECTION_VERTICAL","DIRECTION_NONE","DIRECTION_ALL"],"mappings":"AAAA,OAAOA,MAAP,MAAmB,gBAAnB;AAEA,SAASC,KAAT,QAAsB,UAAtB;AAEA,OAAO,MAAMC,qBAAqB,GAAG,GAA9B;AACP,OAAO,MAAMC,mCAAmC,GAAG,EAA5C;AACP,OAAO,MAAMC,oCAAoC,GAAG,GAA7C;AACP,OAAO,MAAMC,uCAAuC,GAAG,CAAhD;AACP,OAAO,MAAMC,OAAO,GAAGC,IAAI,CAACC,EAAL,GAAU,GAA1B,C,CAEP;;AACA,OAAO,MAAMC,QAAQ,GAAG;AACtB,GAACT,MAAM,CAACU,WAAR,GAAsBT,KAAK,CAACU,KADN;AAEtB,GAACX,MAAM,CAACY,UAAR,GAAqBX,KAAK,CAACY,MAFL;AAGtB,GAACb,MAAM,CAACc,SAAR,GAAoBb,KAAK,CAACc,GAHJ;AAItB,GAACf,MAAM,CAACgB,YAAR,GAAuBf,KAAK,CAACgB;AAJP,CAAjB;AAOP,OAAO,MAAMC,SAAS,GAAG;AACvBC,EAAAA,KAAK,EAAE,CADgB;AAEvBC,EAAAA,IAAI,EAAE,CAFiB;AAGvBC,EAAAA,EAAE,EAAE,CAHmB;AAIvBC,EAAAA,IAAI,EAAE;AAJiB,CAAlB;AAOP,OAAO,MAAMC,YAAY,GAAG;AAC1B,GAACvB,MAAM,CAACwB,eAAR,GAA0BN,SAAS,CAACC,KADV;AAE1B,GAACnB,MAAM,CAACyB,cAAR,GAAyBP,SAAS,CAACE,IAFT;AAG1B,GAACpB,MAAM,CAAC0B,YAAR,GAAuBR,SAAS,CAACG,EAHP;AAI1B,GAACrB,MAAM,CAAC2B,cAAR,GAAyBT,SAAS,CAACI;AAJT,CAArB;AAOP,OAAO,MAAMM,gBAAgB,GAAG;AAC9B,GAAC5B,MAAM,CAACU,WAAR,GAAsB,OADQ;AAE9B,GAACV,MAAM,CAACY,UAAR,GAAqB,MAFS;AAG9B,GAACZ,MAAM,CAACc,SAAR,GAAoB,KAHU;AAI9B,GAACd,MAAM,CAACgB,YAAR,GAAuB;AAJO,CAAzB;AAMP,OAAO,MAAMa,oBAAoB,GAAG;AAClC,GAAC7B,MAAM,CAAC8B,oBAAR,GAA+B,YADG;AAElC,GAAC9B,MAAM,CAAC0B,YAAR,GAAuB,IAFW;AAGlC,GAAC1B,MAAM,CAAC2B,cAAR,GAAyB,MAHS;AAIlC,GAAC3B,MAAM,CAAC+B,kBAAR,GAA6B,UAJK;AAKlC,GAAC/B,MAAM,CAACgC,cAAR,GAAyB,MALS;AAMlC,GAAChC,MAAM,CAACiC,aAAR,GAAwB,KANU;AAOlC,GAACjC,MAAM,CAACwB,eAAR,GAA0B,OAPQ;AAQlC,GAACxB,MAAM,CAACyB,cAAR,GAAyB;AARS,CAA7B","sourcesContent":["import Hammer from '@egjs/hammerjs';\n\nimport { State } from '../State';\n\nexport const CONTENT_TOUCHES_DELAY = 240;\nexport const CONTENT_TOUCHES_QUICK_TAP_END_DELAY = 50;\nexport const MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD = 0.1;\nexport const MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD = 7;\nexport const DEG_RAD = Math.PI / 180;\n\n// Map Hammer values to RNGH\nexport const EventMap = {\n [Hammer.INPUT_START]: State.BEGAN,\n [Hammer.INPUT_MOVE]: State.ACTIVE,\n [Hammer.INPUT_END]: State.END,\n [Hammer.INPUT_CANCEL]: State.FAILED,\n} as const;\n\nexport const Direction = {\n RIGHT: 1,\n LEFT: 2,\n UP: 4,\n DOWN: 8,\n};\n\nexport const DirectionMap = {\n [Hammer.DIRECTION_RIGHT]: Direction.RIGHT,\n [Hammer.DIRECTION_LEFT]: Direction.LEFT,\n [Hammer.DIRECTION_UP]: Direction.UP,\n [Hammer.DIRECTION_DOWN]: Direction.DOWN,\n};\n\nexport const HammerInputNames = {\n [Hammer.INPUT_START]: 'START',\n [Hammer.INPUT_MOVE]: 'MOVE',\n [Hammer.INPUT_END]: 'END',\n [Hammer.INPUT_CANCEL]: 'CANCEL',\n};\nexport const HammerDirectionNames = {\n [Hammer.DIRECTION_HORIZONTAL]: 'HORIZONTAL',\n [Hammer.DIRECTION_UP]: 'UP',\n [Hammer.DIRECTION_DOWN]: 'DOWN',\n [Hammer.DIRECTION_VERTICAL]: 'VERTICAL',\n [Hammer.DIRECTION_NONE]: 'NONE',\n [Hammer.DIRECTION_ALL]: 'ALL',\n [Hammer.DIRECTION_RIGHT]: 'RIGHT',\n [Hammer.DIRECTION_LEFT]: 'LEFT',\n};\n"]} \ No newline at end of file diff --git a/lib/module/web/utils.js b/lib/module/web/utils.js new file mode 100644 index 0000000000..2591b7f7ab --- /dev/null +++ b/lib/module/web/utils.js @@ -0,0 +1,19 @@ +// TODO(TS) remove if not necessary after rewrite +export const isnan = v => Number.isNaN(v); // TODO(TS) remove if not necessary after rewrite + +export const isValidNumber = v => typeof v === 'number' && !Number.isNaN(v); +export const TEST_MIN_IF_NOT_NAN = (value, limit) => !isnan(limit) && (limit < 0 && value <= limit || limit >= 0 && value >= limit); +export const VEC_LEN_SQ = ({ + x = 0, + y = 0 +} = {}) => x * x + y * y; +export const TEST_MAX_IF_NOT_NAN = (value, max) => !isnan(max) && (max < 0 && value < max || max >= 0 && value > max); +export function fireAfterInterval(method, interval) { + if (!interval) { + method(); + return null; + } + + return setTimeout(() => method(), interval); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/lib/module/web/utils.js.map b/lib/module/web/utils.js.map new file mode 100644 index 0000000000..23adbe29a3 --- /dev/null +++ b/lib/module/web/utils.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["utils.ts"],"names":["isnan","v","Number","isNaN","isValidNumber","TEST_MIN_IF_NOT_NAN","value","limit","VEC_LEN_SQ","x","y","TEST_MAX_IF_NOT_NAN","max","fireAfterInterval","method","interval","setTimeout"],"mappings":"AAAA;AACA,OAAO,MAAMA,KAAK,GAAIC,CAAD,IAAgBC,MAAM,CAACC,KAAP,CAAaF,CAAb,CAA9B,C,CAEP;;AACA,OAAO,MAAMG,aAAa,GAAIH,CAAD,IAC3B,OAAOA,CAAP,KAAa,QAAb,IAAyB,CAACC,MAAM,CAACC,KAAP,CAAaF,CAAb,CADrB;AAGP,OAAO,MAAMI,mBAAmB,GAAG,CAACC,KAAD,EAAgBC,KAAhB,KACjC,CAACP,KAAK,CAACO,KAAD,CAAN,KACEA,KAAK,GAAG,CAAR,IAAaD,KAAK,IAAIC,KAAvB,IAAkCA,KAAK,IAAI,CAAT,IAAcD,KAAK,IAAIC,KAD1D,CADK;AAGP,OAAO,MAAMC,UAAU,GAAG,CAAC;AAAEC,EAAAA,CAAC,GAAG,CAAN;AAASC,EAAAA,CAAC,GAAG;AAAb,IAAmB,EAApB,KAA2BD,CAAC,GAAGA,CAAJ,GAAQC,CAAC,GAAGA,CAA1D;AACP,OAAO,MAAMC,mBAAmB,GAAG,CAACL,KAAD,EAAgBM,GAAhB,KACjC,CAACZ,KAAK,CAACY,GAAD,CAAN,KAAiBA,GAAG,GAAG,CAAN,IAAWN,KAAK,GAAGM,GAApB,IAA6BA,GAAG,IAAI,CAAP,IAAYN,KAAK,GAAGM,GAAjE,CADK;AAGP,OAAO,SAASC,iBAAT,CACLC,MADK,EAELC,QAFK,EAGL;AACA,MAAI,CAACA,QAAL,EAAe;AACbD,IAAAA,MAAM;AACN,WAAO,IAAP;AACD;;AACD,SAAOE,UAAU,CAAC,MAAMF,MAAM,EAAb,EAAiBC,QAAjB,CAAjB;AACD","sourcesContent":["// TODO(TS) remove if not necessary after rewrite\nexport const isnan = (v: unknown) => Number.isNaN(v);\n\n// TODO(TS) remove if not necessary after rewrite\nexport const isValidNumber = (v: unknown) =>\n typeof v === 'number' && !Number.isNaN(v);\n\nexport const TEST_MIN_IF_NOT_NAN = (value: number, limit: number): boolean =>\n !isnan(limit) &&\n ((limit < 0 && value <= limit) || (limit >= 0 && value >= limit));\nexport const VEC_LEN_SQ = ({ x = 0, y = 0 } = {}) => x * x + y * y;\nexport const TEST_MAX_IF_NOT_NAN = (value: number, max: number) =>\n !isnan(max) && ((max < 0 && value < max) || (max >= 0 && value > max));\n\nexport function fireAfterInterval(\n method: () => void,\n interval?: number | boolean\n) {\n if (!interval) {\n method();\n return null;\n }\n return setTimeout(() => method(), interval);\n}\n"]} \ No newline at end of file diff --git a/lib/typescript/Directions.d.ts b/lib/typescript/Directions.d.ts new file mode 100644 index 0000000000..e1020204b3 --- /dev/null +++ b/lib/typescript/Directions.d.ts @@ -0,0 +1,7 @@ +export declare const Directions: { + readonly RIGHT: 1; + readonly LEFT: 2; + readonly UP: 4; + readonly DOWN: 8; +}; +export declare type Directions = typeof Directions[keyof typeof Directions]; diff --git a/lib/typescript/EventType.d.ts b/lib/typescript/EventType.d.ts new file mode 100644 index 0000000000..2f404d8753 --- /dev/null +++ b/lib/typescript/EventType.d.ts @@ -0,0 +1,8 @@ +export declare const EventType: { + readonly UNDETERMINED: 0; + readonly TOUCHES_DOWN: 1; + readonly TOUCHES_MOVE: 2; + readonly TOUCHES_UP: 3; + readonly TOUCHES_CANCELLED: 4; +}; +export declare type EventType = typeof EventType[keyof typeof EventType]; diff --git a/lib/typescript/GestureHandlerRootView.android.d.ts b/lib/typescript/GestureHandlerRootView.android.d.ts new file mode 100644 index 0000000000..db5d1136e6 --- /dev/null +++ b/lib/typescript/GestureHandlerRootView.android.d.ts @@ -0,0 +1,2 @@ +import { GestureHandlerRootViewProps } from './GestureHandlerRootView'; +export default function GestureHandlerRootView({ children, ...rest }: GestureHandlerRootViewProps): JSX.Element; diff --git a/lib/typescript/GestureHandlerRootView.d.ts b/lib/typescript/GestureHandlerRootView.d.ts new file mode 100644 index 0000000000..de3ece198a --- /dev/null +++ b/lib/typescript/GestureHandlerRootView.d.ts @@ -0,0 +1,5 @@ +import { PropsWithChildren } from 'react'; +import { ViewProps } from 'react-native'; +export interface GestureHandlerRootViewProps extends PropsWithChildren { +} +export default function GestureHandlerRootView({ ...rest }: GestureHandlerRootViewProps): JSX.Element; diff --git a/lib/typescript/PlatformConstants.d.ts b/lib/typescript/PlatformConstants.d.ts new file mode 100644 index 0000000000..d9fa237405 --- /dev/null +++ b/lib/typescript/PlatformConstants.d.ts @@ -0,0 +1,5 @@ +declare type PlatformConstants = { + forceTouchAvailable: boolean; +}; +declare const _default: PlatformConstants; +export default _default; diff --git a/lib/typescript/PlatformConstants.web.d.ts b/lib/typescript/PlatformConstants.web.d.ts new file mode 100644 index 0000000000..7b53029ee8 --- /dev/null +++ b/lib/typescript/PlatformConstants.web.d.ts @@ -0,0 +1,4 @@ +declare const _default: { + readonly forceTouchAvailable: boolean; +}; +export default _default; diff --git a/lib/typescript/RNGestureHandlerModule.d.ts b/lib/typescript/RNGestureHandlerModule.d.ts new file mode 100644 index 0000000000..45aae5948a --- /dev/null +++ b/lib/typescript/RNGestureHandlerModule.d.ts @@ -0,0 +1,10 @@ +export declare type RNGestureHandlerModuleProps = { + handleSetJSResponder: (tag: number, blockNativeResponder: boolean) => void; + handleClearJSResponder: () => void; + createGestureHandler: (handlerName: string, handlerTag: number, config: Readonly>) => void; + attachGestureHandler: (handlerTag: number, newView: number, usingDeviceEvents: boolean) => void; + updateGestureHandler: (handlerTag: number, newConfig: Readonly>) => void; + dropGestureHandler: (handlerTag: number) => void; +}; +declare const _default: RNGestureHandlerModuleProps; +export default _default; diff --git a/lib/typescript/RNGestureHandlerModule.web.d.ts b/lib/typescript/RNGestureHandlerModule.web.d.ts new file mode 100644 index 0000000000..12174311e6 --- /dev/null +++ b/lib/typescript/RNGestureHandlerModule.web.d.ts @@ -0,0 +1,32 @@ +import FlingGestureHandler from './web/FlingGestureHandler'; +import LongPressGestureHandler from './web/LongPressGestureHandler'; +import NativeViewGestureHandler from './web/NativeViewGestureHandler'; +import PanGestureHandler from './web/PanGestureHandler'; +import PinchGestureHandler from './web/PinchGestureHandler'; +import RotationGestureHandler from './web/RotationGestureHandler'; +import TapGestureHandler from './web/TapGestureHandler'; +export declare const Gestures: { + PanGestureHandler: typeof PanGestureHandler; + RotationGestureHandler: typeof RotationGestureHandler; + PinchGestureHandler: typeof PinchGestureHandler; + TapGestureHandler: typeof TapGestureHandler; + NativeViewGestureHandler: typeof NativeViewGestureHandler; + LongPressGestureHandler: typeof LongPressGestureHandler; + FlingGestureHandler: typeof FlingGestureHandler; +}; +declare const _default: { + Direction: { + RIGHT: number; + LEFT: number; + UP: number; + DOWN: number; + }; + handleSetJSResponder(tag: number, blockNativeResponder: boolean): void; + handleClearJSResponder(): void; + createGestureHandler(handlerName: keyof typeof Gestures, handlerTag: number, config: T): void; + attachGestureHandler(handlerTag: number, newView: number, _usingDeviceEvents: boolean, propsRef: React.RefObject): void; + updateGestureHandler(handlerTag: number, newConfig: any): void; + getGestureHandlerNode(handlerTag: number): PanGestureHandler | RotationGestureHandler | PinchGestureHandler | TapGestureHandler | NativeViewGestureHandler | LongPressGestureHandler | FlingGestureHandler; + dropGestureHandler(handlerTag: number): void; +}; +export default _default; diff --git a/lib/typescript/State.d.ts b/lib/typescript/State.d.ts new file mode 100644 index 0000000000..04cc91f62c --- /dev/null +++ b/lib/typescript/State.d.ts @@ -0,0 +1,9 @@ +export declare const State: { + readonly UNDETERMINED: 0; + readonly FAILED: 1; + readonly BEGAN: 2; + readonly CANCELLED: 3; + readonly ACTIVE: 4; + readonly END: 5; +}; +export declare type State = typeof State[keyof typeof State]; diff --git a/lib/typescript/components/DrawerLayout.d.ts b/lib/typescript/components/DrawerLayout.d.ts new file mode 100644 index 0000000000..fc2dcdb427 --- /dev/null +++ b/lib/typescript/components/DrawerLayout.d.ts @@ -0,0 +1,130 @@ +import * as React from 'react'; +import { Component } from 'react'; +import { Animated, StatusBarAnimation, StyleProp, ViewStyle } from 'react-native'; +import { PanGestureHandler } from '../handlers/PanGestureHandler'; +export declare type DrawerPosition = 'left' | 'right'; +export declare type DrawerState = 'Idle' | 'Dragging' | 'Settling'; +export declare type DrawerType = 'front' | 'back' | 'slide'; +export declare type DrawerLockMode = 'unlocked' | 'locked-closed' | 'locked-open'; +export declare type DrawerKeyboardDismissMode = 'none' | 'on-drag'; +export interface DrawerLayoutProps { + /** + * This attribute is present in the standard implementation already and is one + * of the required params. Gesture handler version of DrawerLayout make it + * possible for the function passed as `renderNavigationView` to take an + * Animated value as a parameter that indicates the progress of drawer + * opening/closing animation (progress value is 0 when closed and 1 when + * opened). This can be used by the drawer component to animated its children + * while the drawer is opening or closing. + */ + renderNavigationView: (progressAnimatedValue: Animated.Value) => React.ReactNode; + drawerPosition?: DrawerPosition; + drawerWidth?: number; + drawerBackgroundColor?: string; + drawerLockMode?: DrawerLockMode; + keyboardDismissMode?: DrawerKeyboardDismissMode; + /** + * Called when the drawer is closed. + */ + onDrawerClose?: () => void; + /** + * Called when the drawer is opened. + */ + onDrawerOpen?: () => void; + /** + * Called when the status of the drawer changes. + */ + onDrawerStateChanged?: (newState: DrawerState, drawerWillShow: boolean) => void; + useNativeAnimations?: boolean; + drawerType?: DrawerType; + /** + * Defines how far from the edge of the content view the gesture should + * activate. + */ + edgeWidth?: number; + minSwipeDistance?: number; + /** + * When set to true Drawer component will use + * {@link https://reactnative.dev/docs/statusbar StatusBar} API to hide the OS + * status bar whenever the drawer is pulled or when its in an "open" state. + */ + hideStatusBar?: boolean; + /** + * @default 'slide' + * + * Can be used when hideStatusBar is set to true and will select the animation + * used for hiding/showing the status bar. See + * {@link https://reactnative.dev/docs/statusbar StatusBar} documentation for + * more details + */ + statusBarAnimation?: StatusBarAnimation; + /** + * @default black + * + * Color of a semi-transparent overlay to be displayed on top of the content + * view when drawer gets open. A solid color should be used as the opacity is + * added by the Drawer itself and the opacity of the overlay is animated (from + * 0% to 70%). + */ + overlayColor?: string; + contentContainerStyle?: StyleProp; + drawerContainerStyle?: StyleProp; + /** + * Enables two-finger gestures on supported devices, for example iPads with + * trackpads. If not enabled the gesture will require click + drag, with + * `enableTrackpadTwoFingerGesture` swiping with two fingers will also trigger + * the gesture. + */ + enableTrackpadTwoFingerGesture?: boolean; + onDrawerSlide?: (position: number) => void; + onGestureRef?: (ref: PanGestureHandler) => void; +} +export declare type DrawerLayoutState = { + dragX: Animated.Value; + touchX: Animated.Value; + drawerTranslation: Animated.Value; + containerWidth: number; +}; +export declare type DrawerMovementOption = { + velocity?: number; + speed?: number; +}; +export default class DrawerLayout extends Component { + static defaultProps: { + drawerWidth: number; + drawerPosition: string; + useNativeAnimations: boolean; + drawerType: string; + edgeWidth: number; + minSwipeDistance: number; + overlayColor: string; + drawerLockMode: string; + enableTrackpadTwoFingerGesture: boolean; + }; + constructor(props: DrawerLayoutProps); + UNSAFE_componentWillUpdate(props: DrawerLayoutProps, state: DrawerLayoutState): void; + private openValue?; + private onGestureEvent?; + private accessibilityIsModalView; + private pointerEventsView; + private panGestureHandler; + private drawerShown; + static positions: { + Left: string; + Right: string; + }; + private updateAnimatedEvent; + private handleContainerLayout; + private emitStateChanged; + private openingHandlerStateChange; + private onTapHandlerStateChange; + private handleRelease; + private updateShowing; + private animateDrawer; + openDrawer: (options?: DrawerMovementOption) => void; + closeDrawer: (options?: DrawerMovementOption) => void; + private renderOverlay; + private renderDrawer; + private setPanGestureRef; + render(): JSX.Element; +} diff --git a/lib/typescript/components/GestureButtons.d.ts b/lib/typescript/components/GestureButtons.d.ts new file mode 100644 index 0000000000..44ec47d322 --- /dev/null +++ b/lib/typescript/components/GestureButtons.d.ts @@ -0,0 +1,87 @@ +import * as React from 'react'; +import { StyleProp, ViewStyle } from 'react-native'; +import { NativeViewGestureHandlerProps } from '../handlers/NativeViewGestureHandler'; +export interface RawButtonProps extends NativeViewGestureHandlerProps { + /** + * Defines if more than one button could be pressed simultaneously. By default + * set true. + */ + exclusive?: boolean; + /** + * Android only. + * + * Defines color of native ripple animation used since API level 21. + */ + rippleColor?: any; +} +export interface BaseButtonProps extends RawButtonProps { + /** + * Called when the button gets pressed (analogous to `onPress` in + * `TouchableHighlight` from RN core). + */ + onPress?: (pointerInside: boolean) => void; + /** + * Called when button changes from inactive to active and vice versa. It + * passes active state as a boolean variable as a first parameter for that + * method. + */ + onActiveStateChange?: (active: boolean) => void; + style?: StyleProp; + testID?: string; +} +export interface RectButtonProps extends BaseButtonProps { + /** + * Background color that will be dimmed when button is in active state. + */ + underlayColor?: string; + /** + * iOS only. + * + * Opacity applied to the underlay when button is in active state. + */ + activeOpacity?: number; +} +export interface BorderlessButtonProps extends BaseButtonProps { + /** + * Android only. + * + * Set this to false if you want the ripple animation to render only within view bounds. + */ + borderless?: boolean; + /** + * iOS only. + * + * Opacity applied to the button when it is in an active state. + */ + activeOpacity?: number; +} +export declare const RawButton: React.ForwardRefExoticComponent>>; +export declare class BaseButton extends React.Component { + private lastActive; + constructor(props: BaseButtonProps); + private handleEvent; + private onHandlerStateChange; + private onGestureEvent; + render(): JSX.Element; +} +export declare class RectButton extends React.Component { + static defaultProps: { + activeOpacity: number; + underlayColor: string; + }; + private opacity; + constructor(props: RectButtonProps); + private onActiveStateChange; + render(): JSX.Element; +} +export declare class BorderlessButton extends React.Component { + static defaultProps: { + activeOpacity: number; + borderless: boolean; + }; + private opacity; + constructor(props: BorderlessButtonProps); + private onActiveStateChange; + render(): JSX.Element; +} +export { default as PureNativeButton } from './GestureHandlerButton'; diff --git a/lib/typescript/components/GestureComponents.d.ts b/lib/typescript/components/GestureComponents.d.ts new file mode 100644 index 0000000000..ce788b57dd --- /dev/null +++ b/lib/typescript/components/GestureComponents.d.ts @@ -0,0 +1,18 @@ +import * as React from 'react'; +import { PropsWithChildren, ForwardedRef, RefAttributes, ReactElement } from 'react'; +import { ScrollView as RNScrollView, ScrollViewProps as RNScrollViewProps, Switch as RNSwitch, SwitchProps as RNSwitchProps, TextInput as RNTextInput, TextInputProps as RNTextInputProps, DrawerLayoutAndroid as RNDrawerLayoutAndroid, DrawerLayoutAndroidProps as RNDrawerLayoutAndroidProps, FlatList as RNFlatList, FlatListProps as RNFlatListProps } from 'react-native'; +import { NativeViewGestureHandlerProps } from '../handlers/NativeViewGestureHandler'; +export declare const ScrollView: React.ForwardRefExoticComponent>>; +export declare type ScrollView = typeof ScrollView & RNScrollView; +export declare const Switch: React.ForwardRefExoticComponent>>; +export declare type Switch = typeof Switch & RNSwitch; +export declare const TextInput: React.ForwardRefExoticComponent>>; +export declare type TextInput = typeof TextInput & RNTextInput; +export declare const DrawerLayoutAndroid: React.ForwardRefExoticComponent>>; +export declare type DrawerLayoutAndroid = typeof DrawerLayoutAndroid & RNDrawerLayoutAndroid; +export declare const FlatList: (props: React.PropsWithChildren & React.RefAttributes> & NativeViewGestureHandlerProps>, ref: React.ForwardedRef>) => ReactElement | null; +export declare type FlatList = typeof FlatList & RNFlatList; diff --git a/lib/typescript/components/GestureComponents.web.d.ts b/lib/typescript/components/GestureComponents.web.d.ts new file mode 100644 index 0000000000..0b39f65005 --- /dev/null +++ b/lib/typescript/components/GestureComponents.web.d.ts @@ -0,0 +1,7 @@ +import * as React from 'react'; +import { FlatListProps } from 'react-native'; +export declare const ScrollView: React.ForwardRefExoticComponent>>; +export declare const Switch: React.ForwardRefExoticComponent>>; +export declare const TextInput: React.ForwardRefExoticComponent>>; +export declare const DrawerLayoutAndroid: React.ForwardRefExoticComponent>>; +export declare const FlatList: React.ForwardRefExoticComponent & React.RefAttributes>; diff --git a/lib/typescript/components/GestureHandlerButton.d.ts b/lib/typescript/components/GestureHandlerButton.d.ts new file mode 100644 index 0000000000..db68ffdd9c --- /dev/null +++ b/lib/typescript/components/GestureHandlerButton.d.ts @@ -0,0 +1,4 @@ +import { HostComponent } from 'react-native'; +import { RawButtonProps } from './GestureButtons'; +declare const RNGestureHandlerButton: HostComponent; +export default RNGestureHandlerButton; diff --git a/lib/typescript/components/GestureHandlerButton.web.d.ts b/lib/typescript/components/GestureHandlerButton.web.d.ts new file mode 100644 index 0000000000..2e71ae6dbc --- /dev/null +++ b/lib/typescript/components/GestureHandlerButton.web.d.ts @@ -0,0 +1,4 @@ +import * as React from 'react'; +import { View } from 'react-native'; +declare const _default: React.ForwardRefExoticComponent>; +export default _default; diff --git a/lib/typescript/components/Swipeable.d.ts b/lib/typescript/components/Swipeable.d.ts new file mode 100644 index 0000000000..53f71452ef --- /dev/null +++ b/lib/typescript/components/Swipeable.d.ts @@ -0,0 +1,150 @@ +import * as React from 'react'; +import { Component } from 'react'; +import { Animated, StyleProp, ViewStyle } from 'react-native'; +import { PanGestureHandlerProps } from '../handlers/PanGestureHandler'; +declare type SwipeableExcludes = Exclude; +export interface SwipeableProps extends Pick { + /** + * Enables two-finger gestures on supported devices, for example iPads with + * trackpads. If not enabled the gesture will require click + drag, with + * `enableTrackpadTwoFingerGesture` swiping with two fingers will also trigger + * the gesture. + */ + enableTrackpadTwoFingerGesture?: boolean; + /** + * Specifies how much the visual interaction will be delayed compared to the + * gesture distance. e.g. value of 1 will indicate that the swipeable panel + * should exactly follow the gesture, 2 means it is going to be two times + * "slower". + */ + friction?: number; + /** + * Distance from the left edge at which released panel will animate to the + * open state (or the open panel will animate into the closed state). By + * default it's a half of the panel's width. + */ + leftThreshold?: number; + /** + * Distance from the right edge at which released panel will animate to the + * open state (or the open panel will animate into the closed state). By + * default it's a half of the panel's width. + */ + rightThreshold?: number; + /** + * Value indicating if the swipeable panel can be pulled further than the left + * actions panel's width. It is set to true by default as long as the left + * panel render method is present. + */ + overshootLeft?: boolean; + /** + * Value indicating if the swipeable panel can be pulled further than the + * right actions panel's width. It is set to true by default as long as the + * right panel render method is present. + */ + overshootRight?: boolean; + /** + * Specifies how much the visual interaction will be delayed compared to the + * gesture distance at overshoot. Default value is 1, it mean no friction, for + * a native feel, try 8 or above. + */ + overshootFriction?: number; + /** + * Called when left action panel gets open. + */ + onSwipeableLeftOpen?: () => void; + /** + * Called when right action panel gets open. + */ + onSwipeableRightOpen?: () => void; + /** + * Called when action panel gets open (either right or left). + */ + onSwipeableOpen?: () => void; + /** + * Called when action panel is closed. + */ + onSwipeableClose?: () => void; + /** + * Called when left action panel starts animating on open. + */ + onSwipeableLeftWillOpen?: () => void; + /** + * Called when right action panel starts animating on open. + */ + onSwipeableRightWillOpen?: () => void; + /** + * Called when action panel starts animating on open (either right or left). + */ + onSwipeableWillOpen?: () => void; + /** + * Called when action panel starts animating on close. + */ + onSwipeableWillClose?: () => void; + /** + * + * This map describes the values to use as inputRange for extra interpolation: + * AnimatedValue: [startValue, endValue] + * + * progressAnimatedValue: [0, 1] dragAnimatedValue: [0, +] + * + * To support `rtl` flexbox layouts use `flexDirection` styling. + * */ + renderLeftActions?: (progressAnimatedValue: Animated.AnimatedInterpolation, dragAnimatedValue: Animated.AnimatedInterpolation) => React.ReactNode; + /** + * + * This map describes the values to use as inputRange for extra interpolation: + * AnimatedValue: [startValue, endValue] + * + * progressAnimatedValue: [0, 1] dragAnimatedValue: [0, -] + * + * To support `rtl` flexbox layouts use `flexDirection` styling. + * */ + renderRightActions?: (progressAnimatedValue: Animated.AnimatedInterpolation, dragAnimatedValue: Animated.AnimatedInterpolation) => React.ReactNode; + useNativeAnimations?: boolean; + animationOptions?: Record; + /** + * Style object for the container (`Animated.View`), for example to override + * `overflow: 'hidden'`. + */ + containerStyle?: StyleProp; + /** + * Style object for the children container (`Animated.View`), for example to + * apply `flex: 1` + */ + childrenContainerStyle?: StyleProp; +} +declare type SwipeableState = { + dragX: Animated.Value; + rowTranslation: Animated.Value; + rowState: number; + leftWidth?: number; + rightOffset?: number; + rowWidth?: number; +}; +export default class Swipeable extends Component { + static defaultProps: { + friction: number; + overshootFriction: number; + useNativeAnimations: boolean; + }; + constructor(props: SwipeableProps); + UNSAFE_componentWillUpdate(props: SwipeableProps, state: SwipeableState): void; + private onGestureEvent?; + private transX?; + private showLeftAction?; + private leftActionTranslate?; + private showRightAction?; + private rightActionTranslate?; + private updateAnimatedEvent; + private onTapHandlerStateChange; + private onHandlerStateChange; + private handleRelease; + private animateRow; + private onRowLayout; + private currentOffset; + close: () => void; + openLeft: () => void; + openRight: () => void; + render(): JSX.Element; +} +export {}; diff --git a/lib/typescript/components/touchables/GenericTouchable.d.ts b/lib/typescript/components/touchables/GenericTouchable.d.ts new file mode 100644 index 0000000000..cf0a0a6ffd --- /dev/null +++ b/lib/typescript/components/touchables/GenericTouchable.d.ts @@ -0,0 +1,66 @@ +import { Component } from 'react'; +import { StyleProp, ViewStyle, TouchableWithoutFeedbackProps } from 'react-native'; +import { GestureEvent, HandlerStateChangeEvent } from '../../handlers/gestureHandlerCommon'; +import { NativeViewGestureHandlerPayload } from '../../handlers/NativeViewGestureHandler'; +import { TouchableNativeFeedbackExtraProps } from './TouchableNativeFeedback.android'; +/** + * Each touchable is a states' machine which preforms transitions. + * On very beginning (and on the very end or recognition) touchable is + * UNDETERMINED. Then it moves to BEGAN. If touchable recognizes that finger + * travel outside it transits to special MOVED_OUTSIDE state. Gesture recognition + * finishes in UNDETERMINED state. + */ +export declare const TOUCHABLE_STATE: { + readonly UNDETERMINED: 0; + readonly BEGAN: 1; + readonly MOVED_OUTSIDE: 2; +}; +declare type TouchableState = typeof TOUCHABLE_STATE[keyof typeof TOUCHABLE_STATE]; +export interface GenericTouchableProps extends TouchableWithoutFeedbackProps { + onPress?: () => void; + onPressIn?: () => void; + onPressOut?: () => void; + onLongPress?: () => void; + nativeID?: string; + shouldActivateOnStart?: boolean; + disallowInterruption?: boolean; + containerStyle?: StyleProp; +} +interface InternalProps { + extraButtonProps: TouchableNativeFeedbackExtraProps; + onStateChange?: (oldState: TouchableState, newState: TouchableState) => void; +} +declare type Timeout = ReturnType | null | undefined; +/** + * GenericTouchable is not intented to be used as it is. + * Should be treated as a source for the rest of touchables + */ +export default class GenericTouchable extends Component { + static defaultProps: { + delayLongPress: number; + extraButtonProps: { + rippleColor: string; + exclusive: boolean; + }; + }; + pressInTimeout: Timeout; + pressOutTimeout: Timeout; + longPressTimeout: Timeout; + longPressDetected: boolean; + pointerInside: boolean; + STATE: TouchableState; + handlePressIn(): void; + handleMoveOutside(): void; + handleGoToUndetermined(): void; + componentDidMount(): void; + reset(): void; + moveToState(newState: TouchableState): void; + onGestureEvent: ({ nativeEvent: { pointerInside }, }: GestureEvent) => void; + onHandlerStateChange: ({ nativeEvent, }: HandlerStateChangeEvent) => void; + onLongPressDetected: () => void; + componentWillUnmount(): void; + onMoveIn(): void; + onMoveOut(): void; + render(): JSX.Element; +} +export {}; diff --git a/lib/typescript/components/touchables/TouchableHighlight.d.ts b/lib/typescript/components/touchables/TouchableHighlight.d.ts new file mode 100644 index 0000000000..18b2b5a586 --- /dev/null +++ b/lib/typescript/components/touchables/TouchableHighlight.d.ts @@ -0,0 +1,34 @@ +import { Component } from 'react'; +import { GenericTouchableProps } from './GenericTouchable'; +import { TouchableHighlightProps, ColorValue } from 'react-native'; +interface State { + extraChildStyle: null | { + opacity?: number; + }; + extraUnderlayStyle: null | { + backgroundColor?: ColorValue; + }; +} +/** + * TouchableHighlight follows RN's implementation + */ +export default class TouchableHighlight extends Component { + static defaultProps: { + activeOpacity: number; + delayPressOut: number; + underlayColor: string; + delayLongPress: number; + extraButtonProps: { + rippleColor: string; + exclusive: boolean; + }; + }; + constructor(props: TouchableHighlightProps & GenericTouchableProps); + showUnderlay: () => void; + hasPressHandler: () => (((event: import("react-native").GestureResponderEvent) => void) & (() => void)) | undefined; + hideUnderlay: () => void; + renderChildren(): JSX.Element; + onStateChange: (_from: number, to: number) => void; + render(): JSX.Element; +} +export {}; diff --git a/lib/typescript/components/touchables/TouchableNativeFeedback.android.d.ts b/lib/typescript/components/touchables/TouchableNativeFeedback.android.d.ts new file mode 100644 index 0000000000..3cf5dc9ada --- /dev/null +++ b/lib/typescript/components/touchables/TouchableNativeFeedback.android.d.ts @@ -0,0 +1,43 @@ +import { TouchableNativeFeedbackProps, ColorValue } from 'react-native'; +import { Component } from 'react'; +import { GenericTouchableProps } from './GenericTouchable'; +export declare type TouchableNativeFeedbackExtraProps = { + borderless?: boolean; + rippleColor?: number | null; + rippleRadius?: number | null; + foreground?: boolean; +}; +/** + * TouchableNativeFeedback behaves slightly different than RN's TouchableNativeFeedback. + * There's small difference with handling long press ripple since RN's implementation calls + * ripple animation via bridge. This solution leaves all animations' handling for native components so + * it follows native behaviours. + */ +export default class TouchableNativeFeedback extends Component { + static defaultProps: { + useForeground: boolean; + extraButtonProps: { + rippleColor: null; + }; + delayLongPress: number; + }; + static SelectableBackground: (rippleRadius?: number | undefined) => { + type: string; + attribute: string; + rippleRadius: number | undefined; + }; + static SelectableBackgroundBorderless: (rippleRadius?: number | undefined) => { + type: string; + attribute: string; + rippleRadius: number | undefined; + }; + static Ripple: (color: ColorValue, borderless: boolean, rippleRadius?: number | undefined) => { + type: string; + color: string | symbol; + borderless: boolean; + rippleRadius: number | undefined; + }; + static canUseNativeForeground: () => boolean; + getExtraButtonProps(): TouchableNativeFeedbackExtraProps; + render(): JSX.Element; +} diff --git a/lib/typescript/components/touchables/TouchableNativeFeedback.d.ts b/lib/typescript/components/touchables/TouchableNativeFeedback.d.ts new file mode 100644 index 0000000000..add3ff6db0 --- /dev/null +++ b/lib/typescript/components/touchables/TouchableNativeFeedback.d.ts @@ -0,0 +1,2 @@ +import { TouchableNativeFeedback } from 'react-native'; +export default TouchableNativeFeedback; diff --git a/lib/typescript/components/touchables/TouchableOpacity.d.ts b/lib/typescript/components/touchables/TouchableOpacity.d.ts new file mode 100644 index 0000000000..bc90e69fb8 --- /dev/null +++ b/lib/typescript/components/touchables/TouchableOpacity.d.ts @@ -0,0 +1,21 @@ +import { Animated, TouchableOpacityProps } from 'react-native'; +import { GenericTouchableProps } from './GenericTouchable'; +import { Component } from 'react'; +/** + * TouchableOpacity bases on timing animation which has been used in RN's core + */ +export default class TouchableOpacity extends Component { + static defaultProps: { + activeOpacity: number; + delayLongPress: number; + extraButtonProps: { + rippleColor: string; + exclusive: boolean; + }; + }; + getChildStyleOpacityWithDefault: () => number; + opacity: Animated.Value; + setOpacityTo: (value: number, duration: number) => void; + onStateChange: (_from: number, to: number) => void; + render(): JSX.Element; +} diff --git a/lib/typescript/components/touchables/TouchableWithoutFeedback.d.ts b/lib/typescript/components/touchables/TouchableWithoutFeedback.d.ts new file mode 100644 index 0000000000..9f25968e7a --- /dev/null +++ b/lib/typescript/components/touchables/TouchableWithoutFeedback.d.ts @@ -0,0 +1,6 @@ +import * as React from 'react'; +import GenericTouchable, { GenericTouchableProps } from './GenericTouchable'; +declare const TouchableWithoutFeedback: React.ForwardRefExoticComponent>; +export default TouchableWithoutFeedback; diff --git a/lib/typescript/components/touchables/index.d.ts b/lib/typescript/components/touchables/index.d.ts new file mode 100644 index 0000000000..fa9ae12b3c --- /dev/null +++ b/lib/typescript/components/touchables/index.d.ts @@ -0,0 +1,4 @@ +export { default as TouchableNativeFeedback } from './TouchableNativeFeedback'; +export { default as TouchableWithoutFeedback } from './TouchableWithoutFeedback'; +export { default as TouchableOpacity } from './TouchableOpacity'; +export { default as TouchableHighlight } from './TouchableHighlight'; diff --git a/lib/typescript/gestureHandlerRootHOC.d.ts b/lib/typescript/gestureHandlerRootHOC.d.ts new file mode 100644 index 0000000000..52a9b52c59 --- /dev/null +++ b/lib/typescript/gestureHandlerRootHOC.d.ts @@ -0,0 +1,3 @@ +import * as React from 'react'; +import { StyleProp, ViewStyle } from 'react-native'; +export default function gestureHandlerRootHOC

(Component: React.ComponentType

, containerStyles?: StyleProp): React.ComponentType

; diff --git a/lib/typescript/handlers/FlingGestureHandler.d.ts b/lib/typescript/handlers/FlingGestureHandler.d.ts new file mode 100644 index 0000000000..b973fd043b --- /dev/null +++ b/lib/typescript/handlers/FlingGestureHandler.d.ts @@ -0,0 +1,33 @@ +import { BaseGestureHandlerProps } from './gestureHandlerCommon'; +export declare const flingGestureHandlerProps: readonly ["numberOfPointers", "direction"]; +export declare type FlingGestureHandlerEventPayload = { + x: number; + y: number; + absoluteX: number; + absoluteY: number; +}; +export interface FlingGestureConfig { + /** + * Expressed allowed direction of movement. It's possible to pass one or many + * directions in one parameter: + * + * ```js + * direction={Directions.RIGHT | Directions.LEFT} + * ``` + * + * or + * + * ```js + * direction={Directions.DOWN} + * ``` + */ + direction?: number; + /** + * Determine exact number of points required to handle the fling gesture. + */ + numberOfPointers?: number; +} +export interface FlingGestureHandlerProps extends BaseGestureHandlerProps, FlingGestureConfig { +} +export declare type FlingGestureHandler = typeof FlingGestureHandler; +export declare const FlingGestureHandler: import("react").ComponentType>; diff --git a/lib/typescript/handlers/ForceTouchGestureHandler.d.ts b/lib/typescript/handlers/ForceTouchGestureHandler.d.ts new file mode 100644 index 0000000000..e4b1f28f2d --- /dev/null +++ b/lib/typescript/handlers/ForceTouchGestureHandler.d.ts @@ -0,0 +1,43 @@ +import React from 'react'; +import { BaseGestureHandlerProps } from './gestureHandlerCommon'; +export declare const forceTouchGestureHandlerProps: readonly ["minForce", "maxForce", "feedbackOnActivation"]; +declare class ForceTouchFallback extends React.Component { + static forceTouchAvailable: boolean; + componentDidMount(): void; + render(): React.ReactNode; +} +export declare type ForceTouchGestureHandlerEventPayload = { + x: number; + y: number; + absoluteX: number; + absoluteY: number; + /** + * The pressure of a touch. + */ + force: number; +}; +export interface ForceTouchGestureConfig { + /** + * + * A minimal pressure that is required before handler can activate. Should be a + * value from range `[0.0, 1.0]`. Default is `0.2`. + */ + minForce?: number; + /** + * A maximal pressure that could be applied for handler. If the pressure is + * greater, handler fails. Should be a value from range `[0.0, 1.0]`. + */ + maxForce?: number; + /** + * Boolean value defining if haptic feedback has to be performed on + * activation. + */ + feedbackOnActivation?: boolean; +} +export interface ForceTouchGestureHandlerProps extends BaseGestureHandlerProps, ForceTouchGestureConfig { +} +export declare type ForceTouchGestureHandler = typeof ForceTouchGestureHandler & { + forceTouchAvailable: boolean; +}; +export declare const ForceTouchGestureHandler: typeof ForceTouchFallback | React.ComponentClass, any> | React.FunctionComponent>; +export {}; diff --git a/lib/typescript/handlers/LongPressGestureHandler.d.ts b/lib/typescript/handlers/LongPressGestureHandler.d.ts new file mode 100644 index 0000000000..0211ea0ce6 --- /dev/null +++ b/lib/typescript/handlers/LongPressGestureHandler.d.ts @@ -0,0 +1,55 @@ +import { BaseGestureHandlerProps } from './gestureHandlerCommon'; +export declare const longPressGestureHandlerProps: readonly ["minDurationMs", "maxDist"]; +export declare type LongPressGestureHandlerEventPayload = { + /** + * X coordinate, expressed in points, of the current position of the pointer + * (finger or a leading pointer when there are multiple fingers placed) + * relative to the view attached to the handler. + */ + x: number; + /** + * Y coordinate, expressed in points, of the current position of the pointer + * (finger or a leading pointer when there are multiple fingers placed) + * relative to the view attached to the handler. + */ + y: number; + /** + * X coordinate, expressed in points, of the current position of the pointer + * (finger or a leading pointer when there are multiple fingers placed) + * relative to the window. It is recommended to use `absoluteX` instead of + * `x` in cases when the view attached to the handler can be transformed as an + * effect of the gesture. + */ + absoluteX: number; + /** + * Y coordinate, expressed in points, of the current position of the pointer + * (finger or a leading pointer when there are multiple fingers placed) + * relative to the window. It is recommended to use `absoluteY` instead of + * `y` in cases when the view attached to the handler can be transformed as an + * effect of the gesture. + */ + absoluteY: number; + /** + * Duration of the long press (time since the start of the event), expressed + * in milliseconds. + */ + duration: number; +}; +export interface LongPressGestureConfig { + /** + * Minimum time, expressed in milliseconds, that a finger must remain pressed on + * the corresponding view. The default value is 500. + */ + minDurationMs?: number; + /** + * Maximum distance, expressed in points, that defines how far the finger is + * allowed to travel during a long press gesture. If the finger travels + * further than the defined distance and the handler hasn't yet activated, it + * will fail to recognize the gesture. The default value is 10. + */ + maxDist?: number; +} +export interface LongPressGestureHandlerProps extends BaseGestureHandlerProps, LongPressGestureConfig { +} +export declare type LongPressGestureHandler = typeof LongPressGestureHandler; +export declare const LongPressGestureHandler: import("react").ComponentType>; diff --git a/lib/typescript/handlers/NativeViewGestureHandler.d.ts b/lib/typescript/handlers/NativeViewGestureHandler.d.ts new file mode 100644 index 0000000000..ab9ec0cdef --- /dev/null +++ b/lib/typescript/handlers/NativeViewGestureHandler.d.ts @@ -0,0 +1,27 @@ +import { BaseGestureHandlerProps } from './gestureHandlerCommon'; +export declare const nativeViewGestureHandlerProps: readonly ["shouldActivateOnStart", "disallowInterruption"]; +export interface NativeViewGestureConfig { + /** + * Android only. + * + * Determines whether the handler should check for an existing touch event on + * instantiation. + */ + shouldActivateOnStart?: boolean; + /** + * When `true`, cancels all other gesture handlers when this + * `NativeViewGestureHandler` receives an `ACTIVE` state event. + */ + disallowInterruption?: boolean; +} +export interface NativeViewGestureHandlerProps extends BaseGestureHandlerProps, NativeViewGestureConfig { +} +export declare type NativeViewGestureHandlerPayload = { + /** + * True if gesture was performed inside of containing view, false otherwise. + */ + pointerInside: boolean; +}; +export declare const nativeViewProps: readonly ["id", "enabled", "shouldCancelWhenOutside", "hitSlop", "waitFor", "simultaneousHandlers", "onBegan", "onFailed", "onCancelled", "onActivated", "onEnded", "onGestureEvent", "onHandlerStateChange", "shouldActivateOnStart", "disallowInterruption"]; +export declare type NativeViewGestureHandler = typeof NativeViewGestureHandler; +export declare const NativeViewGestureHandler: import("react").ComponentType>; diff --git a/lib/typescript/handlers/PanGestureHandler.d.ts b/lib/typescript/handlers/PanGestureHandler.d.ts new file mode 100644 index 0000000000..f8d6849369 --- /dev/null +++ b/lib/typescript/handlers/PanGestureHandler.d.ts @@ -0,0 +1,137 @@ +import { BaseGestureHandlerProps } from './gestureHandlerCommon'; +export declare const panGestureHandlerProps: readonly ["activeOffsetY", "activeOffsetX", "failOffsetY", "failOffsetX", "minDist", "minVelocity", "minVelocityX", "minVelocityY", "minPointers", "maxPointers", "avgTouches", "enableTrackpadTwoFingerGesture"]; +export declare const panGestureHandlerCustomNativeProps: readonly ["activeOffsetYStart", "activeOffsetYEnd", "activeOffsetXStart", "activeOffsetXEnd", "failOffsetYStart", "failOffsetYEnd", "failOffsetXStart", "failOffsetXEnd"]; +export declare type PanGestureHandlerEventPayload = { + /** + * X coordinate of the current position of the pointer (finger or a leading + * pointer when there are multiple fingers placed) relative to the view + * attached to the handler. Expressed in point units. + */ + x: number; + /** + * Y coordinate of the current position of the pointer (finger or a leading + * pointer when there are multiple fingers placed) relative to the view + * attached to the handler. Expressed in point units. + */ + y: number; + /** + * X coordinate of the current position of the pointer (finger or a leading + * pointer when there are multiple fingers placed) relative to the window. + * The value is expressed in point units. It is recommended to use it instead + * of `x` in cases when the original view can be transformed as an effect of + * the gesture. + */ + absoluteX: number; + /** + * Y coordinate of the current position of the pointer (finger or a leading + * pointer when there are multiple fingers placed) relative to the window. + * The value is expressed in point units. It is recommended to use it instead + * of `y` in cases when the original view can be transformed as an + * effect of the gesture. + */ + absoluteY: number; + /** + * Translation of the pan gesture along X axis accumulated over the time of + * the gesture. The value is expressed in the point units. + */ + translationX: number; + /** + * Translation of the pan gesture along Y axis accumulated over the time of + * the gesture. The value is expressed in the point units. + */ + translationY: number; + /** + * Velocity of the pan gesture along the X axis in the current moment. The + * value is expressed in point units per second. + */ + velocityX: number; + /** + * Velocity of the pan gesture along the Y axis in the current moment. The + * value is expressed in point units per second. + */ + velocityY: number; +}; +interface CommonPanProperties { + /** + * Minimum distance the finger (or multiple finger) need to travel before the + * handler activates. Expressed in points. + */ + minDist?: number; + /** + * Android only. + */ + avgTouches?: boolean; + /** + * Enables two-finger gestures on supported devices, for example iPads with + * trackpads. If not enabled the gesture will require click + drag, with + * enableTrackpadTwoFingerGesture swiping with two fingers will also trigger + * the gesture. + */ + enableTrackpadTwoFingerGesture?: boolean; + /** + * A number of fingers that is required to be placed before handler can + * activate. Should be a higher or equal to 0 integer. + */ + minPointers?: number; + /** + * When the given number of fingers is placed on the screen and handler hasn't + * yet activated it will fail recognizing the gesture. Should be a higher or + * equal to 0 integer. + */ + maxPointers?: number; + minVelocity?: number; + minVelocityX?: number; + minVelocityY?: number; +} +export interface PanGestureConfig extends CommonPanProperties { + activeOffsetYStart?: number; + activeOffsetYEnd?: number; + activeOffsetXStart?: number; + activeOffsetXEnd?: number; + failOffsetYStart?: number; + failOffsetYEnd?: number; + failOffsetXStart?: number; + failOffsetXEnd?: number; +} +export interface PanGestureHandlerProps extends BaseGestureHandlerProps, CommonPanProperties { + /** + * Range along X axis (in points) where fingers travels without activation of + * handler. Moving outside of this range implies activation of handler. Range + * can be given as an array or a single number. If range is set as an array, + * first value must be lower or equal to 0, a the second one higher or equal + * to 0. If only one number `p` is given a range of `(-inf, p)` will be used + * if `p` is higher or equal to 0 and `(-p, inf)` otherwise. + */ + activeOffsetY?: number | number[]; + /** + * Range along X axis (in points) where fingers travels without activation of + * handler. Moving outside of this range implies activation of handler. Range + * can be given as an array or a single number. If range is set as an array, + * first value must be lower or equal to 0, a the second one higher or equal + * to 0. If only one number `p` is given a range of `(-inf, p)` will be used + * if `p` is higher or equal to 0 and `(-p, inf)` otherwise. + */ + activeOffsetX?: number | number[]; + /** + * When the finger moves outside this range (in points) along Y axis and + * handler hasn't yet activated it will fail recognizing the gesture. Range + * can be given as an array or a single number. If range is set as an array, + * first value must be lower or equal to 0, a the second one higher or equal + * to 0. If only one number `p` is given a range of `(-inf, p)` will be used + * if `p` is higher or equal to 0 and `(-p, inf)` otherwise. + */ + failOffsetY?: number | number[]; + /** + * When the finger moves outside this range (in points) along X axis and + * handler hasn't yet activated it will fail recognizing the gesture. Range + * can be given as an array or a single number. If range is set as an array, + * first value must be lower or equal to 0, a the second one higher or equal + * to 0. If only one number `p` is given a range of `(-inf, p)` will be used + * if `p` is higher or equal to 0 and `(-p, inf)` otherwise. + */ + failOffsetX?: number | number[]; +} +export declare type PanGestureHandler = typeof PanGestureHandler; +export declare const PanGestureHandler: import("react").ComponentType>; +export declare function managePanProps(props: PanGestureHandlerProps): PanGestureHandlerProps & Partial>; +export {}; diff --git a/lib/typescript/handlers/PinchGestureHandler.d.ts b/lib/typescript/handlers/PinchGestureHandler.d.ts new file mode 100644 index 0000000000..554db2d891 --- /dev/null +++ b/lib/typescript/handlers/PinchGestureHandler.d.ts @@ -0,0 +1,28 @@ +import { BaseGestureHandlerProps } from './gestureHandlerCommon'; +export declare type PinchGestureHandlerEventPayload = { + /** + * The scale factor relative to the points of the two touches in screen + * coordinates. + */ + scale: number; + /** + * Position expressed in points along X axis of center anchor point of + * gesture. + */ + focalX: number; + /** + * Position expressed in points along Y axis of center anchor point of + * gesture. + */ + focalY: number; + /** + * + * Velocity of the pan gesture the current moment. The value is expressed in + * point units per second. + */ + velocity: number; +}; +export interface PinchGestureHandlerProps extends BaseGestureHandlerProps { +} +export declare type PinchGestureHandler = typeof PinchGestureHandler; +export declare const PinchGestureHandler: import("react").ComponentType>; diff --git a/lib/typescript/handlers/RotationGestureHandler.d.ts b/lib/typescript/handlers/RotationGestureHandler.d.ts new file mode 100644 index 0000000000..e046bcca72 --- /dev/null +++ b/lib/typescript/handlers/RotationGestureHandler.d.ts @@ -0,0 +1,28 @@ +import { BaseGestureHandlerProps } from './gestureHandlerCommon'; +export declare type RotationGestureHandlerEventPayload = { + /** + * Amount rotated, expressed in radians, from the gesture's focal point + * (anchor). + */ + rotation: number; + /** + * X coordinate, expressed in points, of the gesture's central focal point + * (anchor). + */ + anchorX: number; + /** + * Y coordinate, expressed in points, of the gesture's central focal point + * (anchor). + */ + anchorY: number; + /** + * + * Instantaneous velocity, expressed in point units per second, of the + * gesture. + */ + velocity: number; +}; +export interface RotationGestureHandlerProps extends BaseGestureHandlerProps { +} +export declare type RotationGestureHandler = typeof RotationGestureHandler; +export declare const RotationGestureHandler: import("react").ComponentType>; diff --git a/lib/typescript/handlers/TapGestureHandler.d.ts b/lib/typescript/handlers/TapGestureHandler.d.ts new file mode 100644 index 0000000000..8b2b832d8f --- /dev/null +++ b/lib/typescript/handlers/TapGestureHandler.d.ts @@ -0,0 +1,56 @@ +import { BaseGestureHandlerProps } from './gestureHandlerCommon'; +export declare const tapGestureHandlerProps: readonly ["maxDurationMs", "maxDelayMs", "numberOfTaps", "maxDeltaX", "maxDeltaY", "maxDist", "minPointers"]; +export declare type TapGestureHandlerEventPayload = { + x: number; + y: number; + absoluteX: number; + absoluteY: number; +}; +export interface TapGestureConfig { + /** + * Minimum number of pointers (fingers) required to be placed before the + * handler activates. Should be a positive integer. + * The default value is 1. + */ + minPointers?: number; + /** + * Maximum time, expressed in milliseconds, that defines how fast a finger + * must be released after a touch. The default value is 500. + */ + maxDurationMs?: number; + /** + * Maximum time, expressed in milliseconds, that can pass before the next tap + * if many taps are required. The default value is 500. + */ + maxDelayMs?: number; + /** + * Number of tap gestures required to activate the handler. The default value + * is 1. + */ + numberOfTaps?: number; + /** + * Maximum distance, expressed in points, that defines how far the finger is + * allowed to travel along the X axis during a tap gesture. If the finger + * travels further than the defined distance along the X axis and the handler + * hasn't yet activated, it will fail to recognize the gesture. + */ + maxDeltaX?: number; + /** + * Maximum distance, expressed in points, that defines how far the finger is + * allowed to travel along the Y axis during a tap gesture. If the finger + * travels further than the defined distance along the Y axis and the handler + * hasn't yet activated, it will fail to recognize the gesture. + */ + maxDeltaY?: number; + /** + * Maximum distance, expressed in points, that defines how far the finger is + * allowed to travel during a tap gesture. If the finger travels further than + * the defined distance and the handler hasn't yet + * activated, it will fail to recognize the gesture. + */ + maxDist?: number; +} +export interface TapGestureHandlerProps extends BaseGestureHandlerProps, TapGestureConfig { +} +export declare type TapGestureHandler = typeof TapGestureHandler; +export declare const TapGestureHandler: import("react").ComponentType>; diff --git a/lib/typescript/handlers/createHandler.d.ts b/lib/typescript/handlers/createHandler.d.ts new file mode 100644 index 0000000000..587824ee41 --- /dev/null +++ b/lib/typescript/handlers/createHandler.d.ts @@ -0,0 +1,11 @@ +import * as React from 'react'; +import { BaseGestureHandlerProps } from './gestureHandlerCommon'; +declare type CreateHandlerArgs> = Readonly<{ + name: string; + allowedProps: Readonly[]>; + config: Readonly>; + transformProps?: (props: HandlerPropsT) => HandlerPropsT; + customNativeProps?: Readonly; +}>; +export default function createHandler, U extends Record>({ name, allowedProps, config, transformProps, customNativeProps, }: CreateHandlerArgs): React.ComponentType>; +export {}; diff --git a/lib/typescript/handlers/createNativeWrapper.d.ts b/lib/typescript/handlers/createNativeWrapper.d.ts new file mode 100644 index 0000000000..2d1dbd8918 --- /dev/null +++ b/lib/typescript/handlers/createNativeWrapper.d.ts @@ -0,0 +1,3 @@ +import * as React from 'react'; +import { NativeViewGestureHandlerProps } from './NativeViewGestureHandler'; +export default function createNativeWrapper

(Component: React.ComponentType

, config?: Readonly): React.ForwardRefExoticComponent & React.RefAttributes>>; diff --git a/lib/typescript/handlers/gestureHandlerCommon.d.ts b/lib/typescript/handlers/gestureHandlerCommon.d.ts new file mode 100644 index 0000000000..608a10ffce --- /dev/null +++ b/lib/typescript/handlers/gestureHandlerCommon.d.ts @@ -0,0 +1,62 @@ +import * as React from 'react'; +import { State } from '../State'; +import { EventType } from '../EventType'; +import { ValueOf } from '../typeUtils'; +export declare const baseGestureHandlerProps: readonly ["id", "enabled", "shouldCancelWhenOutside", "hitSlop", "waitFor", "simultaneousHandlers", "onBegan", "onFailed", "onCancelled", "onActivated", "onEnded", "onGestureEvent", "onHandlerStateChange"]; +export declare const baseGestureHandlerWithMonitorProps: string[]; +export interface GestureEventPayload { + handlerTag: number; + numberOfPointers: number; + state: ValueOf; +} +export interface HandlerStateChangeEventPayload { + handlerTag: number; + numberOfPointers: number; + state: ValueOf; + oldState: ValueOf; +} +export declare type HitSlop = number | Partial> | Record<'width' | 'left', number> | Record<'width' | 'right', number> | Record<'height' | 'top', number> | Record<'height' | 'bottom', number>; +export interface GestureEvent> { + nativeEvent: Readonly; +} +export interface HandlerStateChangeEvent> { + nativeEvent: Readonly; +} +export declare type TouchData = { + id: number; + x: number; + y: number; + absoluteX: number; + absoluteY: number; +}; +export declare type GestureTouchEvent = { + handlerTag: number; + numberOfTouches: number; + state: ValueOf; + eventType: EventType; + allTouches: TouchData[]; + changedTouches: TouchData[]; +}; +export declare type GestureUpdateEvent> = GestureEventPayload & GestureEventPayloadT; +export declare type GestureStateChangeEvent> = HandlerStateChangeEventPayload & GestureStateChangeEventPayloadT; +export declare type CommonGestureConfig = { + enabled?: boolean; + shouldCancelWhenOutside?: boolean; + hitSlop?: HitSlop; +}; +export declare type BaseGestureHandlerProps = Record> = CommonGestureConfig & { + id?: string; + waitFor?: React.Ref | React.Ref[]; + simultaneousHandlers?: React.Ref | React.Ref[]; + onBegan?: (event: HandlerStateChangeEvent) => void; + onFailed?: (event: HandlerStateChangeEvent) => void; + onCancelled?: (event: HandlerStateChangeEvent) => void; + onActivated?: (event: HandlerStateChangeEvent) => void; + onEnded?: (event: HandlerStateChangeEvent) => void; + onGestureEvent?: (event: GestureEvent) => void; + onHandlerStateChange?: (event: HandlerStateChangeEvent) => void; +}; +export declare function filterConfig(props: Record, validProps: string[], defaults?: Record): { + [x: string]: unknown; +}; +export declare function findNodeHandle(node: null | number | React.Component | React.ComponentClass): null | number | React.Component | React.ComponentClass; diff --git a/lib/typescript/handlers/gestureHandlerTypesCompat.d.ts b/lib/typescript/handlers/gestureHandlerTypesCompat.d.ts new file mode 100644 index 0000000000..0645d0eedb --- /dev/null +++ b/lib/typescript/handlers/gestureHandlerTypesCompat.d.ts @@ -0,0 +1,42 @@ +import { BaseButtonProps, BorderlessButtonProps, RawButtonProps, RectButtonProps } from '../components/GestureButtons'; +import { GestureEvent, GestureEventPayload, HandlerStateChangeEvent, HandlerStateChangeEventPayload } from './gestureHandlerCommon'; +import { FlingGestureHandlerEventPayload, FlingGestureHandlerProps } from './FlingGestureHandler'; +import { ForceTouchGestureHandlerEventPayload, ForceTouchGestureHandlerProps } from './ForceTouchGestureHandler'; +import { LongPressGestureHandlerEventPayload, LongPressGestureHandlerProps } from './LongPressGestureHandler'; +import { PanGestureHandlerEventPayload, PanGestureHandlerProps } from './PanGestureHandler'; +import { PinchGestureHandlerEventPayload, PinchGestureHandlerProps } from './PinchGestureHandler'; +import { RotationGestureHandlerEventPayload, RotationGestureHandlerProps } from './RotationGestureHandler'; +import { TapGestureHandlerEventPayload, TapGestureHandlerProps } from './TapGestureHandler'; +import { NativeViewGestureHandlerPayload, NativeViewGestureHandlerProps } from './NativeViewGestureHandler'; +export declare type GestureHandlerGestureEventNativeEvent = GestureEventPayload; +export declare type GestureHandlerStateChangeNativeEvent = HandlerStateChangeEventPayload; +export declare type GestureHandlerGestureEvent = GestureEvent; +export declare type GestureHandlerStateChangeEvent = HandlerStateChangeEvent; +export declare type NativeViewGestureHandlerGestureEvent = GestureEvent; +export declare type NativeViewGestureHandlerStateChangeEvent = HandlerStateChangeEvent; +export declare type TapGestureHandlerGestureEvent = GestureEvent; +export declare type TapGestureHandlerStateChangeEvent = HandlerStateChangeEvent; +export declare type ForceTouchGestureHandlerGestureEvent = GestureEvent; +export declare type ForceTouchGestureHandlerStateChangeEvent = HandlerStateChangeEvent; +export declare type LongPressGestureHandlerGestureEvent = GestureEvent; +export declare type LongPressGestureHandlerStateChangeEvent = HandlerStateChangeEvent; +export declare type PanGestureHandlerGestureEvent = GestureEvent; +export declare type PanGestureHandlerStateChangeEvent = HandlerStateChangeEvent; +export declare type PinchGestureHandlerGestureEvent = GestureEvent; +export declare type PinchGestureHandlerStateChangeEvent = HandlerStateChangeEvent; +export declare type RotationGestureHandlerGestureEvent = GestureEvent; +export declare type RotationGestureHandlerStateChangeEvent = HandlerStateChangeEvent; +export declare type FlingGestureHandlerGestureEvent = GestureEvent; +export declare type FlingGestureHandlerStateChangeEvent = HandlerStateChangeEvent; +export declare type NativeViewGestureHandlerProperties = NativeViewGestureHandlerProps; +export declare type TapGestureHandlerProperties = TapGestureHandlerProps; +export declare type LongPressGestureHandlerProperties = LongPressGestureHandlerProps; +export declare type PanGestureHandlerProperties = PanGestureHandlerProps; +export declare type PinchGestureHandlerProperties = PinchGestureHandlerProps; +export declare type RotationGestureHandlerProperties = RotationGestureHandlerProps; +export declare type FlingGestureHandlerProperties = FlingGestureHandlerProps; +export declare type ForceTouchGestureHandlerProperties = ForceTouchGestureHandlerProps; +export declare type RawButtonProperties = RawButtonProps; +export declare type BaseButtonProperties = BaseButtonProps; +export declare type RectButtonProperties = RectButtonProps; +export declare type BorderlessButtonProperties = BorderlessButtonProps; diff --git a/lib/typescript/handlers/gestures/GestureDetector.d.ts b/lib/typescript/handlers/gestures/GestureDetector.d.ts new file mode 100644 index 0000000000..b98115d90c --- /dev/null +++ b/lib/typescript/handlers/gestures/GestureDetector.d.ts @@ -0,0 +1,16 @@ +import React from 'react'; +import { GestureType, HandlerCallbacks } from './gesture'; +import { SharedValue } from './reanimatedWrapper'; +import { ComposedGesture } from './gestureComposition'; +export declare type GestureConfigReference = { + config: GestureType[]; + animatedEventHandler: unknown; + animatedHandlers: SharedValue>[] | null> | null; + firstExecution: boolean; + useAnimated: boolean; +}; +interface GestureDetectorProps { + gesture?: ComposedGesture | GestureType; +} +export declare const GestureDetector: React.FunctionComponent; +export {}; diff --git a/lib/typescript/handlers/gestures/eventReceiver.d.ts b/lib/typescript/handlers/gestures/eventReceiver.d.ts new file mode 100644 index 0000000000..d6a47db66d --- /dev/null +++ b/lib/typescript/handlers/gestures/eventReceiver.d.ts @@ -0,0 +1,2 @@ +export declare function startListening(): void; +export declare function stopListening(): void; diff --git a/lib/typescript/handlers/gestures/flingGesture.d.ts b/lib/typescript/handlers/gestures/flingGesture.d.ts new file mode 100644 index 0000000000..4c8df93ee1 --- /dev/null +++ b/lib/typescript/handlers/gestures/flingGesture.d.ts @@ -0,0 +1,9 @@ +import { BaseGesture, BaseGestureConfig } from './gesture'; +import { FlingGestureConfig, FlingGestureHandlerEventPayload } from '../FlingGestureHandler'; +export declare class FlingGesture extends BaseGesture { + config: BaseGestureConfig & FlingGestureConfig; + constructor(); + numberOfPointers(pointers: number): this; + direction(direction: number): this; +} +export declare type FlingGestureType = InstanceType; diff --git a/lib/typescript/handlers/gestures/forceTouchGesture.d.ts b/lib/typescript/handlers/gestures/forceTouchGesture.d.ts new file mode 100644 index 0000000000..4d151d3e64 --- /dev/null +++ b/lib/typescript/handlers/gestures/forceTouchGesture.d.ts @@ -0,0 +1,16 @@ +import { BaseGestureConfig, ContinousBaseGesture } from './gesture'; +import { ForceTouchGestureConfig, ForceTouchGestureHandlerEventPayload } from '../ForceTouchGestureHandler'; +import { GestureUpdateEvent } from '../gestureHandlerCommon'; +declare type ForceTouchGestureChangeEventPayload = { + forceChange: number; +}; +export declare class ForceTouchGesture extends ContinousBaseGesture { + config: BaseGestureConfig & ForceTouchGestureConfig; + constructor(); + minForce(force: number): this; + maxForce(force: number): this; + feedbackOnActivation(value: boolean): this; + onChange(callback: (event: GestureUpdateEvent>) => void): this; +} +export declare type ForceTouchGestureType = InstanceType; +export {}; diff --git a/lib/typescript/handlers/gestures/gesture.d.ts b/lib/typescript/handlers/gestures/gesture.d.ts new file mode 100644 index 0000000000..11193a6e8b --- /dev/null +++ b/lib/typescript/handlers/gestures/gesture.d.ts @@ -0,0 +1,97 @@ +import { FlingGestureHandlerEventPayload } from '../FlingGestureHandler'; +import { ForceTouchGestureHandlerEventPayload } from '../ForceTouchGestureHandler'; +import { HitSlop, CommonGestureConfig, GestureTouchEvent, GestureStateChangeEvent, GestureUpdateEvent } from '../gestureHandlerCommon'; +import { GestureStateManagerType } from './gestureStateManager'; +import { LongPressGestureHandlerEventPayload } from '../LongPressGestureHandler'; +import { PanGestureHandlerEventPayload } from '../PanGestureHandler'; +import { PinchGestureHandlerEventPayload } from '../PinchGestureHandler'; +import { RotationGestureHandlerEventPayload } from '../RotationGestureHandler'; +import { TapGestureHandlerEventPayload } from '../TapGestureHandler'; +import { NativeViewGestureHandlerPayload } from '../NativeViewGestureHandler'; +export declare type GestureType = BaseGesture> | BaseGesture> | BaseGesture | BaseGesture | BaseGesture | BaseGesture | BaseGesture | BaseGesture | BaseGesture | BaseGesture; +export declare type GestureRef = number | GestureType | React.RefObject | React.RefObject; +export interface BaseGestureConfig extends CommonGestureConfig, Record { + ref?: React.MutableRefObject; + requireToFail?: GestureRef[]; + simultaneousWith?: GestureRef[]; + needsPointerData?: boolean; + manualActivation?: boolean; +} +declare type TouchEventHandlerType = (event: GestureTouchEvent, stateManager: GestureStateManagerType) => void; +export declare type HandlerCallbacks> = { + handlerTag: number; + onBegin?: (event: GestureStateChangeEvent) => void; + onStart?: (event: GestureStateChangeEvent) => void; + onEnd?: (event: GestureStateChangeEvent, success: boolean) => void; + onFinalize?: (event: GestureStateChangeEvent, success: boolean) => void; + onUpdate?: (event: GestureUpdateEvent) => void; + onChange?: (event: any) => void; + onTouchesDown?: TouchEventHandlerType; + onTouchesMove?: TouchEventHandlerType; + onTouchesUp?: TouchEventHandlerType; + onTouchesCancelled?: TouchEventHandlerType; + changeEventCalculator?: (current: GestureUpdateEvent>, previous?: GestureUpdateEvent>) => GestureUpdateEvent>; + isWorklet: boolean[]; +}; +export declare const CALLBACK_TYPE: { + readonly UNDEFINED: 0; + readonly BEGAN: 1; + readonly START: 2; + readonly UPDATE: 3; + readonly CHANGE: 4; + readonly END: 5; + readonly FINALIZE: 6; + readonly TOUCHES_DOWN: 7; + readonly TOUCHES_MOVE: 8; + readonly TOUCHES_UP: 9; + readonly TOUCHES_CANCELLED: 10; +}; +export declare type CALLBACK_TYPE = typeof CALLBACK_TYPE[keyof typeof CALLBACK_TYPE]; +export declare abstract class Gesture { + /** + * Return array of gestures, providing the same interface for creating and updating + * handlers, no matter which object was used to create gesture instance. + */ + abstract toGestureArray(): GestureType[]; + /** + * Assign handlerTag to the gesture instance and set ref.current (if a ref is set) + */ + abstract initialize(): void; + /** + * Make sure that values of properties defining relations are arrays. Do any necessary + * preprocessing required to configure relations between handlers. Called just before + * updating the handler on the native side. + */ + abstract prepare(): void; +} +export declare abstract class BaseGesture> extends Gesture { + handlerTag: number; + handlerName: string; + config: BaseGestureConfig; + handlers: HandlerCallbacks; + private addDependency; + withRef(ref: React.MutableRefObject): this; + protected isWorklet(callback: Function): boolean; + onBegin(callback: (event: GestureStateChangeEvent) => void): this; + onStart(callback: (event: GestureStateChangeEvent) => void): this; + onEnd(callback: (event: GestureStateChangeEvent, success: boolean) => void): this; + onFinalize(callback: (event: GestureStateChangeEvent, success: boolean) => void): this; + onTouchesDown(callback: TouchEventHandlerType): this; + onTouchesMove(callback: TouchEventHandlerType): this; + onTouchesUp(callback: TouchEventHandlerType): this; + onTouchesCancelled(callback: TouchEventHandlerType): this; + enabled(enabled: boolean): this; + shouldCancelWhenOutside(value: boolean): this; + hitSlop(hitSlop: HitSlop): this; + simultaneousWithExternalGesture(...gestures: Exclude[]): this; + requireExternalGestureToFail(...gestures: Exclude[]): this; + initialize(): void; + toGestureArray(): GestureType[]; + prepare(): void; +} +export declare abstract class ContinousBaseGesture, EventChangePayloadT extends Record> extends BaseGesture { + onUpdate(callback: (event: GestureUpdateEvent) => void): this; + onChange(callback: (event: GestureUpdateEvent) => void): this; + manualActivation(manualActivation: boolean): this; +} +export {}; diff --git a/lib/typescript/handlers/gestures/gestureComposition.d.ts b/lib/typescript/handlers/gestures/gestureComposition.d.ts new file mode 100644 index 0000000000..cd9da9ca39 --- /dev/null +++ b/lib/typescript/handlers/gestures/gestureComposition.d.ts @@ -0,0 +1,21 @@ +import { Gesture, GestureType } from './gesture'; +export declare class ComposedGesture extends Gesture { + protected gestures: Gesture[]; + protected simultaneousGestures: GestureType[]; + protected requireGesturesToFail: GestureType[]; + constructor(...gestures: Gesture[]); + protected prepareSingleGesture(gesture: Gesture, simultaneousGestures: GestureType[], requireGesturesToFail: GestureType[]): void; + prepare(): void; + initialize(): void; + toGestureArray(): GestureType[]; +} +export declare class SimultaneousGesture extends ComposedGesture { + prepare(): void; +} +export declare class ExclusiveGesture extends ComposedGesture { + prepare(): void; +} +export declare type ComposedGestureType = InstanceType; +export declare type RaceGestureType = ComposedGestureType; +export declare type SimultaneousGestureType = InstanceType; +export declare type ExclusiveGestureType = InstanceType; diff --git a/lib/typescript/handlers/gestures/gestureObjects.d.ts b/lib/typescript/handlers/gestures/gestureObjects.d.ts new file mode 100644 index 0000000000..73b3074fe3 --- /dev/null +++ b/lib/typescript/handlers/gestures/gestureObjects.d.ts @@ -0,0 +1,39 @@ +import { FlingGesture } from './flingGesture'; +import { ForceTouchGesture } from './forceTouchGesture'; +import { Gesture } from './gesture'; +import { ComposedGesture, ExclusiveGesture, SimultaneousGesture } from './gestureComposition'; +import { LongPressGesture } from './longPressGesture'; +import { PanGesture } from './panGesture'; +import { PinchGesture } from './pinchGesture'; +import { RotationGesture } from './rotationGesture'; +import { TapGesture } from './tapGesture'; +import { NativeGesture } from './nativeGesture'; +import { ManualGesture } from './manualGesture'; +export declare const GestureObjects: { + Tap: () => TapGesture; + Pan: () => PanGesture; + Pinch: () => PinchGesture; + Rotation: () => RotationGesture; + Fling: () => FlingGesture; + LongPress: () => LongPressGesture; + ForceTouch: () => ForceTouchGesture; + Native: () => NativeGesture; + Manual: () => ManualGesture; + /** + * Builds a composed gesture consisting of gestures provided as parameters. + * The first one that becomes active cancels the rest of gestures. + */ + Race: (...gestures: Gesture[]) => ComposedGesture; + /** + * Builds a composed gesture that allows all base gestures to run simultaneously. + */ + Simultaneous(...gestures: Gesture[]): SimultaneousGesture; + /** + * Builds a composed gesture where only one of the provided gestures can become active. + * Priority is decided through the order of gestures: the first one has higher priority + * than the second one, second one has higher priority than the third one, and so on. + * For example, to make a gesture that recognizes both single and double tap you need + * to call Exclusive(doubleTap, singleTap). + */ + Exclusive(...gestures: Gesture[]): ExclusiveGesture; +}; diff --git a/lib/typescript/handlers/gestures/gestureStateManager.d.ts b/lib/typescript/handlers/gestures/gestureStateManager.d.ts new file mode 100644 index 0000000000..d2cbe6510d --- /dev/null +++ b/lib/typescript/handlers/gestures/gestureStateManager.d.ts @@ -0,0 +1,9 @@ +export interface GestureStateManagerType { + begin: () => void; + activate: () => void; + fail: () => void; + end: () => void; +} +export declare const GestureStateManager: { + create(handlerTag: number): GestureStateManagerType; +}; diff --git a/lib/typescript/handlers/gestures/longPressGesture.d.ts b/lib/typescript/handlers/gestures/longPressGesture.d.ts new file mode 100644 index 0000000000..0d45ed991c --- /dev/null +++ b/lib/typescript/handlers/gestures/longPressGesture.d.ts @@ -0,0 +1,9 @@ +import { BaseGesture, BaseGestureConfig } from './gesture'; +import { LongPressGestureConfig, LongPressGestureHandlerEventPayload } from '../LongPressGestureHandler'; +export declare class LongPressGesture extends BaseGesture { + config: BaseGestureConfig & LongPressGestureConfig; + constructor(); + minDuration(duration: number): this; + maxDistance(distance: number): this; +} +export declare type LongPressGestureType = InstanceType; diff --git a/lib/typescript/handlers/gestures/manualGesture.d.ts b/lib/typescript/handlers/gestures/manualGesture.d.ts new file mode 100644 index 0000000000..c2f3e55fff --- /dev/null +++ b/lib/typescript/handlers/gestures/manualGesture.d.ts @@ -0,0 +1,7 @@ +import { GestureUpdateEvent } from '../gestureHandlerCommon'; +import { ContinousBaseGesture } from './gesture'; +export declare class ManualGesture extends ContinousBaseGesture, Record> { + constructor(); + onChange(callback: (event: GestureUpdateEvent>) => void): this; +} +export declare type ManualGestureType = InstanceType; diff --git a/lib/typescript/handlers/gestures/nativeGesture.d.ts b/lib/typescript/handlers/gestures/nativeGesture.d.ts new file mode 100644 index 0000000000..e83fdbeeae --- /dev/null +++ b/lib/typescript/handlers/gestures/nativeGesture.d.ts @@ -0,0 +1,9 @@ +import { BaseGestureConfig, BaseGesture } from './gesture'; +import { NativeViewGestureConfig, NativeViewGestureHandlerPayload } from '../NativeViewGestureHandler'; +export declare class NativeGesture extends BaseGesture { + config: BaseGestureConfig & NativeViewGestureConfig; + constructor(); + shouldActivateOnStart(value: boolean): this; + disallowInterruption(value: boolean): this; +} +export declare type NativeGestureType = InstanceType; diff --git a/lib/typescript/handlers/gestures/panGesture.d.ts b/lib/typescript/handlers/gestures/panGesture.d.ts new file mode 100644 index 0000000000..5d208eb800 --- /dev/null +++ b/lib/typescript/handlers/gestures/panGesture.d.ts @@ -0,0 +1,26 @@ +import { BaseGestureConfig, ContinousBaseGesture } from './gesture'; +import { GestureUpdateEvent } from '../gestureHandlerCommon'; +import { PanGestureConfig, PanGestureHandlerEventPayload } from '../PanGestureHandler'; +declare type PanGestureChangeEventPayload = { + changeX: number; + changeY: number; +}; +export declare class PanGesture extends ContinousBaseGesture { + config: BaseGestureConfig & PanGestureConfig; + constructor(); + activeOffsetY(offset: number | number[]): this; + activeOffsetX(offset: number | number[]): this; + failOffsetY(offset: number | number[]): this; + failOffsetX(offset: number | number[]): this; + minPointers(minPointers: number): this; + maxPointers(maxPointers: number): this; + minDistance(distance: number): this; + minVelocity(velocity: number): this; + minVelocityX(velocity: number): this; + minVelocityY(velocity: number): this; + averageTouches(value: boolean): this; + enableTrackpadTwoFingerGesture(value: boolean): this; + onChange(callback: (event: GestureUpdateEvent) => void): this; +} +export declare type PanGestureType = InstanceType; +export {}; diff --git a/lib/typescript/handlers/gestures/pinchGesture.d.ts b/lib/typescript/handlers/gestures/pinchGesture.d.ts new file mode 100644 index 0000000000..d73ea28cfa --- /dev/null +++ b/lib/typescript/handlers/gestures/pinchGesture.d.ts @@ -0,0 +1,12 @@ +import { ContinousBaseGesture } from './gesture'; +import { PinchGestureHandlerEventPayload } from '../PinchGestureHandler'; +import { GestureUpdateEvent } from '../gestureHandlerCommon'; +declare type PinchGestureChangeEventPayload = { + scaleChange: number; +}; +export declare class PinchGesture extends ContinousBaseGesture { + constructor(); + onChange(callback: (event: GestureUpdateEvent) => void): this; +} +export declare type PinchGestureType = InstanceType; +export {}; diff --git a/lib/typescript/handlers/gestures/reanimatedWrapper.d.ts b/lib/typescript/handlers/gestures/reanimatedWrapper.d.ts new file mode 100644 index 0000000000..3b0a1d80d6 --- /dev/null +++ b/lib/typescript/handlers/gestures/reanimatedWrapper.d.ts @@ -0,0 +1,14 @@ +import { ComponentClass } from 'react'; +import { GestureUpdateEvent, GestureStateChangeEvent } from '../gestureHandlerCommon'; +export interface SharedValue { + value: T; +} +declare let Reanimated: { + default: { + createAnimatedComponent

(component: ComponentClass

, options?: unknown): ComponentClass

; + }; + useEvent: (callback: (event: GestureUpdateEvent | GestureStateChangeEvent) => void, events: string[], rebuild: boolean) => unknown; + useSharedValue: (value: T) => SharedValue; + setGestureState: (handlerTag: number, newState: number) => void; +}; +export { Reanimated }; diff --git a/lib/typescript/handlers/gestures/rotationGesture.d.ts b/lib/typescript/handlers/gestures/rotationGesture.d.ts new file mode 100644 index 0000000000..abaf6d8d29 --- /dev/null +++ b/lib/typescript/handlers/gestures/rotationGesture.d.ts @@ -0,0 +1,12 @@ +import { ContinousBaseGesture } from './gesture'; +import { RotationGestureHandlerEventPayload } from '../RotationGestureHandler'; +import { GestureUpdateEvent } from '../gestureHandlerCommon'; +declare type RotationGestureChangeEventPayload = { + rotationChange: number; +}; +export declare class RotationGesture extends ContinousBaseGesture { + constructor(); + onChange(callback: (event: GestureUpdateEvent) => void): this; +} +export declare type RotationGestureType = InstanceType; +export {}; diff --git a/lib/typescript/handlers/gestures/tapGesture.d.ts b/lib/typescript/handlers/gestures/tapGesture.d.ts new file mode 100644 index 0000000000..db643ccc6f --- /dev/null +++ b/lib/typescript/handlers/gestures/tapGesture.d.ts @@ -0,0 +1,14 @@ +import { BaseGestureConfig, BaseGesture } from './gesture'; +import { TapGestureConfig, TapGestureHandlerEventPayload } from '../TapGestureHandler'; +export declare class TapGesture extends BaseGesture { + config: BaseGestureConfig & TapGestureConfig; + constructor(); + minPointers(minPointers: number): this; + numberOfTaps(count: number): this; + maxDistance(maxDist: number): this; + maxDuration(duration: number): this; + maxDelay(delay: number): this; + maxDeltaX(delta: number): this; + maxDeltaY(delta: number): this; +} +export declare type TapGestureType = InstanceType; diff --git a/lib/typescript/handlers/handlersRegistry.d.ts b/lib/typescript/handlers/handlersRegistry.d.ts new file mode 100644 index 0000000000..b661ee1f63 --- /dev/null +++ b/lib/typescript/handlers/handlersRegistry.d.ts @@ -0,0 +1,6 @@ +import { GestureType } from './gestures/gesture'; +export declare const handlerIDToTag: Record; +export declare function getNextHandlerTag(): number; +export declare function registerHandler(handlerTag: number, handler: GestureType): void; +export declare function unregisterHandler(handlerTag: number): void; +export declare function findHandler(handlerTag: number): import("./gestures/gesture").BaseGesture> | import("./gestures/gesture").BaseGesture> | import("./gestures/gesture").BaseGesture | import("./gestures/gesture").BaseGesture | import("./gestures/gesture").BaseGesture | import("./gestures/gesture").BaseGesture | import("./gestures/gesture").BaseGesture | import("./gestures/gesture").BaseGesture | import("./gestures/gesture").BaseGesture | import("./gestures/gesture").BaseGesture | undefined; diff --git a/lib/typescript/index.d.ts b/lib/typescript/index.d.ts new file mode 100644 index 0000000000..685031d933 --- /dev/null +++ b/lib/typescript/index.d.ts @@ -0,0 +1,44 @@ +export { Directions } from './Directions'; +export { State } from './State'; +export { default as gestureHandlerRootHOC } from './gestureHandlerRootHOC'; +export { default as GestureHandlerRootView } from './GestureHandlerRootView'; +export type { GestureEvent, HandlerStateChangeEvent, GestureEventPayload, HandlerStateChangeEventPayload, GestureTouchEvent, TouchData, GestureUpdateEvent, GestureStateChangeEvent, } from './handlers/gestureHandlerCommon'; +export type { GestureType } from './handlers/gestures/gesture'; +export type { TapGestureHandlerEventPayload, TapGestureHandlerProps, } from './handlers/TapGestureHandler'; +export type { ForceTouchGestureHandlerEventPayload, ForceTouchGestureHandlerProps, } from './handlers/ForceTouchGestureHandler'; +export type { LongPressGestureHandlerEventPayload, LongPressGestureHandlerProps, } from './handlers/LongPressGestureHandler'; +export type { PanGestureHandlerEventPayload, PanGestureHandlerProps, } from './handlers/PanGestureHandler'; +export type { PinchGestureHandlerEventPayload, PinchGestureHandlerProps, } from './handlers/PinchGestureHandler'; +export type { RotationGestureHandlerEventPayload, RotationGestureHandlerProps, } from './handlers/RotationGestureHandler'; +export type { FlingGestureHandlerEventPayload, FlingGestureHandlerProps, } from './handlers/FlingGestureHandler'; +export { TapGestureHandler } from './handlers/TapGestureHandler'; +export { ForceTouchGestureHandler } from './handlers/ForceTouchGestureHandler'; +export { LongPressGestureHandler } from './handlers/LongPressGestureHandler'; +export { PanGestureHandler } from './handlers/PanGestureHandler'; +export { PinchGestureHandler } from './handlers/PinchGestureHandler'; +export { RotationGestureHandler } from './handlers/RotationGestureHandler'; +export { FlingGestureHandler } from './handlers/FlingGestureHandler'; +export { default as createNativeWrapper } from './handlers/createNativeWrapper'; +export type { NativeViewGestureHandlerPayload, NativeViewGestureHandlerProps, } from './handlers/NativeViewGestureHandler'; +export { GestureDetector } from './handlers/gestures/GestureDetector'; +export { GestureObjects as Gesture } from './handlers/gestures/gestureObjects'; +export type { TapGestureType as TapGesture } from './handlers/gestures/tapGesture'; +export type { PanGestureType as PanGesture } from './handlers/gestures/panGesture'; +export type { FlingGestureType as FlingGesture } from './handlers/gestures/flingGesture'; +export type { LongPressGestureType as LongPressGesture } from './handlers/gestures/longPressGesture'; +export type { PinchGestureType as PinchGesture } from './handlers/gestures/pinchGesture'; +export type { RotationGestureType as RotationGesture } from './handlers/gestures/rotationGesture'; +export type { ForceTouchGestureType as ForceTouchGesture } from './handlers/gestures/forceTouchGesture'; +export type { NativeGestureType as NativeGesture } from './handlers/gestures/nativeGesture'; +export type { ManualGestureType as ManualGesture } from './handlers/gestures/manualGesture'; +export type { ComposedGestureType as ComposedGesture, RaceGestureType as RaceGesture, SimultaneousGestureType as SimultaneousGesture, ExclusiveGestureType as ExclusiveGesture, } from './handlers/gestures/gestureComposition'; +export type { GestureStateManagerType as GestureStateManager } from './handlers/gestures/gestureStateManager'; +export { NativeViewGestureHandler } from './handlers/NativeViewGestureHandler'; +export type { RawButtonProps, BaseButtonProps, RectButtonProps, BorderlessButtonProps, } from './components/GestureButtons'; +export { RawButton, BaseButton, RectButton, BorderlessButton, } from './components/GestureButtons'; +export { TouchableHighlight, TouchableNativeFeedback, TouchableOpacity, TouchableWithoutFeedback, } from './components/touchables'; +export { ScrollView, Switch, TextInput, DrawerLayoutAndroid, FlatList, } from './components/GestureComponents'; +export type { GestureHandlerGestureEvent, GestureHandlerStateChangeEvent, GestureHandlerGestureEventNativeEvent, GestureHandlerStateChangeNativeEvent, NativeViewGestureHandlerGestureEvent, NativeViewGestureHandlerStateChangeEvent, TapGestureHandlerGestureEvent, TapGestureHandlerStateChangeEvent, ForceTouchGestureHandlerGestureEvent, ForceTouchGestureHandlerStateChangeEvent, LongPressGestureHandlerGestureEvent, LongPressGestureHandlerStateChangeEvent, PanGestureHandlerGestureEvent, PanGestureHandlerStateChangeEvent, PinchGestureHandlerGestureEvent, PinchGestureHandlerStateChangeEvent, RotationGestureHandlerGestureEvent, RotationGestureHandlerStateChangeEvent, FlingGestureHandlerGestureEvent, FlingGestureHandlerStateChangeEvent, NativeViewGestureHandlerProperties, TapGestureHandlerProperties, LongPressGestureHandlerProperties, PanGestureHandlerProperties, PinchGestureHandlerProperties, RotationGestureHandlerProperties, FlingGestureHandlerProperties, ForceTouchGestureHandlerProperties, RawButtonProperties, BaseButtonProperties, RectButtonProperties, BorderlessButtonProperties, } from './handlers/gestureHandlerTypesCompat'; +export { default as Swipeable } from './components/Swipeable'; +export type { DrawerLayoutProps, DrawerPosition, DrawerState, DrawerType, DrawerLockMode, DrawerKeyboardDismissMode, } from './components/DrawerLayout'; +export { default as DrawerLayout } from './components/DrawerLayout'; diff --git a/lib/typescript/init.d.ts b/lib/typescript/init.d.ts new file mode 100644 index 0000000000..39a860bd76 --- /dev/null +++ b/lib/typescript/init.d.ts @@ -0,0 +1 @@ +export declare function initialize(): void; diff --git a/lib/typescript/mocks.d.ts b/lib/typescript/mocks.d.ts new file mode 100644 index 0000000000..7bfc8b7638 --- /dev/null +++ b/lib/typescript/mocks.d.ts @@ -0,0 +1,43 @@ +import { TouchableHighlight, TouchableNativeFeedback, TouchableOpacity, TouchableWithoutFeedback, ScrollView, FlatList, Switch, TextInput, DrawerLayoutAndroid, View } from 'react-native'; +declare const _default: { + readonly TouchableHighlight: typeof TouchableHighlight; + readonly TouchableNativeFeedback: typeof TouchableNativeFeedback; + readonly TouchableOpacity: typeof TouchableOpacity; + readonly TouchableWithoutFeedback: typeof TouchableWithoutFeedback; + readonly ScrollView: typeof ScrollView; + readonly FlatList: typeof FlatList; + readonly Switch: typeof Switch; + readonly TextInput: typeof TextInput; + readonly DrawerLayoutAndroid: typeof DrawerLayoutAndroid; + readonly NativeViewGestureHandler: typeof View; + readonly TapGestureHandler: typeof View; + readonly ForceTouchGestureHandler: typeof View; + readonly LongPressGestureHandler: typeof View; + readonly PinchGestureHandler: typeof View; + readonly RotationGestureHandler: typeof View; + readonly FlingGestureHandler: typeof View; + readonly RawButton: typeof TouchableNativeFeedback; + readonly BaseButton: typeof TouchableNativeFeedback; + readonly RectButton: typeof TouchableNativeFeedback; + readonly BorderlessButton: typeof TouchableNativeFeedback; + readonly PanGestureHandler: typeof View; + readonly attachGestureHandler: () => void; + readonly createGestureHandler: () => void; + readonly dropGestureHandler: () => void; + readonly updateGestureHandler: () => void; + readonly Directions: { + readonly RIGHT: 1; + readonly LEFT: 2; + readonly UP: 4; + readonly DOWN: 8; + }; + readonly State: { + readonly UNDETERMINED: 0; + readonly FAILED: 1; + readonly BEGAN: 2; + readonly CANCELLED: 3; + readonly ACTIVE: 4; + readonly END: 5; + }; +}; +export default _default; diff --git a/lib/typescript/typeUtils.d.ts b/lib/typescript/typeUtils.d.ts new file mode 100644 index 0000000000..c00f6b93ce --- /dev/null +++ b/lib/typescript/typeUtils.d.ts @@ -0,0 +1 @@ +export declare type ValueOf = T[keyof T]; diff --git a/lib/typescript/utils.d.ts b/lib/typescript/utils.d.ts new file mode 100644 index 0000000000..3b7f4cfe52 --- /dev/null +++ b/lib/typescript/utils.d.ts @@ -0,0 +1 @@ +export declare function toArray(object: T | T[]): T[]; diff --git a/lib/typescript/web/DiscreteGestureHandler.d.ts b/lib/typescript/web/DiscreteGestureHandler.d.ts new file mode 100644 index 0000000000..d00353e884 --- /dev/null +++ b/lib/typescript/web/DiscreteGestureHandler.d.ts @@ -0,0 +1,20 @@ +import GestureHandler from './GestureHandler'; +declare abstract class DiscreteGestureHandler extends GestureHandler { + get isDiscrete(): boolean; + get shouldEnableGestureOnSetup(): boolean; + shouldFailUnderCustomCriteria({ x, y, deltaX, deltaY }: any, { maxDeltaX, maxDeltaY, maxDistSq, shouldCancelWhenOutside }: any): boolean; + transformNativeEvent({ center: { x, y } }: any): { + absoluteX: any; + absoluteY: any; + x: number; + y: number; + }; + isGestureEnabledForEvent({ minPointers, maxPointers, maxDeltaX, maxDeltaY, maxDistSq, shouldCancelWhenOutside, }: any, _recognizer: any, { maxPointers: pointerLength, center, deltaX, deltaY }: any): { + failed: boolean; + success?: undefined; + } | { + success: boolean; + failed?: undefined; + }; +} +export default DiscreteGestureHandler; diff --git a/lib/typescript/web/DraggingGestureHandler.d.ts b/lib/typescript/web/DraggingGestureHandler.d.ts new file mode 100644 index 0000000000..dd34937b46 --- /dev/null +++ b/lib/typescript/web/DraggingGestureHandler.d.ts @@ -0,0 +1,15 @@ +import GestureHandler, { HammerInputExt } from './GestureHandler'; +declare abstract class DraggingGestureHandler extends GestureHandler { + get shouldEnableGestureOnSetup(): boolean; + transformNativeEvent({ deltaX, deltaY, velocityX, velocityY, center: { x, y }, }: HammerInputExt): { + translationX: number; + translationY: number; + absoluteX: number; + absoluteY: number; + velocityX: number; + velocityY: number; + x: number; + y: number; + }; +} +export default DraggingGestureHandler; diff --git a/lib/typescript/web/Errors.d.ts b/lib/typescript/web/Errors.d.ts new file mode 100644 index 0000000000..7ac1cfaee4 --- /dev/null +++ b/lib/typescript/web/Errors.d.ts @@ -0,0 +1,3 @@ +export declare class GesturePropError extends Error { + constructor(name: string, value: unknown, expectedType: string); +} diff --git a/lib/typescript/web/FlingGestureHandler.d.ts b/lib/typescript/web/FlingGestureHandler.d.ts new file mode 100644 index 0000000000..9a39e2d2ca --- /dev/null +++ b/lib/typescript/web/FlingGestureHandler.d.ts @@ -0,0 +1,42 @@ +import DraggingGestureHandler from './DraggingGestureHandler'; +import { HammerInputExt } from './GestureHandler'; +declare class FlingGestureHandler extends DraggingGestureHandler { + get name(): string; + get NativeGestureClass(): SwipeRecognizerStatic; + onGestureActivated(event: HammerInputExt): void; + onRawEvent(ev: HammerInputExt): void; + getHammerConfig(): { + pointers: any; + direction: number; + }; + getTargetDirections(direction: number): number[]; + getDirection(): number; + isGestureEnabledForEvent({ numberOfPointers }: any, _recognizer: any, { maxPointers: pointerLength }: any): { + failed: boolean; + success?: undefined; + } | { + success: boolean; + failed?: undefined; + }; + updateGestureConfig({ numberOfPointers, direction, ...props }: any): Partial<{ + enabled: boolean; + minPointers: number; + maxPointers: number; + minDist: number; + minDistSq: number; + minVelocity: number; + minVelocitySq: number; + maxDist: number; + maxDistSq: number; + failOffsetXStart: number; + failOffsetYStart: number; + failOffsetXEnd: number; + failOffsetYEnd: number; + activeOffsetXStart: number; + activeOffsetXEnd: number; + activeOffsetYStart: number; + activeOffsetYEnd: number; + waitFor: any[] | null; + }>; +} +export default FlingGestureHandler; diff --git a/lib/typescript/web/GestureHandler.d.ts b/lib/typescript/web/GestureHandler.d.ts new file mode 100644 index 0000000000..435e8a1ec0 --- /dev/null +++ b/lib/typescript/web/GestureHandler.d.ts @@ -0,0 +1,139 @@ +import { findNodeHandle } from 'react-native'; +import { State } from '../State'; +import { EventMap } from './constants'; +export declare type HammerInputExt = Omit; +export declare type Config = Partial<{ + enabled: boolean; + minPointers: number; + maxPointers: number; + minDist: number; + minDistSq: number; + minVelocity: number; + minVelocitySq: number; + maxDist: number; + maxDistSq: number; + failOffsetXStart: number; + failOffsetYStart: number; + failOffsetXEnd: number; + failOffsetYEnd: number; + activeOffsetXStart: number; + activeOffsetXEnd: number; + activeOffsetYStart: number; + activeOffsetYEnd: number; + waitFor: any[] | null; +}>; +declare abstract class GestureHandler { + handlerTag: any; + isGestureRunning: boolean; + view: number | null; + protected hasCustomActivationCriteria: boolean; + protected hasGestureFailed: boolean; + protected hammer: HammerManager | null; + protected initialRotation: number | null; + protected __initialX: any; + protected __initialY: any; + protected config: Config; + protected previousState: State; + private pendingGestures; + private oldState; + private lastSentState; + private gestureInstance; + private _stillWaiting; + private propsRef; + private ref; + abstract get name(): string; + get id(): string; + get isDiscrete(): boolean; + get shouldEnableGestureOnSetup(): boolean; + constructor(); + getConfig(): Partial<{ + enabled: boolean; + minPointers: number; + maxPointers: number; + minDist: number; + minDistSq: number; + minVelocity: number; + minVelocitySq: number; + maxDist: number; + maxDistSq: number; + failOffsetXStart: number; + failOffsetYStart: number; + failOffsetXEnd: number; + failOffsetYEnd: number; + activeOffsetXStart: number; + activeOffsetXEnd: number; + activeOffsetYStart: number; + activeOffsetYEnd: number; + waitFor: any[] | null; + }>; + onWaitingEnded(_gesture: this): void; + removePendingGesture(id: string): void; + addPendingGesture(gesture: this): void; + isGestureEnabledForEvent(_config: any, _recognizer: any, _event: any): { + failed?: boolean; + success?: boolean; + }; + get NativeGestureClass(): RecognizerStatic; + updateHasCustomActivationCriteria(_config: Config): boolean; + clearSelfAsPending: () => void; + updateGestureConfig({ enabled, ...props }: { + [x: string]: any; + enabled?: boolean | undefined; + }): Partial<{ + enabled: boolean; + minPointers: number; + maxPointers: number; + minDist: number; + minDistSq: number; + minVelocity: number; + minVelocitySq: number; + maxDist: number; + maxDistSq: number; + failOffsetXStart: number; + failOffsetYStart: number; + failOffsetXEnd: number; + failOffsetYEnd: number; + activeOffsetXStart: number; + activeOffsetXEnd: number; + activeOffsetYStart: number; + activeOffsetYEnd: number; + waitFor: any[] | null; + }>; + destroy: () => void; + isPointInView: ({ x, y }: { + x: number; + y: number; + }) => boolean; + getState(type: keyof typeof EventMap): State; + transformEventData(event: HammerInputExt): { + nativeEvent: { + handlerTag: any; + target: any; + oldState: State; + numberOfPointers: number; + state: State; + pointerInside: boolean; + }; + timeStamp: number; + }; + transformNativeEvent(_event: HammerInputExt): {}; + sendEvent: (nativeEvent: HammerInputExt) => void; + cancelPendingGestures(event: HammerInputExt): void; + notifyPendingGestures(): void; + onGestureEnded(event: HammerInputExt): void; + forceInvalidate(event: HammerInputExt): void; + cancelEvent(event: HammerInputExt): void; + onRawEvent({ isFirst }: HammerInputExt): void; + setView(ref: Parameters['0'], propsRef: any): void; + setupEvents(): void; + onStart({ deltaX, deltaY, rotation }: HammerInputExt): void; + onGestureActivated(ev: HammerInputExt): void; + onSuccess(): void; + _getPendingGestures(): any[]; + getHammerConfig(): { + pointers: number | undefined; + }; + sync: () => void; + simulateCancelEvent(_inputData: any): void; +} +export default GestureHandler; diff --git a/lib/typescript/web/IndiscreteGestureHandler.d.ts b/lib/typescript/web/IndiscreteGestureHandler.d.ts new file mode 100644 index 0000000000..065f149fe5 --- /dev/null +++ b/lib/typescript/web/IndiscreteGestureHandler.d.ts @@ -0,0 +1,39 @@ +import GestureHandler from './GestureHandler'; +/** + * The base class for **Rotation** and **Pinch** gesture handlers. + */ +declare abstract class IndiscreteGestureHandler extends GestureHandler { + get shouldEnableGestureOnSetup(): boolean; + updateGestureConfig({ minPointers, maxPointers, ...props }: { + [x: string]: any; + minPointers?: number | undefined; + maxPointers?: number | undefined; + }): Partial<{ + enabled: boolean; + minPointers: number; + maxPointers: number; + minDist: number; + minDistSq: number; + minVelocity: number; + minVelocitySq: number; + maxDist: number; + maxDistSq: number; + failOffsetXStart: number; + failOffsetYStart: number; + failOffsetXEnd: number; + failOffsetYEnd: number; + activeOffsetXStart: number; + activeOffsetXEnd: number; + activeOffsetYStart: number; + activeOffsetYEnd: number; + waitFor: any[] | null; + }>; + isGestureEnabledForEvent({ minPointers, maxPointers }: any, _recognizer: any, { maxPointers: pointerLength }: any): { + failed: boolean; + success?: undefined; + } | { + success: boolean; + failed?: undefined; + }; +} +export default IndiscreteGestureHandler; diff --git a/lib/typescript/web/LongPressGestureHandler.d.ts b/lib/typescript/web/LongPressGestureHandler.d.ts new file mode 100644 index 0000000000..a112ab690f --- /dev/null +++ b/lib/typescript/web/LongPressGestureHandler.d.ts @@ -0,0 +1,37 @@ +import PressGestureHandler from './PressGestureHandler'; +import { Config } from './GestureHandler'; +import { HammerInputNames } from './constants'; +declare class LongPressGestureHandler extends PressGestureHandler { + get minDurationMs(): number; + get maxDist(): number | undefined; + updateHasCustomActivationCriteria({ maxDistSq }: Config): boolean; + getConfig(): Partial<{ + enabled: boolean; + minPointers: number; + maxPointers: number; + minDist: number; + minDistSq: number; + minVelocity: number; + minVelocitySq: number; + maxDist: number; + maxDistSq: number; + failOffsetXStart: number; + failOffsetYStart: number; + failOffsetXEnd: number; + failOffsetYEnd: number; + activeOffsetXStart: number; + activeOffsetXEnd: number; + activeOffsetYStart: number; + activeOffsetYEnd: number; + waitFor: any[] | null; + }> | { + shouldCancelWhenOutside: boolean; + maxDistSq: number; + }; + getHammerConfig(): { + time: number; + pointers: number | undefined; + }; + getState(type: keyof typeof HammerInputNames): 1 | 4 | 5; +} +export default LongPressGestureHandler; diff --git a/lib/typescript/web/NativeViewGestureHandler.d.ts b/lib/typescript/web/NativeViewGestureHandler.d.ts new file mode 100644 index 0000000000..ee6418acdf --- /dev/null +++ b/lib/typescript/web/NativeViewGestureHandler.d.ts @@ -0,0 +1,6 @@ +import { HammerInputExt } from './GestureHandler'; +import PressGestureHandler from './PressGestureHandler'; +declare class NativeViewGestureHandler extends PressGestureHandler { + onRawEvent(ev: HammerInputExt): void; +} +export default NativeViewGestureHandler; diff --git a/lib/typescript/web/NodeManager.d.ts b/lib/typescript/web/NodeManager.d.ts new file mode 100644 index 0000000000..e25bb16e1e --- /dev/null +++ b/lib/typescript/web/NodeManager.d.ts @@ -0,0 +1,8 @@ +import { ValueOf } from '../typeUtils'; +import { Gestures } from '../RNGestureHandlerModule.web'; +export declare function getHandler(tag: number): import("./PanGestureHandler").default | import("./RotationGestureHandler").default | import("./PinchGestureHandler").default | import("./TapGestureHandler").default | import("./NativeViewGestureHandler").default | import("./LongPressGestureHandler").default | import("./FlingGestureHandler").default; +export declare function createGestureHandler(handlerTag: number, handler: InstanceType>): void; +export declare function dropGestureHandler(handlerTag: number): void; +export declare function getNodes(): { + [x: number]: import("./PanGestureHandler").default | import("./RotationGestureHandler").default | import("./PinchGestureHandler").default | import("./TapGestureHandler").default | import("./NativeViewGestureHandler").default | import("./LongPressGestureHandler").default | import("./FlingGestureHandler").default; +}; diff --git a/lib/typescript/web/PanGestureHandler.d.ts b/lib/typescript/web/PanGestureHandler.d.ts new file mode 100644 index 0000000000..5d1980d460 --- /dev/null +++ b/lib/typescript/web/PanGestureHandler.d.ts @@ -0,0 +1,55 @@ +import { EventMap } from './constants'; +import DraggingGestureHandler from './DraggingGestureHandler'; +import { State } from '../State'; +import { Config, HammerInputExt } from './GestureHandler'; +declare class PanGestureHandler extends DraggingGestureHandler { + get name(): string; + get NativeGestureClass(): PanRecognizerStatic; + getHammerConfig(): { + direction: number; + pointers: number | undefined; + }; + getState(type: keyof typeof EventMap): State; + getDirection(): number; + getConfig(): Partial<{ + enabled: boolean; + minPointers: number; + maxPointers: number; + minDist: number; + minDistSq: number; + minVelocity: number; + minVelocitySq: number; + maxDist: number; + maxDistSq: number; + failOffsetXStart: number; + failOffsetYStart: number; + failOffsetXEnd: number; + failOffsetYEnd: number; + activeOffsetXStart: number; + activeOffsetXEnd: number; + activeOffsetYStart: number; + activeOffsetYEnd: number; + waitFor: any[] | null; + }>; + shouldFailUnderCustomCriteria({ deltaX, deltaY }: HammerInputExt, criteria: any): boolean; + shouldActivateUnderCustomCriteria({ deltaX, deltaY, velocity }: any, criteria: any): boolean; + shouldMultiFingerPanFail({ pointerLength, scale, deltaRotation, }: { + deltaRotation: number; + pointerLength: number; + scale: number; + }): boolean; + updateHasCustomActivationCriteria(criteria: Config & { + minVelocityX?: number; + minVelocityY?: number; + }): boolean; + isGestureEnabledForEvent(props: any, _recognizer: any, inputData: HammerInputExt & { + deltaRotation: number; + }): { + failed: boolean; + success?: undefined; + } | { + success: boolean; + failed?: undefined; + }; +} +export default PanGestureHandler; diff --git a/lib/typescript/web/PinchGestureHandler.d.ts b/lib/typescript/web/PinchGestureHandler.d.ts new file mode 100644 index 0000000000..d97ebeb3b6 --- /dev/null +++ b/lib/typescript/web/PinchGestureHandler.d.ts @@ -0,0 +1,13 @@ +import { HammerInputExt } from './GestureHandler'; +import IndiscreteGestureHandler from './IndiscreteGestureHandler'; +declare class PinchGestureHandler extends IndiscreteGestureHandler { + get name(): string; + get NativeGestureClass(): PinchRecognizerStatic; + transformNativeEvent({ scale, velocity, center }: HammerInputExt): { + focalX: number; + focalY: number; + velocity: number; + scale: number; + }; +} +export default PinchGestureHandler; diff --git a/lib/typescript/web/PressGestureHandler.d.ts b/lib/typescript/web/PressGestureHandler.d.ts new file mode 100644 index 0000000000..8945604383 --- /dev/null +++ b/lib/typescript/web/PressGestureHandler.d.ts @@ -0,0 +1,81 @@ +import { State } from '../State'; +import { HammerInputNames } from './constants'; +import DiscreteGestureHandler from './DiscreteGestureHandler'; +import { Config, HammerInputExt } from './GestureHandler'; +declare class PressGestureHandler extends DiscreteGestureHandler { + private visualFeedbackTimer; + private initialEvent; + get name(): string; + get minDurationMs(): any; + get maxDist(): number | undefined; + get NativeGestureClass(): PressRecognizerStatic; + shouldDelayTouches: boolean; + simulateCancelEvent(inputData: HammerInputExt): void; + updateHasCustomActivationCriteria({ shouldCancelWhenOutside, maxDistSq, }: Config & { + shouldCancelWhenOutside: boolean; + }): boolean; + getState(type: keyof typeof HammerInputNames): State; + getConfig(): Partial<{ + enabled: boolean; + minPointers: number; + maxPointers: number; + minDist: number; + minDistSq: number; + minVelocity: number; + minVelocitySq: number; + maxDist: number; + maxDistSq: number; + failOffsetXStart: number; + failOffsetYStart: number; + failOffsetXEnd: number; + failOffsetYEnd: number; + activeOffsetXStart: number; + activeOffsetXEnd: number; + activeOffsetYStart: number; + activeOffsetYEnd: number; + waitFor: any[] | null; + }> | { + shouldCancelWhenOutside: boolean; + maxDistSq: number; + }; + getHammerConfig(): { + time: any; + pointers: number | undefined; + }; + onGestureActivated(ev: HammerInputExt): void; + shouldDelayTouchForEvent({ pointerType }: HammerInputExt): boolean; + onGestureStart(ev: HammerInputExt): void; + sendGestureStartedEvent(ev: HammerInputExt): void; + forceInvalidate(event: HammerInputExt): void; + onRawEvent(ev: HammerInputExt): void; + updateGestureConfig({ shouldActivateOnStart, disallowInterruption, shouldCancelWhenOutside, minDurationMs, maxDist, minPointers, maxPointers, ...props }: { + [x: string]: any; + shouldActivateOnStart?: boolean | undefined; + disallowInterruption?: boolean | undefined; + shouldCancelWhenOutside?: boolean | undefined; + minDurationMs?: number | undefined; + maxDist?: number | undefined; + minPointers?: number | undefined; + maxPointers?: number | undefined; + }): Partial<{ + enabled: boolean; + minPointers: number; + maxPointers: number; + minDist: number; + minDistSq: number; + minVelocity: number; + minVelocitySq: number; + maxDist: number; + maxDistSq: number; + failOffsetXStart: number; + failOffsetYStart: number; + failOffsetXEnd: number; + failOffsetYEnd: number; + activeOffsetXStart: number; + activeOffsetXEnd: number; + activeOffsetYStart: number; + activeOffsetYEnd: number; + waitFor: any[] | null; + }>; +} +export default PressGestureHandler; diff --git a/lib/typescript/web/RotationGestureHandler.d.ts b/lib/typescript/web/RotationGestureHandler.d.ts new file mode 100644 index 0000000000..88a59f4f4c --- /dev/null +++ b/lib/typescript/web/RotationGestureHandler.d.ts @@ -0,0 +1,13 @@ +import { HammerInputExt } from './GestureHandler'; +import IndiscreteGestureHandler from './IndiscreteGestureHandler'; +declare class RotationGestureHandler extends IndiscreteGestureHandler { + get name(): string; + get NativeGestureClass(): RotateRecognizerStatic; + transformNativeEvent({ rotation, velocity, center }: HammerInputExt): { + rotation: number; + anchorX: number; + anchorY: number; + velocity: number; + }; +} +export default RotationGestureHandler; diff --git a/lib/typescript/web/TapGestureHandler.d.ts b/lib/typescript/web/TapGestureHandler.d.ts new file mode 100644 index 0000000000..ad3bc3ff74 --- /dev/null +++ b/lib/typescript/web/TapGestureHandler.d.ts @@ -0,0 +1,56 @@ +import DiscreteGestureHandler from './DiscreteGestureHandler'; +import { HammerInputExt } from './GestureHandler'; +declare class TapGestureHandler extends DiscreteGestureHandler { + private _shouldFireEndEvent; + private _timer; + private _multiTapTimer; + get name(): string; + get NativeGestureClass(): TapRecognizerStatic; + get maxDelayMs(): any; + simulateCancelEvent(inputData: HammerInputExt): void; + onGestureActivated(ev: HammerInputExt): void; + onSuccessfulTap: (ev: HammerInputExt) => void; + onRawEvent(ev: HammerInput): void; + getHammerConfig(): { + event: string; + taps: any; + interval: any; + time: any; + pointers: number | undefined; + }; + updateGestureConfig({ shouldCancelWhenOutside, maxDeltaX, maxDeltaY, numberOfTaps, minDurationMs, maxDelayMs, maxDurationMs, maxDist, minPointers, maxPointers, ...props }: { + [x: string]: any; + shouldCancelWhenOutside?: boolean | undefined; + maxDeltaX?: number | undefined; + maxDeltaY?: number | undefined; + numberOfTaps?: number | undefined; + minDurationMs?: number | undefined; + maxDelayMs?: number | undefined; + maxDurationMs?: number | undefined; + maxDist?: number | undefined; + minPointers?: number | undefined; + maxPointers?: number | undefined; + }): Partial<{ + enabled: boolean; + minPointers: number; + maxPointers: number; + minDist: number; + minDistSq: number; + minVelocity: number; + minVelocitySq: number; + maxDist: number; + maxDistSq: number; + failOffsetXStart: number; + failOffsetYStart: number; + failOffsetXEnd: number; + failOffsetYEnd: number; + activeOffsetXStart: number; + activeOffsetXEnd: number; + activeOffsetYStart: number; + activeOffsetYEnd: number; + waitFor: any[] | null; + }>; + onGestureEnded(...props: any): void; + onWaitingEnded(_gesture: any): void; +} +export default TapGestureHandler; diff --git a/lib/typescript/web/constants.d.ts b/lib/typescript/web/constants.d.ts new file mode 100644 index 0000000000..01bf4f0b66 --- /dev/null +++ b/lib/typescript/web/constants.d.ts @@ -0,0 +1,40 @@ +import Hammer from '@egjs/hammerjs'; +export declare const CONTENT_TOUCHES_DELAY = 240; +export declare const CONTENT_TOUCHES_QUICK_TAP_END_DELAY = 50; +export declare const MULTI_FINGER_PAN_MAX_PINCH_THRESHOLD = 0.1; +export declare const MULTI_FINGER_PAN_MAX_ROTATION_THRESHOLD = 7; +export declare const DEG_RAD: number; +export declare const EventMap: { + readonly 1: 2; + readonly 2: 4; + readonly 4: 5; + readonly 8: 1; +}; +export declare const Direction: { + RIGHT: number; + LEFT: number; + UP: number; + DOWN: number; +}; +export declare const DirectionMap: { + 4: number; + 2: number; + 8: number; + 16: number; +}; +export declare const HammerInputNames: { + 1: string; + 2: string; + 4: string; + 8: string; +}; +export declare const HammerDirectionNames: { + 6: string; + 8: string; + 16: string; + 24: string; + 1: string; + 30: string; + 4: string; + 2: string; +}; diff --git a/lib/typescript/web/utils.d.ts b/lib/typescript/web/utils.d.ts new file mode 100644 index 0000000000..4d502ca8a6 --- /dev/null +++ b/lib/typescript/web/utils.d.ts @@ -0,0 +1,9 @@ +export declare const isnan: (v: unknown) => boolean; +export declare const isValidNumber: (v: unknown) => boolean; +export declare const TEST_MIN_IF_NOT_NAN: (value: number, limit: number) => boolean; +export declare const VEC_LEN_SQ: ({ x, y }?: { + x?: number | undefined; + y?: number | undefined; +}) => number; +export declare const TEST_MAX_IF_NOT_NAN: (value: number, max: number) => boolean; +export declare function fireAfterInterval(method: () => void, interval?: number | boolean): number | null;