enable dragging of element in a ScrollView after long press - ios

I have implemented drag n drop list with panResponder and ScrollView. I want to be able to scroll the list even when I touch the item. Problem is that the item moves when I do the gesture to scroll. Of course I also want to be able to move the item but now it has the same gesture as scroll. I want to overcome it by enabling dragging the element only after it was long pressed (1,5 sec). How to implement it? I thought to use Touchable as an element with onPressIn / onPressOut just like described here: http://browniefed.com/blog/react-native-press-and-hold-button-actions/
and somehow to enable panResponder after the time period, but I don't know how to enable it programmatically.
Right now this is my code for element in the list:
class AccountItem extends Component {
constructor(props) {
super(props);
this.state = {
pan: new Animated.ValueXY(),
zIndex: 0,
}
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderGrant: (e, gestureState) => {
this.setState({ zIndex: 100 });
this.props.disableScroll();
},
onPanResponderMove: Animated.event([null, {
dx: this.state.pan.x,
dy: this.state.pan.y,
}]),
onPanResponderRelease: (e, gesture) => {
this.props.submitNewPositions();
Animated.spring(
this.state.pan,
{toValue:{ x:0, y:0 }}
).start();
this.setState({ zIndex: 0 });
this.props.enableScroll();
}
})
}
meassureMyComponent = (event) => {
const { setElementPosition } = this.props;
let posY = event.nativeEvent.layout.y;
setElementPosition(posY);
}
render() {
const {name, index, onChangeText, onRemoveAccount} = this.props;
return (
<Animated.View
style={[this.state.pan.getLayout(), styles.container, {zIndex: this.state.zIndex}]}
{...this.panResponder.panHandlers}
onLayout={this.meassureMyComponent}
>
some other components...
</Animated.View>
)
}
}
export default AccountItem;

I met the same issue with you. My solution is to define 2 different panResponder handler for onLongPress and normal behaviour.
_onLongPressPanResponder(){
return PanResponder.create({
onPanResponderTerminationRequest: () => false,
onStartShouldSetPanResponderCapture: () => true,
onPanResponderMove: Animated.event([
null, {dx: this.state.pan.x, dy: this.state.pan.y},
]),
onPanResponderRelease: (e, {vx, vy}) => {
this.state.pan.flattenOffset()
Animated.spring(this.state.pan, { //This will make the draggable card back to its original position
toValue: 0
}).start();
this.setState({panResponder: undefined}) //Clear panResponder when user release on long press
}
})
}
_normalPanResponder(){
return PanResponder.create({
onPanResponderTerminationRequest: () => false,
onStartShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (e, gestureState) => {
this.state.pan.setOffset({x: this.state.pan.x._value, y: this.state.pan.y._value});
this.state.pan.setValue({x: 0, y: 0})
this.longPressTimer=setTimeout(this._onLongPress, 400) // this is where you trigger the onlongpress panResponder handler
},
onPanResponderRelease: (e, {vx, vy}) => {
if (!this.state.panResponder) {
clearTimeout(this.longPressTimer); // clean the timeout handler
}
}
})
}
Define your _onLongPress function:
_onLongPress(){
// you can add some animation effect here as wll
this.setState({panResponder: this._onLongPressPanResponder()})
}
Define your constructor:
constructor(props){
super(props)
this.state = {
pan: new Animated.ValueXY()
};
this._onLongPress = this._onLongPress.bind(this)
this._onLongPressPanResponder = this._onLongPressPanResponder.bind(this)
this._normalPanResponder = this._normalPanResponder.bind(this)
this.longPressTimer = null
}
Finally, before you render, you should switch to different panResponder handlers according to the state:
let panHandlers = {}
if(this.state.panResponder){
panHandlers = this.state.panResponder.panHandlers
}else{
panHandlers = this._normalPanResponder().panHandlers
}
Then attach the panHandlers to your view {...panHandlers}
You can even change the css for different panHandlers to show different effect.

If your only issue is that ScrollView scrolls when moving item, then I'll suggest simply to disable scrolling of parent for movement period.
Like:
//component with ScrollView:
...
constructor() {
super()
this.state = {scrolling: true}
this.enableScroll = this.enableScroll.bind(this)
this.disableScroll = this.disableScroll.bind(this)
}
// inject those methods into Drag&Drop item as props:
enableScroll() {
this.setState({scrolling: true})
}
disableScroll() {
this.setState({scrolling: false})
}
...
<ScrollView scrollEnabled={this.state.scrolling} ... />
...
//component with drag&drop item:
...
onPanResponderGrant() {
...
this.props.disableScroll()
...
}
onPanResponderRelease() {
this.props.enableScroll()
}
Make sure to cover all cases of release gesture (like onPanResponderTerminate etc.)

You can do this using a ref value to store if dragging should be enabled, and this can be accessed within the PanResponder. Using a ref ensures that the value won't be stale w.r.t the PanResponder; that is, the reference to the ref will be fixed at the initialisation of the PanResponder, but the underlying .current value can change. (This is unlike a useState value, which would be stale past the initialisation of the PanResponder.)
e.g.
const dragEnabledRef = useRef(false);
const pan = useRef(
PanResponder.create({
onStartShouldSetPanResponder: () => dragEnabledRef.current,
onStartShouldSetPanResponderCapture: () => dragEnabledRef.current,
onMoveShouldSetPanResponder: () => dragEnabledRef.current,
onMoveShouldSetPanResponderCapture: () => dragEnabledRef.current,
...
onPanResponderRelease: () => {
...
dragEnabledRef.current = false
}
})
).current
return (
<Pressable onLongPress={() => {
dragEnabledRef.current = true
}}>
{children}
</Pressable>
);

Related

Konva onDragMove and onDragEnd not updating position?

I'm trying to onDragMove to manually update an elements position. The shape itself is dragging around, and the is updating the objects, but it is not being rendered?
Same with onDragEnd. Both are updating the array of shapes correctly, but it is not appearing on the render, even though
import React, { useState, useEffect } from "react";
import { Stage, Layer, Rect } from "react-konva";
import "./styles.css";
export default function App() {
const [objects, setObject] = useState([{ id: "rect1", x: 50, y: 50 }]);
// Function
const updatePosition = (id) => {
let update = objects.map((entry) => {
if (entry.id !== id) return entry;
else return { ...entry, x: 100, y: 0 };
});
setObject(update);
};
// We can see the object is updated with the new coords
useEffect(() => {
console.log(objects);
});
return (
<main style={{ background: "lightgrey" }}>
<Stage width={800} height={800}>
<Layer>
{objects.map((object) => {
// This shows an updated X value correclty
console.log(object.x);
// It doesn't render the new x position at all
return (
<Rect
key={object.id}
fill={"green"}
width={200}
height={300}
x={object.x}
y={object.y}
draggable
onDragMove={() => updatePosition(object.id)}
onDragEnd={() => updatePosition(object.id)}
/>
);
})}
</Layer>
</Stage>
</main>
);
}
https://codesandbox.io/s/priceless-dust-cjr6z?file=/src/App.js:0-1323
From your demo, I see that you are setting the same {x, y} position to the shape:
const updatePosition = (id) => {
let update = objects.map((entry) => {
if (entry.id !== id) return entry;
else return { ...entry, x: 100, y: 0 };
});
setObject(update);
};
By default react-konva will set 100, 0 position just once. On the next render calls, properties for <Rect /> element are not changing. react-konva will update only CHANGED from previous render properties.
If you want to strictly set the last properties, you should use strict mode

How to navigate page immediately after rendering animation?

I currently have a loading screen that renders an animation. After doing so I would like it to immediately, based on firebase.auth().onAuthStateChange, navigate the user to a specific page.
I have already implemented the animation and part of the logic. I just need the ability to navigate immediately after the first render/animation has completed.
class LoadingScreen extends Component {
state = {
opacity: new Animated.Value(0),
}
onLoad = () => {
Animated.timing(this.state.opacity, {
toValue: 1,
duration: 1500,
delay: 1000,
useNativeDriver: true,
}).start();
}
render() {
return (
<Animated.Image
onLoad={this.onLoad}
{...this.props}
style={[
{
opacity: this.state.opacity,
transform: [
{
scale: this.state.opacity.interpolate({
inputRange: [0, 1],
outputRange: [0.85, 1],
})
},
],
},
this.props.style,
]}
/>
);
}
}
export default class App extends Component{
render()
{
return (
<View style={styles.container}>
<LoadingScreen
style={styles.image}
source= {require('../assets/images/logo.png')}
/>
</View>
)
}
checkIfLoggedIn = () => {
firebase.auth().onAuthStateChanged((user)=>
{
if(user)
{
this.props.navigation.navigate('Login');
}
else
{
this.props.navigation.navigate('Signup');
}
})
}
}
To do something on the end of the animation, you should add a callback to the start() function, so:
Pass your checkIfLoggedIn function as a prop to LoadingScreen component
<LoadingScreen
style={styles.image}
source= {require('../assets/images/logo.png')}
onAnimationEnd={this.checkIfLoggedIn}
/>
Use the function passed as a prop for the animation callback
onLoad = () => {
Animated.timing(this.state.opacity, {
toValue: 1,
duration: 1500,
delay: 1000,
useNativeDriver: true,
}).start(() => this.props.onAnimationEnd());
}

How to send search text to findInPage in Electron

I try using contents.findInPage.
I have code in index.js:
const { webContents } = require('electron')
webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) webContents.stopFindInPage('clearSelection')
})
const requestId = webContents.findInPage('api')
console.log(requestId)
And code in component:
searchText(value){
this.query = value;
if (this.query.length > 0) {
ipcRenderer.send('api', this.query);
}
}
I wrote this code on the example of this answer.
But function find not work. I do not understand how I can send the text to be searched and the word to be searched.
How I can use function findInPage ?
sorry my answer to the other question wasn't clear enough (it was 2 years ago! I don't remember it that well but I'll give it a shot)
This is the documentation for webcontents and IPCMain
Here's what I have in my main.development.js (globals for the mainWindow and ipc communication):
mainWindow.on('focus', () => {
globalShortcut.register('CmdorCtrl+F', () => {
mainWindow.webContents.send('find_request', '');
});
});
mainWindow.webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) {
mainWindow.webContents.stopFindInPage('keepSelection');
}
});
ipcMain.on('search-text', (event, arg) => {
mainWindow.webContents.findInPage(arg);
});
mainWindow.on('blur', () => {
globalShortcut.unregister('CmdorCtrl+F');
});
Then I made an ipc listener for CmdorCtrl+F:
ipcRenderer.on('find_request', () => {
const modalbox = document.getElementById('modalbox');
if (modalbox.style.display === 'block') {
modalbox.style.display = 'none';
} else {
modalbox.style.display = 'block';
}
});
Then I made a modal searchbox:
const searchBox = (
<div
id="modalbox"
style={{ display: 'none', position: 'fixed', zIndex: 1 }}
><input type="text" onChange={Calls.searchPage} />
</div>);
The onchange sends the input text to the ipc listener:
static searchPage(event) {
ipcRenderer.send('search-text', event.target.value);
}
I hope this is enough for you to get it fixed :)

React Native - panResponder animation not working on iOS

I use a panResponder to create draggable view in my app. It's working fine on android but on iOS, the drag animation stops after moving la little bit.
Vidéo here
Here is my code :
export default class Draggable extends React.Component {
constructor(props) {
super(props);
const { pressDragRelease, pressDragStart, reverse, initPosition } = props;
this.state = {
pan: new Animated.ValueXY({
x: initPosition.dragX,
y: initPosition.dragY
}),
_value: { x: initPosition.dragX, y: initPosition.dragY }
};
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: (evt, gestureState) => true,
onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
onMoveShouldSetPanResponder: (evt, gestureState) => true,
onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
onPanResponderGrant: (gesture) => {
console.log("inside panResponder grant");
if (reverse === false) {
this.state.pan.setOffset({x: this.state._value.x,y: this.state._value.y});
this.state.pan.setValue({ x: 0, y: 0 });
} else {
this.state.pan.setValue({ x: gesture.dx, y: gesture.dy });
}
},
onPanResponderMove: Animated.event([
null,
{
dx: this.state.pan.x,
dy: this.state.pan.y
}
]),
//Called on android at the end
onPanResponderRelease: () => {
if (pressDragRelease) {
pressDragRelease({ x: this.state._value.x, y: this.state._value.y });
}
if (reverse === false) this.state.pan.flattenOffset();
else this.reversePosition();
},
//Called on ios at the end
onPanResponderTerminate: () => {
if (pressDragRelease) {
pressDragRelease({ x: this.state._value.x, y: this.state._value.y
});
}
if(reverse === false) {
this.state.pan.flattenOffset();
} else {
this.reversePosition();
}
}
});
}
componentWillMount() {
if (this.props.reverse === false)
this.state.pan.addListener(c => this.setState({ _value: c }));
}
componentWillUnmount() {
this.state.pan.removeAllListeners();
}
reversePosition = () => {
const { initPosition } = this.props;
Animated.spring(this.state.pan, {
toValue: { x: initPosition.dragX, y: initPosition.dragY }
}).start();
};
render() {
return (
<Animated.View
{...this.panResponder.panHandlers}
style={[this.state.pan.getLayout()]}
>
{this.props.children}
</Animated.View>
);
}
}
I'm using :
"react-native": "0.57.7"
I tried lots of things related to panResponder, as it works fine on android I guest it's an issue of handler or of the Animated.event in onPanResponderMove handler ?
Any help appreciated, I'm struggling on it for several days ! :)
Also ran into this issue.
Deleted my node modules and pods with a reinstall which was able to resolve it.
I know in the past react-navigation conflicted.
https://github.com/react-navigation/react-navigation/issues/5497
Actually ran into this while using a slider library which was built using panResponder.

React Native multiple panresponders

With this code how would I add a second or multiple panresponders that can be moved independently of each other? If I use the same panresponder instance and code they move together as one. I want to know how to have several independently draggable panresponders.
'use strict';
var React = require('react-native');
var {
PanResponder,
StyleSheet,
View,
processColor,
} = React;
var CIRCLE_SIZE = 80;
var CIRCLE_COLOR = 'blue';
var CIRCLE_HIGHLIGHT_COLOR = 'green';
var PanResponderExample = React.createClass({
statics: {
title: 'PanResponder Sample',
description: 'Shows the use of PanResponder to provide basic gesture handling.',
},
_panResponder: {},
_previousLeft: 0,
_previousTop: 0,
_circleStyles: {},
circle: (null : ?{ setNativeProps(props: Object): void }),
componentWillMount: function() {
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder,
onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
onPanResponderGrant: this._handlePanResponderGrant,
onPanResponderMove: this._handlePanResponderMove,
onPanResponderRelease: this._handlePanResponderEnd,
onPanResponderTerminate: this._handlePanResponderEnd,
});
this._previousLeft = 20;
this._previousTop = 84;
this._circleStyles = {
style: {
left: this._previousLeft,
top: this._previousTop
}
};
},
componentDidMount: function() {
this._updatePosition();
},
render: function() {
return (
<View
style={styles.container}>
<View
ref={(circle) => {
this.circle = circle;
}}
style={styles.circle}
{...this._panResponder.panHandlers}
/>
</View>
);
},
_highlight: function() {
const circle = this.circle;
circle && circle.setNativeProps({
style: {
backgroundColor: processColor(CIRCLE_HIGHLIGHT_COLOR)
}
});
},
_unHighlight: function() {
const circle = this.circle;
circle && circle.setNativeProps({
style: {
backgroundColor: processColor(CIRCLE_COLOR)
}
});
},
_updatePosition: function() {
this.circle && this.circle.setNativeProps(this._circleStyles);
},
_handleStartShouldSetPanResponder: function(e: Object, gestureState: Object): boolean {
// Should we become active when the user presses down on the circle?
return true;
},
_handleMoveShouldSetPanResponder: function(e: Object, gestureState: Object): boolean {
// Should we become active when the user moves a touch over the circle?
return true;
},
_handlePanResponderGrant: function(e: Object, gestureState: Object) {
this._highlight();
},
_handlePanResponderMove: function(e: Object, gestureState: Object) {
this._circleStyles.style.left = this._previousLeft + gestureState.dx;
this._circleStyles.style.top = this._previousTop + gestureState.dy;
this._updatePosition();
},
_handlePanResponderEnd: function(e: Object, gestureState: Object) {
this._unHighlight();
this._previousLeft += gestureState.dx;
this._previousTop += gestureState.dy;
},
});
var styles = StyleSheet.create({
circle: {
width: CIRCLE_SIZE,
height: CIRCLE_SIZE,
borderRadius: CIRCLE_SIZE / 2,
backgroundColor: CIRCLE_COLOR,
position: 'absolute',
left: 0,
top: 0,
},
container: {
flex: 1,
paddingTop: 64,
},
});
module.exports = PanResponderExample;
You can use an array of PanResponders, created like so:
this._panResponders = yourObjectsArray.map((_, index) => (
PanResponder.create({
onMoveShouldSetPanResponder: () => true,
...
})
));
yourObjectsArray is an array that you use for creating as many panResponders as you want, I imagine each object in that array will correspond to a data instance of whatever data structure you use to create the moveable Views.
Then to actually use it in your View:
render: function() {
return yourObjectsArray.map((_, index) => (
<View
style={styles.container}>
<View
... some stuff here ...
{...this._panResponders[index].panHandlers}
/>
</View>
)
};

Resources