tldraw/packages/editor/src/lib/hooks/useCanvasEvents.ts
Mime Čuvalo b4c1f606e1
focus: rework and untangle existing focus management logic in the sdk (#3718)
Focus management is really scattered across the codebase. There's sort
of a battle between different code paths to make the focus the correct
desired state. It seemed to grow like a knot and once I started pulling
on one thread to see if it was still needed you could see underneath
that it was accounting for another thing underneath that perhaps wasn't
needed.

The impetus for this PR came but especially during the text label
rework, now that it's much more easy to jump around from textfield to
textfield. It became apparent that we were playing whack-a-mole trying
to preserve the right focus conditions (especially on iOS, ugh).

This tries to remove as many hacks as possible, and bring together in
place the focus logic (and in the darkness, bind them).

## Places affected
- [x] `useEditableText`: was able to remove a bunch of the focus logic
here. In addition, it doesn't look like we need to save the selection
range anymore.
- lingering footgun that needed to be fixed anyway: if there are two
labels in the same shape, because we were just checking `editingShapeId
=== id`, the two text labels would have just fought each other for
control
- [x] `useFocusEvents`: nixed and refactored — we listen to the store in
`FocusManager` and then take care of autoFocus there
- [x] `useSafariFocusOutFix`: nixed. not necessary anymore because we're
not trying to refocus when blurring in `useEditableText`. original PR
for reference: https://github.com/tldraw/brivate/pull/79
- [x] `defaultSideEffects`: moved logic to `FocusManager`
- [x] `PointingShape` focus for `startTranslating`, decided to leave
this alone actually.
- [x] `TldrawUIButton`: it doesn't look like this focus bug fix is
needed anymore, original PR for reference:
https://github.com/tldraw/tldraw/pull/2630
- [x] `useDocumentEvents`: left alone its manual focus after the Escape
key is hit
- [x] `FrameHeading`: double focus/select doesn't seem necessary anymore
- [x] `useCanvasEvents`: `onPointerDown` focus logic never happened b/c
in `Editor.ts` we `clearedMenus` on pointer down
- [x] `onTouchStart`: looks like `document.body.click()` is not
necessary anymore

## Future Changes
- [ ] a11y: work on having an accessebility focus ring
- [ ] Page visibility API:
(https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API)
events when tab is back in focus vs. background, different kind of focus
- [ ] Reexamine places we manually dispatch `pointer_down` events to see
if they're necessary.
- [ ] Minor: get rid of `useContainer` maybe? Is it really necessary to
have this hook? you can just do `useEditor` → `editor.getContainer()`,
feels superfluous.

## Methodology
Looked for places where we do:
- `body.click()`
- places we do `container.focus()`
- places we do `container.blur()`
- places we do `editor.updateInstanceState({ isFocused })`
- places we do `autofocus`
- searched for `document.activeElement`

### Change Type

<!--  Please select a 'Scope' label ️ -->

- [x] `sdk` — Changes the tldraw SDK
- [ ] `dotcom` — Changes the tldraw.com web app
- [ ] `docs` — Changes to the documentation, examples, or templates.
- [ ] `vs code` — Changes to the vscode plugin
- [ ] `internal` — Does not affect user-facing stuff

<!--  Please select a 'Type' label ️ -->

- [ ] `bugfix` — Bug fix
- [ ] `feature` — New feature
- [x] `improvement` — Improving existing features
- [ ] `chore` — Updating dependencies, other boring stuff
- [ ] `galaxy brain` — Architectural changes
- [ ] `tests` — Changes to any test code
- [ ] `tools` — Changes to infrastructure, CI, internal scripts,
debugging tools, etc.
- [ ] `dunno` — I don't know


### Test Plan

- [x] run test-focus.spec.ts
- [x] check MultipleExample
- [x] check EditorFocusExample
- [x] check autoFocus
- [x] check style panel usage and focus events in general
- [x] check text editing focus, lots of different devices,
mobile/desktop

### Release Notes

- Focus: rework and untangle existing focus management logic in the SDK
2024-05-17 08:53:57 +00:00

152 lines
3.8 KiB
TypeScript

import React, { useMemo } from 'react'
import { RIGHT_MOUSE_BUTTON } from '../constants'
import {
preventDefault,
releasePointerCapture,
setPointerCapture,
stopEventPropagation,
} from '../utils/dom'
import { getPointerInfo } from '../utils/getPointerInfo'
import { useEditor } from './useEditor'
export function useCanvasEvents() {
const editor = useEditor()
const events = useMemo(
function canvasEvents() {
// Track the last screen point
let lastX: number, lastY: number
function onPointerDown(e: React.PointerEvent) {
if ((e as any).isKilled) return
if (e.button === RIGHT_MOUSE_BUTTON) {
editor.dispatch({
type: 'pointer',
target: 'canvas',
name: 'right_click',
...getPointerInfo(e),
})
return
}
if (e.button !== 0 && e.button !== 1 && e.button !== 5) return
setPointerCapture(e.currentTarget, e)
editor.dispatch({
type: 'pointer',
target: 'canvas',
name: 'pointer_down',
...getPointerInfo(e),
})
}
function onPointerMove(e: React.PointerEvent) {
if ((e as any).isKilled) return
if (e.clientX === lastX && e.clientY === lastY) return
lastX = e.clientX
lastY = e.clientY
editor.dispatch({
type: 'pointer',
target: 'canvas',
name: 'pointer_move',
...getPointerInfo(e),
})
}
function onPointerUp(e: React.PointerEvent) {
if ((e as any).isKilled) return
if (e.button !== 0 && e.button !== 1 && e.button !== 2 && e.button !== 5) return
lastX = e.clientX
lastY = e.clientY
releasePointerCapture(e.currentTarget, e)
editor.dispatch({
type: 'pointer',
target: 'canvas',
name: 'pointer_up',
...getPointerInfo(e),
})
}
function onPointerEnter(e: React.PointerEvent) {
if ((e as any).isKilled) return
if (editor.getInstanceState().isPenMode && e.pointerType !== 'pen') return
const canHover = e.pointerType === 'mouse' || e.pointerType === 'pen'
editor.updateInstanceState({ isHoveringCanvas: canHover ? true : null })
}
function onPointerLeave(e: React.PointerEvent) {
if ((e as any).isKilled) return
if (editor.getInstanceState().isPenMode && e.pointerType !== 'pen') return
const canHover = e.pointerType === 'mouse' || e.pointerType === 'pen'
editor.updateInstanceState({ isHoveringCanvas: canHover ? false : null })
}
function onTouchStart(e: React.TouchEvent) {
;(e as any).isKilled = true
preventDefault(e)
}
function onTouchEnd(e: React.TouchEvent) {
;(e as any).isKilled = true
// check that e.target is an HTMLElement
if (!(e.target instanceof HTMLElement)) return
if (
e.target.tagName !== 'A' &&
e.target.tagName !== 'TEXTAREA' &&
// When in EditingShape state, we are actually clicking on a 'DIV'
// not A/TEXTAREA element yet. So, to preserve cursor position
// for edit mode on mobile we need to not preventDefault.
// TODO: Find out if we still need this preventDefault in general though.
!(editor.getEditingShape() && e.target.className.includes('tl-text-content'))
) {
preventDefault(e)
}
}
function onDragOver(e: React.DragEvent<Element>) {
preventDefault(e)
}
async function onDrop(e: React.DragEvent<Element>) {
preventDefault(e)
if (!e.dataTransfer?.files?.length) return
const files = Array.from(e.dataTransfer.files)
await editor.putExternalContent({
type: 'files',
files,
point: editor.screenToPage({ x: e.clientX, y: e.clientY }),
ignoreParent: false,
})
}
function onClick(e: React.MouseEvent) {
stopEventPropagation(e)
}
return {
onPointerDown,
onPointerMove,
onPointerUp,
onPointerEnter,
onPointerLeave,
onDragOver,
onDrop,
onTouchStart,
onTouchEnd,
onClick,
}
},
[editor]
)
return events
}