motion-start 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +39 -0
  3. package/package.json +64 -0
  4. package/src/animation/UseAnimatedState.svelte +86 -0
  5. package/src/animation/UseAnimation.svelte +61 -0
  6. package/src/animation/animate.ts +78 -0
  7. package/src/animation/animation-controls.ts +101 -0
  8. package/src/animation/types.ts +83 -0
  9. package/src/animation/use-animated-state.ts +1 -0
  10. package/src/animation/use-animation.ts +74 -0
  11. package/src/animation/utils/default-transitions.ts +70 -0
  12. package/src/animation/utils/easing.ts +55 -0
  13. package/src/animation/utils/is-animatable.ts +42 -0
  14. package/src/animation/utils/is-animation-controls.ts +17 -0
  15. package/src/animation/utils/is-keyframes-target.ts +17 -0
  16. package/src/animation/utils/transitions.ts +218 -0
  17. package/src/animation/utils/variant-resolvers.ts +15 -0
  18. package/src/components/AnimatePresence/AnimatePresence.svelte +180 -0
  19. package/src/components/AnimatePresence/PresenceChild/PresenceChild.svelte +78 -0
  20. package/src/components/AnimatePresence/PresenceChild/index.ts +7 -0
  21. package/src/components/AnimatePresence/PresenceChild/types.ts +10 -0
  22. package/src/components/AnimatePresence/index.ts +46 -0
  23. package/src/components/AnimatePresence/types.ts +79 -0
  24. package/src/components/AnimatePresence/use-presence.ts +90 -0
  25. package/src/components/AnimateSharedLayout/AnimateSharedLayout.svelte +239 -0
  26. package/src/components/AnimateSharedLayout/index.ts +11 -0
  27. package/src/components/AnimateSharedLayout/types.ts +111 -0
  28. package/src/components/AnimateSharedLayout/utils/batcher.ts +96 -0
  29. package/src/components/AnimateSharedLayout/utils/crossfader.ts +260 -0
  30. package/src/components/AnimateSharedLayout/utils/rotate.ts +48 -0
  31. package/src/components/AnimateSharedLayout/utils/stack.ts +160 -0
  32. package/src/components/LazyMotion/LazyMotion.svelte +82 -0
  33. package/src/components/LazyMotion/index.ts +42 -0
  34. package/src/components/LazyMotion/types.ts +58 -0
  35. package/src/components/MotionConfig/MotionConfig.svelte +56 -0
  36. package/src/components/MotionConfig/MotionConfigScaleCorrection.ts +47 -0
  37. package/src/components/MotionConfig/index.ts +20 -0
  38. package/src/components/MotionDiv.svelte +8 -0
  39. package/src/context/DOMcontext.ts +21 -0
  40. package/src/context/LayoutGroupContext.ts +13 -0
  41. package/src/context/LazyContext.ts +18 -0
  42. package/src/context/MotionConfigContext.ts +48 -0
  43. package/src/context/MotionContext/MotionContext.svelte +27 -0
  44. package/src/context/MotionContext/MotionContextProvider.svelte +22 -0
  45. package/src/context/MotionContext/UseCreateMotionContext.svelte +34 -0
  46. package/src/context/MotionContext/create.ts +1 -0
  47. package/src/context/MotionContext/index.ts +14 -0
  48. package/src/context/MotionContext/utils.ts +29 -0
  49. package/src/context/PresenceContext.ts +26 -0
  50. package/src/context/ScaleCorrectionProvider.svelte +27 -0
  51. package/src/context/SharedLayoutContext.ts +29 -0
  52. package/src/events/UseDomEvent.svelte +67 -0
  53. package/src/events/UsePointerEvent.svelte +76 -0
  54. package/src/events/event-info.ts +69 -0
  55. package/src/events/types.ts +15 -0
  56. package/src/events/use-dom-event.ts +48 -0
  57. package/src/events/use-pointer-event.ts +29 -0
  58. package/src/events/utils.ts +25 -0
  59. package/src/gestures/PanSession.ts +298 -0
  60. package/src/gestures/UseFocusGesture.svelte +31 -0
  61. package/src/gestures/UseGestures.svelte +17 -0
  62. package/src/gestures/UseHoverGesture.svelte +40 -0
  63. package/src/gestures/UsePanGesture.svelte +58 -0
  64. package/src/gestures/UseTapGesture.svelte +77 -0
  65. package/src/gestures/drag/UseDrag.svelte +55 -0
  66. package/src/gestures/drag/UseDragControls.svelte +145 -0
  67. package/src/gestures/drag/VisualElementDragControls.ts +632 -0
  68. package/src/gestures/drag/types.ts +307 -0
  69. package/src/gestures/drag/use-drag-controls.ts +148 -0
  70. package/src/gestures/drag/use-drag.ts +15 -0
  71. package/src/gestures/drag/utils/constraints.ts +157 -0
  72. package/src/gestures/drag/utils/lock.ts +69 -0
  73. package/src/gestures/types.ts +257 -0
  74. package/src/gestures/use-focus-gesture.ts +16 -0
  75. package/src/gestures/use-gestures.ts +2 -0
  76. package/src/gestures/use-hover-gesture.ts +10 -0
  77. package/src/gestures/use-pan-gesture.ts +22 -0
  78. package/src/gestures/use-tap-gesture.ts +14 -0
  79. package/src/gestures/utils/event-type.ts +24 -0
  80. package/src/gestures/utils/is-node-or-child.ts +31 -0
  81. package/src/index.ts +104 -0
  82. package/src/motion/Motion.svelte +246 -0
  83. package/src/motion/MotionSSR.svelte +244 -0
  84. package/src/motion/features/AnimationState.svelte +29 -0
  85. package/src/motion/features/Exit.svelte +32 -0
  86. package/src/motion/features/UseFeatures.svelte +39 -0
  87. package/src/motion/features/animations.ts +22 -0
  88. package/src/motion/features/definitions.ts +49 -0
  89. package/src/motion/features/drag.ts +24 -0
  90. package/src/motion/features/gestures.ts +24 -0
  91. package/src/motion/features/layout/Animate.svelte +314 -0
  92. package/src/motion/features/layout/Animate.ts +9 -0
  93. package/src/motion/features/layout/AnimateLayoutContextProvider.svelte +14 -0
  94. package/src/motion/features/layout/Measure.svelte +98 -0
  95. package/src/motion/features/layout/Measure.ts +9 -0
  96. package/src/motion/features/layout/MeasureContextProvider.svelte +32 -0
  97. package/src/motion/features/layout/index.ts +20 -0
  98. package/src/motion/features/layout/types.ts +71 -0
  99. package/src/motion/features/layout/utils.ts +40 -0
  100. package/src/motion/features/types.ts +53 -0
  101. package/src/motion/features/use-features.ts +16 -0
  102. package/src/motion/index.ts +64 -0
  103. package/src/motion/types.ts +278 -0
  104. package/src/motion/utils/UseLayoutId.svelte +18 -0
  105. package/src/motion/utils/UseVisualElement.svelte +104 -0
  106. package/src/motion/utils/UseVisualState.svelte +137 -0
  107. package/src/motion/utils/is-forced-motion-value.ts +23 -0
  108. package/src/motion/utils/make-renderless-component.ts +17 -0
  109. package/src/motion/utils/should-inhert-variant.ts +6 -0
  110. package/src/motion/utils/use-motion-ref.ts +41 -0
  111. package/src/motion/utils/use-visual-element.ts +13 -0
  112. package/src/motion/utils/use-visual-state.ts +24 -0
  113. package/src/motion/utils/valid-prop.ts +80 -0
  114. package/src/render/dom/M.svelte +16 -0
  115. package/src/render/dom/UseRender.svelte +37 -0
  116. package/src/render/dom/create-motion-class.ts +12 -0
  117. package/src/render/dom/create-visual-element.ts +22 -0
  118. package/src/render/dom/featureBundle.ts +22 -0
  119. package/src/render/dom/motion-minimal.ts +22 -0
  120. package/src/render/dom/motion-proxy.ts +107 -0
  121. package/src/render/dom/motion.ts +62 -0
  122. package/src/render/dom/projection/convert-to-relative.ts +40 -0
  123. package/src/render/dom/projection/default-scale-correctors.ts +138 -0
  124. package/src/render/dom/projection/measure.ts +28 -0
  125. package/src/render/dom/projection/relative-set.ts +27 -0
  126. package/src/render/dom/projection/scale-correction.ts +22 -0
  127. package/src/render/dom/projection/types.ts +13 -0
  128. package/src/render/dom/projection/utils.ts +69 -0
  129. package/src/render/dom/svg-visual-element.ts +114 -0
  130. package/src/render/dom/types.ts +32 -0
  131. package/src/render/dom/use-render.ts +11 -0
  132. package/src/render/dom/utils/UseInitialMotionProps.svelte +26 -0
  133. package/src/render/dom/utils/batch-layout.ts +77 -0
  134. package/src/render/dom/utils/camel-to-dash.ts +20 -0
  135. package/src/render/dom/utils/create-config.ts +33 -0
  136. package/src/render/dom/utils/css-variables-conversion.ts +121 -0
  137. package/src/render/dom/utils/filter-props.ts +55 -0
  138. package/src/render/dom/utils/is-css-variable.ts +18 -0
  139. package/src/render/dom/utils/is-svg-component.ts +41 -0
  140. package/src/render/dom/utils/parse-dom-variant.ts +26 -0
  141. package/src/render/dom/utils/unit-conversion.ts +258 -0
  142. package/src/render/dom/utils/use-html-props.ts +2 -0
  143. package/src/render/dom/utils/use-svg-props.ts +1 -0
  144. package/src/render/dom/value-types/animatable-none.ts +24 -0
  145. package/src/render/dom/value-types/defaults.ts +30 -0
  146. package/src/render/dom/value-types/dimensions.ts +27 -0
  147. package/src/render/dom/value-types/find.ts +31 -0
  148. package/src/render/dom/value-types/get-as-type.ts +21 -0
  149. package/src/render/dom/value-types/number.ts +83 -0
  150. package/src/render/dom/value-types/test.ts +17 -0
  151. package/src/render/dom/value-types/type-auto.ts +21 -0
  152. package/src/render/dom/value-types/type-int.ts +23 -0
  153. package/src/render/dom/value-types/types.ts +8 -0
  154. package/src/render/html/UseHTMLProps.svelte +33 -0
  155. package/src/render/html/UseInitialMotionValues.svelte +27 -0
  156. package/src/render/html/UseStyle.svelte +47 -0
  157. package/src/render/html/config-motion.ts +23 -0
  158. package/src/render/html/supported-elements.ts +10 -0
  159. package/src/render/html/types.ts +64 -0
  160. package/src/render/html/use-props.ts +14 -0
  161. package/src/render/html/utils/build-projection-transform.ts +53 -0
  162. package/src/render/html/utils/build-styles.ts +121 -0
  163. package/src/render/html/utils/build-transform.ts +79 -0
  164. package/src/render/html/utils/create-render-state.ts +18 -0
  165. package/src/render/html/utils/render.ts +22 -0
  166. package/src/render/html/utils/scrape-motion-values.ts +26 -0
  167. package/src/render/html/utils/transform.ts +51 -0
  168. package/src/render/html/visual-element.ts +129 -0
  169. package/src/render/index.ts +703 -0
  170. package/src/render/svg/UseSVGProps.svelte +34 -0
  171. package/src/render/svg/config-motion.ts +51 -0
  172. package/src/render/svg/lowercase-elements.ts +35 -0
  173. package/src/render/svg/supported-elements.ts +10 -0
  174. package/src/render/svg/types.ts +51 -0
  175. package/src/render/svg/use-props.ts +14 -0
  176. package/src/render/svg/utils/build-attrs.ts +58 -0
  177. package/src/render/svg/utils/camel-case-attrs.ts +27 -0
  178. package/src/render/svg/utils/create-render-state.ts +17 -0
  179. package/src/render/svg/utils/path.ts +49 -0
  180. package/src/render/svg/utils/render.ts +22 -0
  181. package/src/render/svg/utils/scrape-motion-values.ts +26 -0
  182. package/src/render/svg/utils/transform-origin.ts +30 -0
  183. package/src/render/svg/visual-element.ts +44 -0
  184. package/src/render/types.ts +148 -0
  185. package/src/render/utils/animation-state.ts +375 -0
  186. package/src/render/utils/animation.ts +167 -0
  187. package/src/render/utils/compare-by-depth.ts +18 -0
  188. package/src/render/utils/flat-tree.ts +35 -0
  189. package/src/render/utils/is-draggable.ts +17 -0
  190. package/src/render/utils/lifecycles.ts +172 -0
  191. package/src/render/utils/motion-values.ts +59 -0
  192. package/src/render/utils/projection.ts +38 -0
  193. package/src/render/utils/setters.ts +910 -0
  194. package/src/render/utils/state.ts +113 -0
  195. package/src/render/utils/types.ts +12 -0
  196. package/src/render/utils/variants.ts +76 -0
  197. package/src/types/geometry.ts +91 -0
  198. package/src/types.ts +1088 -0
  199. package/src/utils/UseUnmountEffect.svelte +11 -0
  200. package/src/utils/array.ts +18 -0
  201. package/src/utils/each-axis.ts +15 -0
  202. package/src/utils/errors.ts +22 -0
  203. package/src/utils/fix-process-env.ts +22 -0
  204. package/src/utils/geometry/delta-apply.ts +162 -0
  205. package/src/utils/geometry/delta-calc.ts +89 -0
  206. package/src/utils/geometry/index.ts +83 -0
  207. package/src/utils/is-browser.ts +12 -0
  208. package/src/utils/is-numerical-string.ts +15 -0
  209. package/src/utils/is-ref-object.ts +16 -0
  210. package/src/utils/noop.ts +15 -0
  211. package/src/utils/resolve-value.ts +23 -0
  212. package/src/utils/shallow-compare.ts +23 -0
  213. package/src/utils/subscription-manager.ts +49 -0
  214. package/src/utils/time-conversion.ts +18 -0
  215. package/src/utils/transform.ts +120 -0
  216. package/src/utils/use-constant.ts +23 -0
  217. package/src/utils/use-cycle.ts +78 -0
  218. package/src/utils/use-force-update.ts +7 -0
  219. package/src/utils/use-isomorphic-effect.ts +8 -0
  220. package/src/utils/use-reduced-motion.ts +70 -0
  221. package/src/utils/use-unmount-effect.ts +8 -0
  222. package/src/value/index.ts +409 -0
  223. package/src/value/scroll/use-element-scroll.ts +73 -0
  224. package/src/value/scroll/use-viewport-scroll.ts +81 -0
  225. package/src/value/scroll/utils.ts +76 -0
  226. package/src/value/use-combine-values.ts +53 -0
  227. package/src/value/use-motion-template.ts +57 -0
  228. package/src/value/use-motion-value.ts +27 -0
  229. package/src/value/use-spring.ts +84 -0
  230. package/src/value/use-transform.ts +216 -0
  231. package/src/value/use-velocity.ts +44 -0
  232. package/src/value/utils/is-motion-value.ts +15 -0
  233. package/src/value/utils/resolve-motion-value.ts +29 -0
@@ -0,0 +1,632 @@
1
+ /**
2
+ based on framer-motion@4.1.17,
3
+ Copyright (c) 2018 Framer B.V.
4
+ */
5
+ import type { RefObject } from "react";
6
+ import type { PanInfo } from "../../gestures/PanSession";
7
+ import type { MotionProps } from "../../motion/types";
8
+ import type { VisualElement } from "../../render/types";
9
+ import type { AxisBox2D, Point2D, TransformPoint2D } from "../../types/geometry";
10
+ import type { DraggableProps, ResolvedConstraints } from "./types";
11
+ import type { Lock } from "./utils/lock.js";
12
+
13
+
14
+ interface DragControlConfig {
15
+ visualElement: VisualElement;
16
+ }
17
+ export interface DragControlOptions {
18
+ snapToCursor?: boolean;
19
+ cursorProgress?: Point2D;
20
+ }
21
+ interface DragControlsProps extends DraggableProps {
22
+ transformPagePoint?: TransformPoint2D;
23
+ }
24
+ type DragDirection = "x" | "y";
25
+ export type expectsResolvedDragConstraints = ({ dragConstraints, onMeasureDragConstraints, }: MotionProps) => boolean;
26
+
27
+ /**
28
+ based on framer-motion@4.1.15,
29
+ Copyright (c) 2018 Framer B.V.
30
+ */
31
+ import { flushSync } from 'framesync';
32
+ import { progress } from 'popmotion';
33
+ import { __assign, __read, __spreadArray } from 'tslib';
34
+ import { startAnimation } from '../../animation/utils/transitions.js';
35
+ import { getViewportPointFromEvent } from '../../events/event-info.js';
36
+ import { addDomEvent } from '../../events/use-dom-event.js';
37
+ import { addPointerEvent } from '../../events/use-pointer-event.js';
38
+ import { calcRelativeOffset } from '../../motion/features/layout/utils.js';
39
+ import { convertToRelativeProjection } from '../../render/dom/projection/convert-to-relative.js';
40
+ import { getBoundingBox } from '../../render/dom/projection/measure.js';
41
+ import { collectProjectingAncestors, collectProjectingChildren, updateLayoutMeasurement } from '../../render/dom/projection/utils.js';
42
+ import { batchLayout, flushLayout } from '../../render/dom/utils/batch-layout.js';
43
+ import { AnimationType } from '../../render/utils/types.js';
44
+ import { eachAxis } from '../../utils/each-axis.js';
45
+ import { invariant } from '../../utils/errors.js';
46
+ import { calcOrigin } from '../../utils/geometry/delta-calc.js';
47
+ import { axisBox, convertAxisBoxToBoundingBox, convertBoundingBoxToAxisBox } from '../../utils/geometry/index.js';
48
+ import { isRefObject } from '../../utils/is-ref-object.js';
49
+ import { PanSession } from '../PanSession.js';
50
+ import { applyConstraints, calcConstrainedMinPoint, calcPositionFromProgress, calcRelativeConstraints, calcViewportConstraints, defaultElastic, rebaseAxisConstraints, resolveDragElastic } from './utils/constraints.js';
51
+ import { getGlobalLock } from './utils/lock.js';
52
+
53
+ var elementDragControls: WeakMap<VisualElement<any, any>, VisualElementDragControls> = new WeakMap();
54
+ /**
55
+ *
56
+ */
57
+ var lastPointerEvent;
58
+
59
+ class VisualElementDragControls {
60
+ /**
61
+ * Track whether we're currently dragging.
62
+ *
63
+ * @internal
64
+ */
65
+ isDragging = false;
66
+ /**
67
+ * The current direction of drag, or `null` if both.
68
+ *
69
+ * @internal
70
+ */
71
+ private currentDirection: DragDirection | null = null;
72
+ /**
73
+ * The permitted boundaries of travel, in pixels.
74
+ *
75
+ * @internal
76
+ */
77
+ private constraints: ResolvedConstraints | false = false;
78
+ /**
79
+ * The per-axis resolved elastic values.
80
+ *
81
+ * @internal
82
+ */
83
+ private elastic = axisBox();
84
+ /**
85
+ * A reference to the host component's latest props.
86
+ *
87
+ * @internal
88
+ */
89
+ private props: MotionProps & DragControlsProps = {};
90
+ /**
91
+ * @internal
92
+ */
93
+ private visualElement: VisualElement<HTMLElement>;
94
+ /**
95
+ * @internal
96
+ */
97
+ private hasMutatedConstraints = false;
98
+ /**
99
+ * @internal
100
+ */
101
+ private cancelLayout?;
102
+ /**
103
+ * Track the initial position of the cursor relative to the dragging element
104
+ * when dragging starts as a value of 0-1 on each axis. We then use this to calculate
105
+ * an ideal bounding box for the VisualElement renderer to project into every frame.
106
+ *
107
+ * @internal
108
+ */
109
+ private cursorProgress: Point2D = {
110
+ x: 0.5,
111
+ y: 0.5,
112
+ };
113
+ private originPoint: Point2D = { x: 0, y: 0 };
114
+ private openGlobalLock: Lock | null = null;
115
+ /**
116
+ * @internal
117
+ */
118
+ private panSession?: PanSession;
119
+ /**
120
+ * A reference to the measured constraints bounding box
121
+ */
122
+ private constraintsBox?;
123
+
124
+ constructor({ visualElement }: DragControlConfig) {
125
+ this.visualElement = visualElement;
126
+ this.visualElement.enableLayoutProjection();
127
+ elementDragControls.set(visualElement, this);
128
+ }
129
+ /**
130
+ * Instantiate a PanSession for the drag gesture
131
+ *
132
+ * @public
133
+ */
134
+ start(originEvent: PointerEvent, { snapToCursor = false, cursorProgress = undefined }: DragControlOptions = {}) {
135
+ const onSessionStart = (event: PointerEvent | typeof this.cancelLayout) => {
136
+ // Stop any animations on both axis values immediately. This allows the user to throw and catch
137
+ // the component.
138
+ this.stopMotion();
139
+ /**
140
+ * Save the initial point. We'll use this to calculate the pointer's position rather
141
+ * than the one we receive when the gesture actually starts. By then, the pointer will
142
+ * have already moved, and the perception will be of the pointer "slipping" across the element
143
+ */
144
+ var initialPoint = getViewportPointFromEvent(event).point;
145
+ (event = this.cancelLayout) === null || event === void 0 ? void 0 : event.call(this);
146
+ var _self = this;
147
+ this.cancelLayout = batchLayout(function (read, write) {
148
+ var ancestors = collectProjectingAncestors(_self.visualElement);
149
+ var children = collectProjectingChildren(_self.visualElement);
150
+ var tree = __spreadArray(__spreadArray([], __read(ancestors)), __read(children));
151
+ var hasManuallySetCursorOrigin = false;
152
+ /**
153
+ * Apply a simple lock to the projection target. This ensures no animations
154
+ * can run on the projection box while this lock is active.
155
+ */
156
+ _self.isLayoutDrag() && _self.visualElement.lockProjectionTarget();
157
+ write(function () {
158
+ tree.forEach(function (element) { return element.resetTransform(); });
159
+ });
160
+ read(function () {
161
+ updateLayoutMeasurement(_self.visualElement);
162
+ children.forEach(updateLayoutMeasurement);
163
+ });
164
+ write(function () {
165
+ tree.forEach(function (element) { return element.restoreTransform(); });
166
+ if (snapToCursor) {
167
+ hasManuallySetCursorOrigin = _self.snapToCursor(initialPoint);
168
+ }
169
+ });
170
+ read(function () {
171
+ var isRelativeDrag = Boolean(_self.getAxisMotionValue("x") && !_self.isExternalDrag());
172
+ if (!isRelativeDrag) {
173
+ _self.visualElement.rebaseProjectionTarget(true, _self.visualElement.measureViewportBox(false));
174
+ }
175
+ _self.visualElement.scheduleUpdateLayoutProjection();
176
+ /**
177
+ * When dragging starts, we want to find where the cursor is relative to the bounding box
178
+ * of the element. Every frame, we calculate a new bounding box using this relative position
179
+ * and let the visualElement renderer figure out how to reproject the element into this bounding
180
+ * box.
181
+ *
182
+ * By doing it this way, rather than applying an x/y transform directly to the element,
183
+ * we can ensure the component always visually sticks to the cursor as we'd expect, even
184
+ * if the DOM element itself changes layout as a result of React updates the user might
185
+ * make based on the drag position.
186
+ */
187
+ var projection = _self.visualElement.projection;
188
+ eachAxis(function (axis) {
189
+ if (!hasManuallySetCursorOrigin) {
190
+ var _a = projection.target[axis], min = _a.min, max = _a.max;
191
+ _self.cursorProgress[axis] = cursorProgress
192
+ ? cursorProgress[axis]
193
+ : progress(min, max, initialPoint[axis]);
194
+ }
195
+ /**
196
+ * If we have external drag MotionValues, record their origin point. On pointermove
197
+ * we'll apply the pan gesture offset directly to this value.
198
+ */
199
+ var axisValue = _self.getAxisMotionValue(axis);
200
+ if (axisValue) {
201
+ _self.originPoint[axis] = axisValue.get();
202
+ }
203
+ });
204
+ });
205
+ write(function () {
206
+ flushSync.update();
207
+ flushSync.preRender();
208
+ flushSync.render();
209
+ flushSync.postRender();
210
+ });
211
+ read(function () { return _self.resolveDragConstraints(); });
212
+ });
213
+ };
214
+ const onStart = (event: PointerEvent, info: PanInfo) => {
215
+ // Attempt to grab the global drag gesture lock - maybe make this part of PanSession
216
+ const { drag, dragPropagation, onDragStart } = this.props;
217
+ if (drag && !dragPropagation) {
218
+ if (this.openGlobalLock)
219
+ this.openGlobalLock();
220
+ this.openGlobalLock = getGlobalLock(drag);
221
+ // If we don 't have the lock, don't start dragging
222
+ if (!this.openGlobalLock)
223
+ return;
224
+ }
225
+ flushLayout();
226
+ // Set current drag status
227
+ this.isDragging = true;
228
+ this.currentDirection = null;
229
+ // Fire onDragStart event
230
+ if(onDragStart) onDragStart(event, info);
231
+ const { animationState } = this.visualElement;
232
+ animationState && animationState.setActive(AnimationType.Drag, true);
233
+ };
234
+ const onMove = (event: PointerEvent, info: PanInfo) => {
235
+ const {
236
+ dragPropagation,
237
+ dragDirectionLock,
238
+ onDirectionLock,
239
+ onDrag,
240
+ } = this.props;
241
+ // If we didn't successfully receive the gesture lock, early return.
242
+ if (!dragPropagation && !this.openGlobalLock)
243
+ return;
244
+ var offset = info.offset;
245
+ // Attempt to detect drag direction if directionLock is true
246
+ if (dragDirectionLock && this.currentDirection === null) {
247
+ this.currentDirection = getCurrentDirection(offset);
248
+ // If we've successfully set a direction, notify listener
249
+ if (this.currentDirection !== null) {
250
+ onDirectionLock && onDirectionLock(this.currentDirection);
251
+ }
252
+ return;
253
+ }
254
+ // Update each point with the latest position
255
+ this.updateAxis("x", info.point, offset);
256
+ this.updateAxis("y", info.point, offset);
257
+ // Fire onDrag event
258
+ onDrag && onDrag(event, info);
259
+ // Update the last pointer event
260
+ lastPointerEvent = event;
261
+ };
262
+ const onSessionEnd = (event: PointerEvent, info: PanInfo) => {
263
+ return this.stop(event, info);
264
+ };
265
+ const transformPagePoint = this.props.transformPagePoint;
266
+ this.panSession = new PanSession(originEvent, {
267
+ onSessionStart,
268
+ onStart,
269
+ onMove,
270
+ onSessionEnd,
271
+ }, { transformPagePoint: transformPagePoint });
272
+ }
273
+ resolveDragConstraints() {
274
+ const { dragConstraints, dragElastic } = this.props;
275
+ var layout = this.visualElement.getLayoutState().layoutCorrected;
276
+ if (dragConstraints) {
277
+ this.constraints = isRefObject(dragConstraints)
278
+ ? this.resolveRefConstraints(layout, dragConstraints)
279
+ : calcRelativeConstraints(layout, dragConstraints);
280
+ }
281
+ else {
282
+ this.constraints = false;
283
+ }
284
+ this.elastic = resolveDragElastic(dragElastic);
285
+ /**
286
+ * If we're outputting to external MotionValues, we want to rebase the measured constraints
287
+ * from viewport-relative to component-relative.
288
+ */
289
+ if (this.constraints && !this.hasMutatedConstraints) {
290
+ eachAxis((axis) => {
291
+ if (this.getAxisMotionValue(axis)) {
292
+ this.constraints[axis] = rebaseAxisConstraints(layout[axis], this.constraints[axis]);
293
+ }
294
+ });
295
+ }
296
+ }
297
+ private resolveRefConstraints(layoutBox: AxisBox2D, constraints: RefObject<Element>) {
298
+ const { transformPagePoint, onMeasureDragConstraints } = this.props;
299
+ const constraintsElement = constraints.current as HTMLElement;
300
+ invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.");
301
+ this.constraintsBox = getBoundingBox(constraintsElement, transformPagePoint);
302
+ var measuredConstraints = calcViewportConstraints(layoutBox, this.constraintsBox);
303
+ /**
304
+ * If there's an onMeasureDragConstraints listener we call it and
305
+ * if different constraints are returned, set constraints to that
306
+ */
307
+ if (onMeasureDragConstraints) {
308
+ var userConstraints = onMeasureDragConstraints(convertAxisBoxToBoundingBox(measuredConstraints));
309
+ this.hasMutatedConstraints = !!userConstraints;
310
+ if (userConstraints) {
311
+ measuredConstraints = convertBoundingBoxToAxisBox(userConstraints);
312
+ }
313
+ }
314
+ return measuredConstraints;
315
+ }
316
+ private cancelDrag() {
317
+ var _a, _b;
318
+ this.visualElement.unlockProjectionTarget();
319
+ (_a = this.cancelLayout) === null || _a === void 0 ? void 0 : _a.call(this);
320
+ this.isDragging = false;
321
+ const { projection, animationState } = this.visualElement
322
+ this.panSession && this.panSession.end();
323
+ this.panSession = undefined;
324
+ if (!this.props.dragPropagation && this.openGlobalLock) {
325
+ this.openGlobalLock();
326
+ this.openGlobalLock = null;
327
+ }
328
+ animationState && animationState.setActive(AnimationType.Drag, false)
329
+ }
330
+ private stop(event: PointerEvent, info: PanInfo) {
331
+ var _a, _b, _c;
332
+ (_a = this.panSession) === null || _a === void 0 ? void 0 : _a.end();
333
+ this.panSession = undefined;
334
+ var isDragging = this.isDragging;
335
+ this.cancelDrag();
336
+ if (!isDragging)
337
+ return;
338
+ var velocity = info.velocity;
339
+ this.animateDragEnd(velocity);
340
+ const { onDragEnd } = this.props;
341
+ if (onDragEnd) onDragEnd(event, info)
342
+ }
343
+ snapToCursor(point: Point2D) {
344
+ var _this = this;
345
+ return eachAxis(function (axis) {
346
+ var drag = _this.props.drag;
347
+ // If we're not dragging this axis, do an early return.
348
+ if (!shouldDrag(axis, drag, _this.currentDirection))
349
+ return;
350
+ var axisValue = _this.getAxisMotionValue(axis);
351
+ if (axisValue) {
352
+ var box = _this.visualElement.getLayoutState().layout;
353
+ var length_1 = box[axis].max - box[axis].min;
354
+ var center = box[axis].min + length_1 / 2;
355
+ var offset = point[axis] - center;
356
+ _this.originPoint[axis] = point[axis];
357
+ axisValue.set(offset);
358
+ }
359
+ else {
360
+ _this.cursorProgress[axis] = 0.5;
361
+ return true;
362
+ }
363
+ }).includes(true);
364
+ };
365
+ /**
366
+ * Update the specified axis with the latest pointer information.
367
+ */
368
+ private updateAxis(axis: DragDirection, point: Point2D, offset?: Point2D) {
369
+ var drag = this.props.drag;
370
+ // If we're not dragging this axis, do an early return.
371
+ if (!shouldDrag(axis, drag, this.currentDirection))
372
+ return;
373
+ return this.getAxisMotionValue(axis)
374
+ ? this.updateAxisMotionValue(axis, offset)
375
+ : this.updateVisualElementAxis(axis, point);
376
+ };
377
+ private updateAxisMotionValue(axis: DragDirection, offset?: Point2D) {
378
+ var axisValue = this.getAxisMotionValue(axis);
379
+ if (!offset || !axisValue)
380
+ return;
381
+ var nextValue = this.originPoint[axis] + offset[axis];
382
+ var update = this.constraints
383
+ ? applyConstraints(nextValue, this.constraints[axis], this.elastic[axis])
384
+ : nextValue;
385
+ axisValue.set(update);
386
+ };
387
+ private updateVisualElementAxis(axis: DragDirection, point: Point2D) {
388
+ var _a;
389
+ // Get the actual layout bounding box of the element
390
+ var axisLayout = this.visualElement.getLayoutState().layout[axis];
391
+ // Calculate its current length. In the future we might want to lerp this to animate
392
+ // between lengths if the layout changes as we change the DOM
393
+ var axisLength = axisLayout.max - axisLayout.min;
394
+ // Get the initial progress that the pointer sat on this axis on gesture start.
395
+ var axisProgress = this.cursorProgress[axis];
396
+ // Calculate a new min point based on the latest pointer position, constraints and elastic
397
+ var min = calcConstrainedMinPoint(point[axis], axisLength, axisProgress, (_a = this.constraints) === null || _a === void 0 ? void 0 : _a[axis], this.elastic[axis]);
398
+ // Update the axis viewport target with this new min and the length
399
+ this.visualElement.setProjectionTargetAxis(axis, min, min + axisLength);
400
+ };
401
+ setProps({ drag = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true, ...remainingProps }: DragControlsProps & MotionProps) {
402
+ this.props = {
403
+ ...remainingProps,
404
+ drag,
405
+ dragDirectionLock,
406
+ dragPropagation,
407
+ dragConstraints,
408
+ dragElastic,
409
+ dragMomentum,
410
+ };
411
+ };
412
+ /**
413
+ * Drag works differently depending on which props are provided.
414
+ *
415
+ * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values.
416
+ * - If the component will perform layout animations, we output the gesture to the component's
417
+ * visual bounding box
418
+ * - Otherwise, we apply the delta to the x/y motion values.
419
+ */
420
+ private getAxisMotionValue(axis: string) {
421
+ var _a = this.props, layout = _a.layout, layoutId = _a.layoutId;
422
+ var dragKey = "_drag" + axis.toUpperCase();
423
+ if (this.props[dragKey]) {
424
+ return this.props[dragKey];
425
+ }
426
+ else if (!layout && layoutId === undefined) {
427
+ return this.visualElement.getValue(axis, 0);
428
+ }
429
+ }
430
+ private isLayoutDrag() {
431
+ return !this.getAxisMotionValue("x");
432
+ }
433
+ private isExternalDrag() {
434
+ var _a = this.props, _dragX = _a._dragX, _dragY = _a._dragY;
435
+ return _dragX || _dragY;
436
+ }
437
+ private animateDragEnd(velocity) {
438
+ var _this = this;
439
+ var _a = this.props, drag = _a.drag, dragMomentum = _a.dragMomentum, dragElastic = _a.dragElastic, dragTransition = _a.dragTransition;
440
+ /**
441
+ * Everything beyond the drag gesture should be performed with
442
+ * relative projection so children stay in sync with their parent element.
443
+ */
444
+ var isRelative = convertToRelativeProjection(this.visualElement, this.isLayoutDrag() && !this.isExternalDrag());
445
+ /**
446
+ * If we had previously resolved constraints relative to the viewport,
447
+ * we need to also convert those to a relative coordinate space for the animation
448
+ */
449
+ var constraints = this.constraints || {};
450
+ if (isRelative &&
451
+ Object.keys(constraints).length &&
452
+ this.isLayoutDrag()) {
453
+ var projectionParent = this.visualElement.getProjectionParent();
454
+ if (projectionParent) {
455
+ var relativeConstraints_1 = calcRelativeOffset(projectionParent.projection.targetFinal, constraints);
456
+ eachAxis(function (axis) {
457
+ var _a = relativeConstraints_1[axis], min = _a.min, max = _a.max;
458
+ constraints[axis] = {
459
+ min: isNaN(min) ? undefined : min,
460
+ max: isNaN(max) ? undefined : max,
461
+ };
462
+ });
463
+ }
464
+ }
465
+ var momentumAnimations = eachAxis(function (axis) {
466
+ var _a;
467
+ if (!shouldDrag(axis, drag, _this.currentDirection)) {
468
+ return;
469
+ }
470
+ var transition = (_a = constraints === null || constraints === void 0 ? void 0 : constraints[axis]) !== null && _a !== void 0 ? _a : {};
471
+ /**
472
+ * Overdamp the boundary spring if `dragElastic` is disabled. There's still a frame
473
+ * of spring animations so we should look into adding a disable spring option to `inertia`.
474
+ * We could do something here where we affect the `bounceStiffness` and `bounceDamping`
475
+ * using the value of `dragElastic`.
476
+ */
477
+ var bounceStiffness = dragElastic ? 200 : 1000000;
478
+ var bounceDamping = dragElastic ? 40 : 10000000;
479
+ var inertia = __assign(__assign({ type: "inertia", velocity: dragMomentum ? velocity[axis] : 0, bounceStiffness: bounceStiffness,
480
+ bounceDamping: bounceDamping, timeConstant: 750, restDelta: 1, restSpeed: 10 }, dragTransition), transition);
481
+ // If we're not animating on an externally-provided `MotionValue` we can use the
482
+ // component's animation controls which will handle interactions with whileHover (etc),
483
+ // otherwise we just have to animate the `MotionValue` itself.
484
+ return _this.getAxisMotionValue(axis)
485
+ ? _this.startAxisValueAnimation(axis, inertia)
486
+ : _this.visualElement.startLayoutAnimation(axis, inertia, isRelative);
487
+ });
488
+ // Run all animations and then resolve the new drag constraints.
489
+ return Promise.all(momentumAnimations).then(function () {
490
+ var _a, _b;
491
+ (_b = (_a = _this.props).onDragTransitionEnd) === null || _b === void 0 ? void 0 : _b.call(_a);
492
+ });
493
+ }
494
+ stopMotion() {
495
+ var _this = this;
496
+ eachAxis(function (axis) {
497
+ var axisValue = _this.getAxisMotionValue(axis);
498
+ axisValue
499
+ ? axisValue.stop()
500
+ : _this.visualElement.stopLayoutAnimation();
501
+ });
502
+ }
503
+ private startAxisValueAnimation(axis, transition) {
504
+ var axisValue = this.getAxisMotionValue(axis);
505
+ if (!axisValue)
506
+ return;
507
+ var currentValue = axisValue.get();
508
+ axisValue.set(currentValue);
509
+ axisValue.set(currentValue); // Set twice to hard-reset velocity
510
+ return startAnimation(axis, axisValue, 0, transition);
511
+ }
512
+ scalePoint() {
513
+ var _this = this;
514
+ var _a = this.props, drag = _a.drag, dragConstraints = _a.dragConstraints;
515
+ if (!isRefObject(dragConstraints) || !this.constraintsBox)
516
+ return;
517
+ // Stop any current animations as there can be some visual glitching if we resize mid animation
518
+ this.stopMotion();
519
+ // Record the relative progress of the targetBox relative to the constraintsBox
520
+ var boxProgress = { x: 0, y: 0 };
521
+ eachAxis(function (axis) {
522
+ boxProgress[axis] = calcOrigin(_this.visualElement.projection.target[axis], _this.constraintsBox[axis]);
523
+ });
524
+ /**
525
+ * For each axis, calculate the current progress of the layout axis within the constraints.
526
+ * Then, using the latest layout and constraints measurements, reposition the new layout axis
527
+ * proportionally within the constraints.
528
+ */
529
+ this.updateConstraints(function () {
530
+ eachAxis(function (axis) {
531
+ if (!shouldDrag(axis, drag, null))
532
+ return;
533
+ // Calculate the position of the targetBox relative to the constraintsBox using the
534
+ // previously calculated progress
535
+ var _a = calcPositionFromProgress(_this.visualElement.projection.target[axis], _this.constraintsBox[axis], boxProgress[axis]), min = _a.min, max = _a.max;
536
+ _this.visualElement.setProjectionTargetAxis(axis, min, max);
537
+ });
538
+ });
539
+ /**
540
+ * If any other draggable components are queuing the same tasks synchronously
541
+ * this will wait until they've all been scheduled before flushing.
542
+ */
543
+ setTimeout(flushLayout, 1);
544
+ }
545
+ updateConstraints(onReady?: () => void) {
546
+ var _this = this;
547
+ this.cancelLayout = batchLayout(function (read, write) {
548
+ var ancestors = collectProjectingAncestors(_this.visualElement);
549
+ write(function () {
550
+ return ancestors.forEach(function (element) { return element.resetTransform(); });
551
+ });
552
+ read(function () { return updateLayoutMeasurement(_this.visualElement); });
553
+ write(function () {
554
+ return ancestors.forEach(function (element) { return element.restoreTransform(); });
555
+ });
556
+ read(function () {
557
+ _this.resolveDragConstraints();
558
+ });
559
+ if (onReady)
560
+ write(onReady);
561
+ });
562
+ };
563
+ mount(visualElement: VisualElement): () => void {
564
+ var _this = this;
565
+ var element = visualElement.getInstance();
566
+ /**
567
+ * Attach a pointerdown event listener on this DOM element to initiate drag tracking.
568
+ */
569
+ var stopPointerListener = addPointerEvent(element, "pointerdown", function (event) {
570
+ var _a = _this.props, drag = _a.drag, _b = _a.dragListener, dragListener = _b === void 0 ? true : _b;
571
+ drag && dragListener && _this.start(event);
572
+ });
573
+ /**
574
+ * Attach a window resize listener to scale the draggable target within its defined
575
+ * constraints as the window resizes.
576
+ */
577
+ var stopResizeListener = addDomEvent(window, "resize", function () {
578
+ _this.scalePoint();
579
+ });
580
+ /**
581
+ * Ensure drag constraints are resolved correctly relative to the dragging element
582
+ * whenever its layout changes.
583
+ */
584
+ var stopLayoutUpdateListener = visualElement.onLayoutUpdate(function () {
585
+ if (_this.isDragging) {
586
+ _this.resolveDragConstraints();
587
+ }
588
+ });
589
+ /**
590
+ * If the previous component with this same layoutId was dragging at the time
591
+ * it was unmounted, we want to continue the same gesture on this component.
592
+ */
593
+ var prevDragCursor = visualElement.prevDragCursor;
594
+ if (prevDragCursor) {
595
+ this.start(lastPointerEvent, { cursorProgress: prevDragCursor });
596
+ }
597
+ /**
598
+ * Return a function that will teardown the drag gesture
599
+ */
600
+ return function () {
601
+ stopPointerListener === null || stopPointerListener === void 0 ? void 0 : stopPointerListener();
602
+ stopResizeListener === null || stopResizeListener === void 0 ? void 0 : stopResizeListener();
603
+ stopLayoutUpdateListener === null || stopLayoutUpdateListener === void 0 ? void 0 : stopLayoutUpdateListener();
604
+ _this.cancelDrag();
605
+ };
606
+ };
607
+ }
608
+
609
+ function shouldDrag(direction: DragDirection, drag: boolean | DragDirection | undefined, currentDirection: null | DragDirection) {
610
+ return ((drag === true || drag === direction) &&
611
+ (currentDirection === null || currentDirection === direction));
612
+ }
613
+ /**
614
+ * Based on an x/y offset determine the current drag direction. If both axis' offsets are lower
615
+ * than the provided threshold, return `null`.
616
+ *
617
+ * @param offset - The x/y offset from origin.
618
+ * @param lockThreshold - (Optional) - the minimum absolute offset before we can determine a drag direction.
619
+ */
620
+ function getCurrentDirection(offset: Point2D, lockThreshold = 10) {
621
+ var direction: DragDirection | null = null;
622
+ if (Math.abs(offset.y) > lockThreshold) {
623
+ direction = "y";
624
+ }
625
+ else if (Math.abs(offset.x) > lockThreshold) {
626
+ direction = "x";
627
+ }
628
+ return direction;
629
+ }
630
+
631
+ export { VisualElementDragControls, elementDragControls };
632
+