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

feat(native): implement native EventTarget methods #3252

Merged
merged 8 commits into from
Aug 10, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
60 changes: 60 additions & 0 deletions packages/fiber/src/core/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -531,3 +531,63 @@ export function createEvents(store: UseBoundStore<RootState>) {

return { handlePointer }
}

const DOM_EVENTS = {
onClick: ['click', false],
onContextMenu: ['contextmenu', false],
onDoubleClick: ['dblclick', false],
onWheel: ['wheel', true],
onPointerDown: ['pointerdown', true],
onPointerUp: ['pointerup', true],
onPointerLeave: ['pointerleave', true],
onPointerMove: ['pointermove', true],
onPointerCancel: ['pointercancel', true],
onLostPointerCapture: ['lostpointercapture', true],
} as const

/** Default R3F event manager for web */
export function createPointerEvents(store: UseBoundStore<RootState>): EventManager<HTMLElement> {
const { handlePointer } = createEvents(store)

return {
priority: 1,
enabled: true,
compute(event: DomEvent, state: RootState, previous?: RootState) {
// https://github.com/pmndrs/react-three-fiber/pull/782
// Events trigger outside of canvas when moved, use offsetX/Y by default and allow overrides
state.pointer.set((event.offsetX / state.size.width) * 2 - 1, -(event.offsetY / state.size.height) * 2 + 1)
state.raycaster.setFromCamera(state.pointer, state.camera)
},

connected: undefined,
handlers: Object.keys(DOM_EVENTS).reduce(
(acc, key) => ({ ...acc, [key]: handlePointer(key) }),
{},
) as unknown as Events,
update: () => {
const { events, internal } = store.getState()
if (internal.lastEvent?.current && events.handlers) events.handlers.onPointerMove(internal.lastEvent.current)
},
connect: (target: HTMLElement) => {
const { set, events } = store.getState()
events.disconnect?.()
set((state) => ({ events: { ...state.events, connected: target } }))
Object.entries(events.handlers ?? []).forEach(([name, event]) => {
const [eventName, passive] = DOM_EVENTS[name as keyof typeof DOM_EVENTS]
target.addEventListener(eventName, event, { passive })
})
},
disconnect: () => {
const { set, events } = store.getState()
if (events.connected) {
Object.entries(events.handlers ?? []).forEach(([name, event]) => {
if (events && events.connected instanceof HTMLElement) {
const [eventName] = DOM_EVENTS[name as keyof typeof DOM_EVENTS]
events.connected.removeEventListener(eventName, event)
}
})
set((state) => ({ events: { ...state.events, connected: undefined } }))
}
},
}
}
3 changes: 1 addition & 2 deletions packages/fiber/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ export type {
RootState,
} from './core/store'
export type { ThreeEvent, Events, EventManager, ComputeFunction } from './core/events'
export { createEvents } from './core/events'
export { createEvents, createPointerEvents as events } from './core/events'
export type { ObjectMap, Camera } from './core/utils'
export * from './web/Canvas'
export { createPointerEvents as events } from './web/events'
export type { GlobalRenderCallback, GlobalEffectType } from './core/loop'
export * from './core'
3 changes: 1 addition & 2 deletions packages/fiber/src/native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ export type {
RootState,
} from './core/store'
export type { ThreeEvent, Events, EventManager, ComputeFunction } from './core/events'
export { createEvents } from './core/events'
export { createEvents, createPointerEvents as events } from './core/events'
export type { ObjectMap, Camera } from './core/utils'
export * from './native/Canvas'
export { createTouchEvents as events } from './native/events'
CodyJasonBennett marked this conversation as resolved.
Show resolved Hide resolved
export type { GlobalRenderCallback, GlobalEffectType } from './core/loop'
export * from './core'

Expand Down
120 changes: 100 additions & 20 deletions packages/fiber/src/native/Canvas.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
import * as React from 'react'
import * as THREE from 'three'
import { View, ViewProps, ViewStyle, LayoutChangeEvent, StyleSheet, PixelRatio } from 'react-native'
import {
View,
type ViewProps,
type ViewStyle,
type GestureResponderHandlers,
type GestureResponderEvent,
PanResponder,
type LayoutChangeEvent,
StyleSheet,
PixelRatio,
} from 'react-native'
import { ExpoWebGLRenderingContext, GLView } from 'expo-gl'
import { useContextBridge, FiberProvider } from 'its-fine'
import { SetBlock, Block, ErrorBoundary, useMutableCallback } from '../core/utils'
import { extend, createRoot, unmountComponentAtNode, RenderProps, ReconcilerRoot } from '../core'
import { createTouchEvents } from './events'
import { createPointerEvents } from '../core/events'
import { RootState, Size } from '../core/store'

export interface CanvasProps extends Omit<RenderProps<HTMLCanvasElement>, 'size' | 'dpr'>, ViewProps {
Expand All @@ -25,7 +35,7 @@ const CanvasImpl = /*#__PURE__*/ React.forwardRef<View, Props>(
children,
style,
gl,
events = createTouchEvents,
events = createPointerEvents,
shadows,
linear,
flat,
Expand All @@ -51,7 +61,7 @@ const CanvasImpl = /*#__PURE__*/ React.forwardRef<View, Props>(

const [{ width, height, top, left }, setSize] = React.useState<Size>({ width: 0, height: 0, top: 0, left: 0 })
const [canvas, setCanvas] = React.useState<HTMLCanvasElement | null>(null)
const [bind, setBind] = React.useState<any>()
const [bind, setBind] = React.useState<GestureResponderHandlers>()
React.useImperativeHandle(forwardedRef, () => viewRef.current)

const handlePointerMissed = useMutableCallback(onPointerMissed)
Expand All @@ -76,21 +86,87 @@ const CanvasImpl = /*#__PURE__*/ React.forwardRef<View, Props>(
// Called on context create or swap
// https://github.com/pmndrs/react-three-fiber/pull/2297
const onContextCreate = React.useCallback((context: ExpoWebGLRenderingContext) => {
const canvasShim = {
const listeners = new Map<string, EventListener[]>()

const canvas = {
style: {},
width: context.drawingBufferWidth,
height: context.drawingBufferHeight,
style: {},
addEventListener: (() => {}) as any,
removeEventListener: (() => {}) as any,
clientWidth: context.drawingBufferWidth,
clientHeight: context.drawingBufferHeight,
getContext: ((_: any, { antialias = false }) => {
getContext: (_: any, { antialias = false }) => {
setAntialias(antialias)
return context
}) as any,
} as HTMLCanvasElement
},
addEventListener(type: string, listener: EventListener) {
let callbacks = listeners.get(type)
if (!callbacks) {
callbacks = []
listeners.set(type, callbacks)
}

root.current = createRoot<HTMLCanvasElement>(canvasShim)
setCanvas(canvasShim)
callbacks.push(listener)
},
removeEventListener(type: string, listener: EventListener) {
const callbacks = listeners.get(type)
if (callbacks) {
const index = callbacks.indexOf(listener)
if (index !== -1) callbacks.splice(index, 1)
}
},
dispatchEvent(event: Event) {
Object.assign(event, { target: this })

const callbacks = listeners.get(event.type)
if (callbacks) {
for (const callback of callbacks) {
callback(event)
}
}
},
releasePointerCapture() {
// TODO
},
} as unknown as HTMLCanvasElement

// TODO: this is wrong but necessary to trick controls
// @ts-ignore
canvas.ownerDocument = canvas

root.current = createRoot<HTMLCanvasElement>(canvas)
setCanvas(canvas)

function handleTouch(gestureEvent: GestureResponderEvent, type: string): true {
gestureEvent.persist()

canvas.dispatchEvent(
Object.assign(gestureEvent.nativeEvent, {
type,
offsetX: gestureEvent.nativeEvent.locationX,
offsetY: gestureEvent.nativeEvent.locationY,
}) as unknown as Event,
)

return true
}

const responder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onMoveShouldSetPanResponder: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderTerminationRequest: () => true,
onStartShouldSetPanResponderCapture: (e) => handleTouch(e, 'pointercapture'),
onPanResponderStart: (e) => handleTouch(e, 'pointerdown'),
onPanResponderMove: (e) => handleTouch(e, 'pointermove'),
onPanResponderEnd: (e, state) => {
handleTouch(e, 'pointerup')
if (Math.hypot(state.dx, state.dy) < 20) handleTouch(e, 'click')
},
onPanResponderRelease: (e) => handleTouch(e, 'pointerleave'),
onPanResponderTerminate: (e) => handleTouch(e, 'lostpointercapture'),
onPanResponderReject: (e) => handleTouch(e, 'lostpointercapture'),
})
setBind(responder.panHandlers)
}, [])

if (root.current && width > 0 && height > 0) {
Expand All @@ -115,9 +191,6 @@ const CanvasImpl = /*#__PURE__*/ React.forwardRef<View, Props>(
onPointerMissed: (...args) => handlePointerMissed.current?.(...args),
// Overwrite onCreated to apply RN bindings
onCreated: (state: RootState) => {
// Bind events after creation
setBind(state.events.handlers)

// Bind render to RN bridge
const context = state.gl.getContext() as ExpoWebGLRenderingContext
const renderFrame = state.gl.render.bind(state.gl)
Expand Down Expand Up @@ -145,10 +218,17 @@ const CanvasImpl = /*#__PURE__*/ React.forwardRef<View, Props>(
}, [canvas])

return (
<View {...props} ref={viewRef} onLayout={onLayout} style={{ flex: 1, ...style }} {...bind}>
{width > 0 && (
<GLView msaaSamples={antialias ? 4 : 0} onContextCreate={onContextCreate} style={StyleSheet.absoluteFill} />
)}
<View ref={viewRef} onLayout={onLayout} style={{ flex: 1, ...style }}>
<View {...props} style={{ flex: 1 }}>
{width > 0 && (
<GLView
{...bind}
msaaSamples={antialias ? 4 : 0}
onContextCreate={onContextCreate}
style={StyleSheet.absoluteFill}
/>
)}
</View>
</View>
)
},
Expand Down
71 changes: 0 additions & 71 deletions packages/fiber/src/native/events.ts

This file was deleted.

3 changes: 1 addition & 2 deletions packages/fiber/src/web/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import type { Options as ResizeOptions } from 'react-use-measure'
import { useContextBridge, FiberProvider } from 'its-fine'
import { isRef, SetBlock, Block, ErrorBoundary, useMutableCallback, useIsomorphicLayoutEffect } from '../core/utils'
import { ReconcilerRoot, extend, createRoot, unmountComponentAtNode, RenderProps } from '../core'
import { createPointerEvents } from './events'
import { DomEvent } from '../core/events'
import { createPointerEvents, DomEvent } from '../core/events'

export interface CanvasProps
extends Omit<RenderProps<HTMLCanvasElement>, 'size'>,
Expand Down
Loading