Skip to content

Instantly share code, notes, and snippets.

@trueadm
Last active July 24, 2019 10:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save trueadm/fbcb249efb07296582f8d980ff2de6fc to your computer and use it in GitHub Desktop.
Save trueadm/fbcb249efb07296582f8d980ff2de6fc to your computer and use it in GitHub Desktop.
// -----------------
// This system replaces this existing Flare event system and its concept of Event Components.
// -----------------
// Here's an example of how we might make a Pressable View:
// PressableView.js
import {usePressResponder} from "react-events/press";
import {useFocusResponder} from "react-events/focus";
import {useHoverResponder} from "react-events/hover";
export default function PressableView(props) {
const pressEvents = {
onPress: props.onPress,
...
};
const focusEvents = {
onFocus: props.onFocus,
...
};
const hoverEvents = {
...
};
const targetRef = useRef(null);
const [pressed] = usePressResponder(targetRef, pressEvents)
const [focused] = useFocusResponder(targetRef, focusEvents)
const [hovered] = useHoverResponder(targetRef, hoverEvents)
const childState = {
focused,
pressed,
hovered
};
const children = props.children;
if (typeof children === 'function') {
return <div ref={targetRef}>{children(childState)}</div>;
}
return <div ref={targetRef}>{props.children}</div>
}
// -----------------
// Here is how we can consume our PressableView.
// -----------------
// App.js
import PressableView from 'PressableView';
export default function App() {
function handlePress() {
console.log('You pressed me!');
}
return (
<PressableView onPress={handlePress}>
{({pressed}) => (
<Text>{pressed ? 'Nice press!' : 'Press me!'}</Text>
)}
</PressableView>
);
}
// -----------------
// When events are fired from Flare responders, such as `press` or `focuswithin`,
// we can listen for these events (defined in the responder).
// -----------------
// Using `useListener` or `createListener`, this can be done in the tree:
const PressListener = React.createListener(PressResponder);
export default function App() {
function handlePressOuter() {
console.log('You pressed outer!');
}
function handlePressInner() {
console.log('You pressed inner!');
}
return (
<PressListener onPress={handlePressOuter}>
<PressableView onPress={handlePressInner}>
...
</PressableView>
</PressListener>
);
}
// -----------------
// The important thing to note is that the listener components will only
// capture events that have been defined as bubbling:
// -----------------
// Inside Press.js
context.dispatchEvent(eventObject, listener, eventPriority, bubbles);
// So this can allow certain non-bubbling events to not traverse up the tree.
// For example `focus`, `blur` and `scroll`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment