Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

V7 #289

Merged
merged 23 commits into from
Apr 27, 2022
Merged

V7 #289

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
node_modules
es
dist
lib
examples
12 changes: 12 additions & 0 deletions .github/workflows/size.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
name: size
on: [pull_request]
jobs:
size:
runs-on: ubuntu-latest
env:
CI_JOB_NUMBER: 1
steps:
- uses: actions/checkout@v1
- uses: andresz1/size-limit-action@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ TODO
*.log
.DS_Store
.vscode
es
lib
dist
examples/static
Expand Down
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package.json
node_modules
/es
/lib
/dist
/coverage
Expand Down
49 changes: 49 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,52 @@
# UNRELEASED

**New Features:**
- add new `swipeDuration` prop - "allowable duration of a swipe"
- A swipe lasting more than `swipeDuration`, in milliseconds, will **not** be considered a swipe.
- Feature mimicked from `use-gesture` [swipe.duration](https://use-gesture.netlify.app/docs/options/#swipeduration)
- Defaults to `Infinity` for backwards compatibility
- add new `touchEventOptions` prop that can set the options for the touch event listeners
- 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)
- Defaults to `{ passive: true }`
- add new `onTouchStartOrOnMouseDown` prop that is called for `touchstart` and `mousedown`. Before a swipe even starts.
- combined with `touchEventOptions` allows users the ability to now call `preventDefault` on `touchstart`
- add new `onTouchEndOrOnMouseUp` prop that is called for `touchend` and `mouseup`.
- add [react 18](https://reactjs.org/blog/2022/03/29/react-v18.html) to `peerDependencies`

**Breaking Changes:**
* we have dropped support for `es5` transpiled output
* we target `es2015` for our transpilation now
* `swipeable` utilizes object/array spread & const/let natively
* `preventScrollOnSwipe` - "new" prop. Replaces `preventDefaultTouchmoveEvent`
* same functionality but renamed to be more explicit on its intended use
* **fixed bug** - where toggling this prop did not re-attach event listeners
* **update** - we now **only** change the `passive` event listener option for `touchmove` depending on this prop
* see notes in README for more details [readme#passive-listener](https://github.com/FormidableLabs/react-swipeable#passive-listener)
* Thank you [@stefvhuynh](https://github.com/stefvhuynh)

**Bug fixes:**
* fix bug where directional swiped check allowed `undefined`/falsy values to set `cancelablePageSwipe`
* Thank you [@bhj](https://github.com/bhj) for the [comment](https://github.com/FormidableLabs/react-swipeable/pull/240#issuecomment-1014980025)
* fix bug when both `trackTouch` and `trackMouse` were present that triggered an erroneous swipe when the user clicked outside and above the swipeable area
* See [issue 304](https://github.com/FormidableLabs/react-swipeable/issues/304) for details
* Thank you [@Sacret](https://github.com/Sacret)

**Infrastructure:**
* post `size-limit report` to PRs with bundle diff sizes
* utilize `rollup` for build & output
* remove dependency on `microbundle`
* remove `interop` injected code - [pull/260](https://github.com/FormidableLabs/react-swipeable/pull/260#discussion_r679541081)
* Thank you [@binoy14](https://github.com/binoy14)
* upgrade lots of dev dependencies
* 🎉 upgrade to `typescript` `v4.6.3`
* export/outputs housekeeping and cleaning (mimicked from `react-redux`)
* removed/renamed exports from `package.json`:
* `browser`, `umd:main`(renamed `dist`), `jsnext:main`(use `module`), `typings`(use `types`)
* moved exports - **old** => **new**
* `"main": "./dist/react-swipeable.js"` => `"main": "./lib/index.js"`
* `"module": "./dist/react-swipeable.module.js"` => `"module": "es/index.js"`
* `"types": "./dist/index.d.ts"` => `"types": "./es/index.d.ts"`

# v6.2.2
* add react v18 to `peerDependencies`

Expand Down
18 changes: 13 additions & 5 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,15 @@ $ yarn run prettier
$ yarn run format
```

If you see this error:
```
[warn] Code style issues found in the above file(s). Forgot to run Prettier?
```
Then run the formatter:
```sh
$ yarn run format
```

## Project Maintainers
### Releasing a new version
1. Publish to npm
Expand Down Expand Up @@ -112,8 +121,8 @@ Make sure you've already completed the above steps for `Update version in the ex

(Optional) Validate examples build locally
```sh
# From root run build:examples
$ yarn build:examples
# From root - build the examples
$ yarn examples:build

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

```sh
# From the root run build:publish:examples
# This will build and publish the examples app to github pages
$ yarn build:publish:examples
# From root - build and publish the examples app to github pages
$ yarn examples:build:publish
```
6 changes: 3 additions & 3 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
The MIT License (MIT)

Copyright (C) 2014-2020 Josh Perez
Copyright (C) 2014-2020 Brian Emil Hartz
Copyright (C) 2020 Formidable Labs, Inc.
Copyright (C) 2014-2022 Josh Perez
Copyright (C) 2014-2022 Brian Emil Hartz
Copyright (C) 2022 Formidable Labs, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
119 changes: 80 additions & 39 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ Spread `handlers` onto the element you wish to track swipes on.
onSwipeStart, // Start of swipe (SwipeEventData) => void *see details*
onSwiping, // During swiping (SwipeEventData) => void
onTap, // After a tap ({ event }) => void

// Pass through callbacks, event provided: ({ event }) => void
onTouchStartOrOnMouseDown, // Called for `touchstart` and `mousedown`
onTouchEndOrOnMouseUp, // Called for `touchend` and `mouseup`
}
```

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

```js
{
delta: 10, // min distance(px) before a swipe starts. *See Notes*
preventDefaultTouchmoveEvent: false, // call e.preventDefault *See Details*
trackTouch: true, // track touch input
trackMouse: false, // track mouse input
rotationAngle: 0, // set a rotation angle
delta: 10, // min distance(px) before a swipe starts. *See Notes*
preventScrollOnSwipe: false, // prevents scroll during swipe (*See Details*)
trackTouch: true, // track touch input
trackMouse: false, // track mouse input
rotationAngle: 0, // set a rotation angle
swipeDuration: Infinity, // allowable duration of a swipe (ms). *See Notes*
touchEventOptions: { passive: true }, // options for touch listeners (*See Details*)
}
```

#### Delta
#### delta

`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`;

```js
{
delta: { top: 20, bottom: 20 } // top and bottom when ">= 20", left and right default to ">= 10"
delta: { up: 20, down: 20 } // up and down ">= 20", left and right default to ">= 10"
}
```

#### swipeDuration
A swipe lasting more than `swipeDuration`, in milliseconds, will **not** be considered a swipe.
- It will also **not** trigger any callbacks and the swipe event will stop being tracked
- **Defaults** to `Infinity` for backwards compatibility, a sensible duration could be something like `250`
- Feature mimicked from `use-gesture` [swipe.duration](https://use-gesture.netlify.app/docs/options/#swipeduration)

```js
{
swipeDuration: 250 // only swipes under 250ms will trigger callbacks
}
```

#### touchEventOptions

Allows the user to set the options for the touch event listeners( currently only `passive` option ).
- `touchstart`, `touchmove`, and `touchend` event listeners
- **Defaults** to `{ passive: true }`
- 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)
- https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#options
- `preventScrollOnSwipe` option **supersedes** `touchEventOptions.passive` for `touchmove` event listener
- See `preventScrollOnSwipe` for [more details](#preventscrollonswipe-details)

## Swipe Event Data

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

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

### `preventDefaultTouchmoveEvent` details
### `preventScrollOnSwipe` details

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".
This prop prevents scroll during swipe in most cases. Use this to **stop scrolling** in the browser while a user swipes.

Use this to **stop scrolling** in the browser while a user swipes.
- You can additionally try `touch-action` css property, [see below](#how-to-use-touch-action-to-prevent-scrolling)
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).

**NOTE:** `preventScrollOnSwipe` option **supersedes** `touchEventOptions.passive` for the `touchmove` event listener

**Example scenario:**
> 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.

`e.preventDefault()` is only called when:
- `preventDefaultTouchmoveEvent: true`
- `preventScrollOnSwipe: true`
- `trackTouch: true`
- the users current swipe has an associated `onSwiping` or `onSwiped` handler/prop

Example scenario:
> 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.

Please experiment with the [example app](http://formidablelabs.github.io/react-swipeable/) to test `preventDefaultTouchmoveEvent`.
Please experiment with the [example app](http://formidablelabs.github.io/react-swipeable/) to test `preventScrollOnSwipe`.

#### passive listener
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`.
#### passive listener details
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`.

**When `preventDefaultTouchmoveEvent` is:**
- `true` => `el.addEventListener(event, cb, { passive: false })`
- `false` => `el.addEventListener(event, cb, { passive: true })`
**When `preventScrollOnSwipe` is:**
- `true` => `el.addEventListener('touchmove', cb, { passive: false })`
- `false` => `el.addEventListener('touchmove', cb, { passive: true })`

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

We previously had issues with chrome lighthouse performance deducting points for not having passive option set.
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.

### Browser Support
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).

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).
### Version 7 Updates and migration

### Version 6 Updates and migration

If upgrading from v5 or later please refer to the release notes and the [v6 migration doc](./migration.md)

v6 now only exports a hook, `useSwipeable`.

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).
If upgrading from v6 refer to the release notes and the [migration doc](./migration.md).

## FAQs

Expand Down Expand Up @@ -174,21 +197,39 @@ const MyComponent = () => {

### How to use `touch-action` to prevent scrolling?

Sometimes you don't want the `body` of your page to scroll along with the user manipulating or swiping an item.
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.

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.
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.

`touch-action` is a CSS property that sets how an element's region can be manipulated by a touchscreen user.
`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.

#### Static example
```js
const handlers = useSwipeable({
onSwiped: (eventData) => console.log("User Swiped!", evenData),
onSwiped: (eventData) => console.log("User Swiped!", eventData),
...config,
});
return <div {...handlers} style={{ touchAction: 'pan-y' }}> Swipe here </div>;

return <div {...handlers} style={{ touchAction: 'pan-y' }}>Swipe here</div>;
```
This explanation and example borrowed from `use-gesture`'s [wonderful docs](https://use-gesture.netlify.app/docs/extras/#touch-action).

#### Dynamic example
```js
const MySwipeableComponent = props => {
const [stopScroll, setStopScroll] = useState(false);

const handlers = useSwipeable({
onSwipeStart: () => setStopScroll(true),
onSwiped: () => setStopScroll(false)
});

return <div {...handlers} style={{ touchAction: stopScroll ? 'none' : 'auto' }}>Swipe here</div>;
};
```

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.

## License

[MIT]((./LICENSE))
Expand Down
9 changes: 8 additions & 1 deletion __tests__/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { MockedSwipeFunctions } from "../useSwipeable.spec";
export type MockedSwipeFunctions = {
onSwiping: jest.Mock;
onSwiped: jest.Mock;
onSwipedLeft: jest.Mock;
onSwipedRight: jest.Mock;
onSwipedUp: jest.Mock;
onSwipedDown: jest.Mock;
};

const expectSwipingDir = (fns: jest.Mock, dir: string) => {
fns.mock.calls.forEach((call) => {
Expand Down
Loading