Skip to content

Commit 2528bb2

Browse files
hartzisbinoy14Stefan Huynh
authored
V7 (#289)
* Replace microbundle with rollup (#273) * Prevent scroll prop (#240) * update changelog with callouts * update format, fix lint config issue, update contributing * set ts output target to es2015, update changelog * add comments to types for more info (#293) * setup touchEventOptions prop (#290) * setup touchEventOptions prop * add onTouchStartOrOnMouseDown prop and test * add onTouchEndOrOnMouseUp callback * Feature swipeDuration (#291) * update docs and migration * 7.0.0-alpha.0 * update deps, add react 18 peer * 7.0.0-alpha.1 * update examples to use react 18 * update deps, update LICENSE dates * update readme, types, example types * export/outputs housekeeping and cleaning * 7.0.0-alpha.2 * fix issue #304 * 7.0.0-alpha.3 * bump deps Co-authored-by: Binoy <[email protected]> Co-authored-by: Stefan Huynh <[email protected]> Co-authored-by: Brian Emil Hartz <[email protected]>
1 parent 193654a commit 2528bb2

29 files changed

+2703
-7052
lines changed

.eslintignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
node_modules
2+
es
23
dist
34
lib
45
examples

.github/workflows/size.yml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
name: size
2+
on: [pull_request]
3+
jobs:
4+
size:
5+
runs-on: ubuntu-latest
6+
env:
7+
CI_JOB_NUMBER: 1
8+
steps:
9+
- uses: actions/checkout@v1
10+
- uses: andresz1/size-limit-action@v1
11+
with:
12+
github_token: ${{ secrets.GITHUB_TOKEN }}

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ TODO
33
*.log
44
.DS_Store
55
.vscode
6+
es
67
lib
78
dist
89
examples/static

.prettierignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package.json
22
node_modules
3+
/es
34
/lib
45
/dist
56
/coverage

CHANGELOG.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,52 @@
1+
# UNRELEASED
2+
3+
**New Features:**
4+
- add new `swipeDuration` prop - "allowable duration of a swipe"
5+
- A swipe lasting more than `swipeDuration`, in milliseconds, will **not** be considered a swipe.
6+
- Feature mimicked from `use-gesture` [swipe.duration](https://use-gesture.netlify.app/docs/options/#swipeduration)
7+
- Defaults to `Infinity` for backwards compatibility
8+
- add new `touchEventOptions` prop that can set the options for the touch event listeners
9+
- this provides users full control of if/when they want to set [passive](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#options)
10+
- Defaults to `{ passive: true }`
11+
- add new `onTouchStartOrOnMouseDown` prop that is called for `touchstart` and `mousedown`. Before a swipe even starts.
12+
- combined with `touchEventOptions` allows users the ability to now call `preventDefault` on `touchstart`
13+
- add new `onTouchEndOrOnMouseUp` prop that is called for `touchend` and `mouseup`.
14+
- add [react 18](https://reactjs.org/blog/2022/03/29/react-v18.html) to `peerDependencies`
15+
16+
**Breaking Changes:**
17+
* we have dropped support for `es5` transpiled output
18+
* we target `es2015` for our transpilation now
19+
* `swipeable` utilizes object/array spread & const/let natively
20+
* `preventScrollOnSwipe` - "new" prop. Replaces `preventDefaultTouchmoveEvent`
21+
* same functionality but renamed to be more explicit on its intended use
22+
* **fixed bug** - where toggling this prop did not re-attach event listeners
23+
* **update** - we now **only** change the `passive` event listener option for `touchmove` depending on this prop
24+
* see notes in README for more details [readme#passive-listener](https://github.com/FormidableLabs/react-swipeable#passive-listener)
25+
* Thank you [@stefvhuynh](https://github.com/stefvhuynh)
26+
27+
**Bug fixes:**
28+
* fix bug where directional swiped check allowed `undefined`/falsy values to set `cancelablePageSwipe`
29+
* Thank you [@bhj](https://github.com/bhj) for the [comment](https://github.com/FormidableLabs/react-swipeable/pull/240#issuecomment-1014980025)
30+
* fix bug when both `trackTouch` and `trackMouse` were present that triggered an erroneous swipe when the user clicked outside and above the swipeable area
31+
* See [issue 304](https://github.com/FormidableLabs/react-swipeable/issues/304) for details
32+
* Thank you [@Sacret](https://github.com/Sacret)
33+
34+
**Infrastructure:**
35+
* post `size-limit report` to PRs with bundle diff sizes
36+
* utilize `rollup` for build & output
37+
* remove dependency on `microbundle`
38+
* remove `interop` injected code - [pull/260](https://github.com/FormidableLabs/react-swipeable/pull/260#discussion_r679541081)
39+
* Thank you [@binoy14](https://github.com/binoy14)
40+
* upgrade lots of dev dependencies
41+
* 🎉 upgrade to `typescript` `v4.6.3`
42+
* export/outputs housekeeping and cleaning (mimicked from `react-redux`)
43+
* removed/renamed exports from `package.json`:
44+
* `browser`, `umd:main`(renamed `dist`), `jsnext:main`(use `module`), `typings`(use `types`)
45+
* moved exports - **old** => **new**
46+
* `"main": "./dist/react-swipeable.js"` => `"main": "./lib/index.js"`
47+
* `"module": "./dist/react-swipeable.module.js"` => `"module": "es/index.js"`
48+
* `"types": "./dist/index.d.ts"` => `"types": "./es/index.d.ts"`
49+
150
# v6.2.2
251
* add react v18 to `peerDependencies`
352

CONTRIBUTING.md

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,15 @@ $ yarn run prettier
7979
$ yarn run format
8080
```
8181

82+
If you see this error:
83+
```
84+
[warn] Code style issues found in the above file(s). Forgot to run Prettier?
85+
```
86+
Then run the formatter:
87+
```sh
88+
$ yarn run format
89+
```
90+
8291
## Project Maintainers
8392
### Releasing a new version
8493
1. Publish to npm
@@ -112,8 +121,8 @@ Make sure you've already completed the above steps for `Update version in the ex
112121

113122
(Optional) Validate examples build locally
114123
```sh
115-
# From root run build:examples
116-
$ yarn build:examples
124+
# From root - build the examples
125+
$ yarn examples:build
117126

118127
# cd into examples and start simple http server(python v3)
119128
# validate everything works locally: http://localhost:8080/
@@ -122,7 +131,6 @@ examples$ python -m http.server 8080
122131
```
123132

124133
```sh
125-
# From the root run build:publish:examples
126-
# This will build and publish the examples app to github pages
127-
$ yarn build:publish:examples
134+
# From root - build and publish the examples app to github pages
135+
$ yarn examples:build:publish
128136
```

LICENSE

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
The MIT License (MIT)
22

3-
Copyright (C) 2014-2020 Josh Perez
4-
Copyright (C) 2014-2020 Brian Emil Hartz
5-
Copyright (C) 2020 Formidable Labs, Inc.
3+
Copyright (C) 2014-2022 Josh Perez
4+
Copyright (C) 2014-2022 Brian Emil Hartz
5+
Copyright (C) 2022 Formidable Labs, Inc.
66

77
Permission is hereby granted, free of charge, to any person obtaining a copy
88
of this software and associated documentation files (the "Software"), to deal

README.md

Lines changed: 80 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ Spread `handlers` onto the element you wish to track swipes on.
3636
onSwipeStart, // Start of swipe (SwipeEventData) => void *see details*
3737
onSwiping, // During swiping (SwipeEventData) => void
3838
onTap, // After a tap ({ event }) => void
39+
40+
// Pass through callbacks, event provided: ({ event }) => void
41+
onTouchStartOrOnMouseDown, // Called for `touchstart` and `mousedown`
42+
onTouchEndOrOnMouseUp, // Called for `touchend` and `mouseup`
3943
}
4044
```
4145

@@ -47,24 +51,48 @@ Spread `handlers` onto the element you wish to track swipes on.
4751

4852
```js
4953
{
50-
delta: 10, // min distance(px) before a swipe starts. *See Notes*
51-
preventDefaultTouchmoveEvent: false, // call e.preventDefault *See Details*
52-
trackTouch: true, // track touch input
53-
trackMouse: false, // track mouse input
54-
rotationAngle: 0, // set a rotation angle
54+
delta: 10, // min distance(px) before a swipe starts. *See Notes*
55+
preventScrollOnSwipe: false, // prevents scroll during swipe (*See Details*)
56+
trackTouch: true, // track touch input
57+
trackMouse: false, // track mouse input
58+
rotationAngle: 0, // set a rotation angle
59+
swipeDuration: Infinity, // allowable duration of a swipe (ms). *See Notes*
60+
touchEventOptions: { passive: true }, // options for touch listeners (*See Details*)
5561
}
5662
```
5763

58-
#### Delta
64+
#### delta
5965

6066
`delta` can be either a `number` or an `object` specifying different deltas for each direction, [`left`, `right`, `up`, `down`], direction values are optional and will default to `10`;
6167

6268
```js
6369
{
64-
delta: { top: 20, bottom: 20 } // top and bottom when ">= 20", left and right default to ">= 10"
70+
delta: { up: 20, down: 20 } // up and down ">= 20", left and right default to ">= 10"
71+
}
72+
```
73+
74+
#### swipeDuration
75+
A swipe lasting more than `swipeDuration`, in milliseconds, will **not** be considered a swipe.
76+
- It will also **not** trigger any callbacks and the swipe event will stop being tracked
77+
- **Defaults** to `Infinity` for backwards compatibility, a sensible duration could be something like `250`
78+
- Feature mimicked from `use-gesture` [swipe.duration](https://use-gesture.netlify.app/docs/options/#swipeduration)
79+
80+
```js
81+
{
82+
swipeDuration: 250 // only swipes under 250ms will trigger callbacks
6583
}
6684
```
6785

86+
#### touchEventOptions
87+
88+
Allows the user to set the options for the touch event listeners( currently only `passive` option ).
89+
- `touchstart`, `touchmove`, and `touchend` event listeners
90+
- **Defaults** to `{ passive: true }`
91+
- this provides users full control of if/when they want to set [passive](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#options)
92+
- https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#options
93+
- `preventScrollOnSwipe` option **supersedes** `touchEventOptions.passive` for `touchmove` event listener
94+
- See `preventScrollOnSwipe` for [more details](#preventscrollonswipe-details)
95+
6896
## Swipe Event Data
6997

7098
All Event Handlers are called with the below event data, `SwipeEventData`.
@@ -73,7 +101,7 @@ All Event Handlers are called with the below event data, `SwipeEventData`.
73101
{
74102
event, // source event
75103
initial, // initial swipe [x,y]
76-
first, // true for first event
104+
first, // true for the first event of a tracked swipe
77105
deltaX, // x offset (current.x - initial.x)
78106
deltaY, // y offset (current.y - initial.y)
79107
absX, // absolute deltaX
@@ -90,47 +118,42 @@ All Event Handlers are called with the below event data, `SwipeEventData`.
90118

91119
- Hook use requires **react >= 16.8.3**
92120
- The props contained in `handlers` are currently `ref` and `onMouseDown`
93-
- Please spread `handlers` as the props contained in it could change as react improves event listening capabilities
121+
- Please spread `handlers` as the props contained in it could change as react changes event listening capabilities
94122

95-
### `preventDefaultTouchmoveEvent` details
123+
### `preventScrollOnSwipe` details
96124

97-
This prop allows you to prevent the browser's [touchmove](https://developer.mozilla.org/en-US/docs/Web/Events/touchmove) event default action, mostly "scrolling".
125+
This prop prevents scroll during swipe in most cases. Use this to **stop scrolling** in the browser while a user swipes.
98126

99-
Use this to **stop scrolling** in the browser while a user swipes.
100-
- You can additionally try `touch-action` css property, [see below](#how-to-use-touch-action-to-prevent-scrolling)
127+
Swipeable will call `e.preventDefault()` internally in an attempt to stop the browser's [touchmove](https://developer.mozilla.org/en-US/docs/Web/Events/touchmove) event default action (mostly scrolling).
128+
129+
**NOTE:** `preventScrollOnSwipe` option **supersedes** `touchEventOptions.passive` for the `touchmove` event listener
130+
131+
**Example scenario:**
132+
> If a user is swiping right with props `{ onSwipedRight: userSwipedRight, preventScrollOnSwipe: true }` then `e.preventDefault()` will be called, but if the user was swiping left then `e.preventDefault()` would **not** be called.
101133
102134
`e.preventDefault()` is only called when:
103-
- `preventDefaultTouchmoveEvent: true`
135+
- `preventScrollOnSwipe: true`
104136
- `trackTouch: true`
105137
- the users current swipe has an associated `onSwiping` or `onSwiped` handler/prop
106138

107-
Example scenario:
108-
> If a user is swiping right with props `{ onSwipedRight: userSwipedRight, preventDefaultTouchmoveEvent: true }` then `e.preventDefault()` will be called, but if the user was swiping left then `e.preventDefault()` would **not** be called.
109-
110-
Please experiment with the [example app](http://formidablelabs.github.io/react-swipeable/) to test `preventDefaultTouchmoveEvent`.
139+
Please experiment with the [example app](http://formidablelabs.github.io/react-swipeable/) to test `preventScrollOnSwipe`.
111140

112-
#### passive listener
113-
With v6 we've added the passive event listener option, by default, to **internal uses** of `addEventListener`. We set the `passive` option to `false` only when `preventDefaultTouchmoveEvent` is `true`.
141+
#### passive listener details
142+
Swipeable adds the passive event listener option, by default, to **internal uses** of touch `addEventListener`'s. We set the `passive` option to `false` only when `preventScrollOnSwipe` is `true` and only to `touchmove`. Other listeners will retain `passive: true`.
114143

115-
**When `preventDefaultTouchmoveEvent` is:**
116-
- `true` => `el.addEventListener(event, cb, { passive: false })`
117-
- `false` => `el.addEventListener(event, cb, { passive: true })`
144+
**When `preventScrollOnSwipe` is:**
145+
- `true` => `el.addEventListener('touchmove', cb, { passive: false })`
146+
- `false` => `el.addEventListener('touchmove', cb, { passive: true })`
118147

119-
React's long running passive [event issue](https://github.com/facebook/react/issues/6436).
148+
Here is more information on react's long running passive [event issue](https://github.com/facebook/react/issues/6436).
120149

121-
We previously had issues with chrome lighthouse performance deducting points for not having passive option set.
150+
We previously had issues with chrome lighthouse performance deducting points for not having passive option set so it is now on by default except in the case mentioned above.
122151

123-
### Browser Support
152+
If, however, you really **need** _all_ of the listeners to be passive (for performance reasons or otherwise), you can prevent all scrolling on the swipeable container by using the `touch-action` css property instead, [see below for an example](#how-to-use-touch-action-to-prevent-scrolling).
124153

125-
The release of v6 `react-swipeable` we only support browsers that support options object for `addEventListener`, [Browser compatibility](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Browser_compatibility). Which mainly means `react-swipeable` does not support ie11 by default, you need to polyfill options. For example using [event-listener-with-options](https://github.com/Macil/event-listener-with-options).
154+
### Version 7 Updates and migration
126155

127-
### Version 6 Updates and migration
128-
129-
If upgrading from v5 or later please refer to the release notes and the [v6 migration doc](./migration.md)
130-
131-
v6 now only exports a hook, `useSwipeable`.
132-
133-
If you would like something similar to the old `<Swipeable>` component you can recreate it from the hook. There are examples in the [migration doc](./migration.md#swipeable-component-examples).
156+
If upgrading from v6 refer to the release notes and the [migration doc](./migration.md).
134157

135158
## FAQs
136159

@@ -174,21 +197,39 @@ const MyComponent = () => {
174197
175198
### How to use `touch-action` to prevent scrolling?
176199
177-
Sometimes you don't want the `body` of your page to scroll along with the user manipulating or swiping an item.
200+
Sometimes you don't want the `body` of your page to scroll along with the user manipulating or swiping an item. Or you might want all of the internal event listeners to be passive and performant.
178201
179-
You might try to prevent the event default action via [preventDefaultTouchmoveEvent](#preventdefaulttouchmoveevent-details), which calls `event.preventDefault()`. **But** there may be a simpler, more effective solution, which has to do with a simple CSS property.
202+
You can prevent scrolling via [preventScrollOnSwipe](#preventscrollonswipe-details), which calls `event.preventDefault()` during `onTouchMove`. **But** there may be a simpler, more effective solution, which has to do with a simple CSS property.
180203
181-
`touch-action` is a CSS property that sets how an element's region can be manipulated by a touchscreen user.
204+
`touch-action` is a CSS property that sets how an element's region can be manipulated by a touchscreen user. See the [documentation for `touch-action`](https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action) to determine which property value to use for your particular use case.
182205
206+
#### Static example
183207
```js
184208
const handlers = useSwipeable({
185-
onSwiped: (eventData) => console.log("User Swiped!", evenData),
209+
onSwiped: (eventData) => console.log("User Swiped!", eventData),
186210
...config,
187211
});
188-
return <div {...handlers} style={{ touchAction: 'pan-y' }}> Swipe here </div>;
212+
213+
return <div {...handlers} style={{ touchAction: 'pan-y' }}>Swipe here</div>;
189214
```
190215
This explanation and example borrowed from `use-gesture`'s [wonderful docs](https://use-gesture.netlify.app/docs/extras/#touch-action).
191216
217+
#### Dynamic example
218+
```js
219+
const MySwipeableComponent = props => {
220+
const [stopScroll, setStopScroll] = useState(false);
221+
222+
const handlers = useSwipeable({
223+
onSwipeStart: () => setStopScroll(true),
224+
onSwiped: () => setStopScroll(false)
225+
});
226+
227+
return <div {...handlers} style={{ touchAction: stopScroll ? 'none' : 'auto' }}>Swipe here</div>;
228+
};
229+
```
230+
231+
This is a somewhat contrived example as the final outcome would be similar to the static example. However, there may be cases where you want to determine when the user can scroll based on the user's swiping action along with any number of variables from state and props.
232+
192233
## License
193234
194235
[MIT]((./LICENSE))

__tests__/helpers/index.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
import { MockedSwipeFunctions } from "../useSwipeable.spec";
1+
export type MockedSwipeFunctions = {
2+
onSwiping: jest.Mock;
3+
onSwiped: jest.Mock;
4+
onSwipedLeft: jest.Mock;
5+
onSwipedRight: jest.Mock;
6+
onSwipedUp: jest.Mock;
7+
onSwipedDown: jest.Mock;
8+
};
29

310
const expectSwipingDir = (fns: jest.Mock, dir: string) => {
411
fns.mock.calls.forEach((call) => {

0 commit comments

Comments
 (0)