Tldraw/packages/tldraw/src/lib/ui/components/PageMenu/PageMenu.tsx

416 wiersze
12 KiB
TypeScript
Czysty Zwykły widok Historia

tldraw zero - package shuffle (#1710) This PR moves code between our packages so that: - @tldraw/editor is a “core” library with the engine and canvas but no shapes, tools, or other things - @tldraw/tldraw contains everything particular to the experience we’ve built for tldraw At first look, this might seem like a step away from customization and configuration, however I believe it greatly increases the configuration potential of the @tldraw/editor while also providing a more accurate reflection of what configuration options actually exist for @tldraw/tldraw. ## Library changes @tldraw/editor re-exports its dependencies and @tldraw/tldraw re-exports @tldraw/editor. - users of @tldraw/editor WITHOUT @tldraw/tldraw should almost always only import things from @tldraw/editor. - users of @tldraw/tldraw should almost always only import things from @tldraw/tldraw. - @tldraw/polyfills is merged into @tldraw/editor - @tldraw/indices is merged into @tldraw/editor - @tldraw/primitives is merged mostly into @tldraw/editor, partially into @tldraw/tldraw - @tldraw/file-format is merged into @tldraw/tldraw - @tldraw/ui is merged into @tldraw/tldraw Many (many) utils and other code is moved from the editor to tldraw. For example, embeds now are entirely an feature of @tldraw/tldraw. The only big chunk of code left in core is related to arrow handling. ## API Changes The editor can now be used without tldraw's assets. We load them in @tldraw/tldraw instead, so feel free to use whatever fonts or images or whatever that you like with the editor. All tools and shapes (except for the `Group` shape) are moved to @tldraw/tldraw. This includes the `select` tool. You should use the editor with at least one tool, however, so you now also need to send in an `initialState` prop to the Editor / <TldrawEditor> component indicating which state the editor should begin in. The `components` prop now also accepts `SelectionForeground`. The complex selection component that we use for tldraw is moved to @tldraw/tldraw. The default component is quite basic but can easily be replaced via the `components` prop. We pass down our tldraw-flavored SelectionFg via `components`. Likewise with the `Scribble` component: the `DefaultScribble` no longer uses our freehand tech and is a simple path instead. We pass down the tldraw-flavored scribble via `components`. The `ExternalContentManager` (`Editor.externalContentManager`) is removed and replaced with a mapping of types to handlers. - Register new content handlers with `Editor.registerExternalContentHandler`. - Register new asset creation handlers (for files and URLs) with `Editor.registerExternalAssetHandler` ### Change Type - [x] `major` — Breaking change ### Test Plan - [x] Unit Tests - [x] End to end tests ### Release Notes - [@tldraw/editor] lots, wip - [@tldraw/ui] gone, merged to tldraw/tldraw - [@tldraw/polyfills] gone, merged to tldraw/editor - [@tldraw/primitives] gone, merged to tldraw/editor / tldraw/tldraw - [@tldraw/indices] gone, merged to tldraw/editor - [@tldraw/file-format] gone, merged to tldraw/tldraw --------- Co-authored-by: alex <alex@dytry.ch>
2023-07-17 21:22:34 +00:00
import {
MAX_PAGES,
PageRecordType,
TLPageId,
releasePointerCapture,
setPointerCapture,
useEditor,
useValue,
} from '@tldraw/editor'
2023-04-25 11:01:25 +00:00
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useBreakpoint } from '../../hooks/useBreakpoint'
import { useMenuIsOpen } from '../../hooks/useMenuIsOpen'
import { useReadonly } from '../../hooks/useReadonly'
2023-04-25 11:01:25 +00:00
import { useTranslation } from '../../hooks/useTranslation/useTranslation'
import { Button } from '../primitives/Button'
import { Icon } from '../primitives/Icon'
import { Popover, PopoverContent, PopoverTrigger } from '../primitives/Popover'
import { PageItemInput } from './PageItemInput'
import { PageItemSubmenu } from './PageItemSubmenu'
import { onMovePage } from './edit-pages-shared'
export const PageMenu = function PageMenu() {
const editor = useEditor()
2023-04-25 11:01:25 +00:00
const msg = useTranslation()
const breakpoint = useBreakpoint()
const handleOpenChange = useCallback(() => setIsEditing(false), [])
const [isOpen, onOpenChange] = useMenuIsOpen('page-menu', handleOpenChange)
const ITEM_HEIGHT = 36
2023-04-25 11:01:25 +00:00
const rSortableContainer = useRef<HTMLDivElement>(null)
const pages = useValue('pages', () => editor.getPages(), [editor])
const currentPage = useValue('currentPage', () => editor.getCurrentPage(), [editor])
const currentPageId = useValue('currentPageId', () => editor.getCurrentPageId(), [editor])
2023-04-25 11:01:25 +00:00
// When in readonly mode, we don't allow a user to edit the pages
const isReadonlyMode = useReadonly()
2023-04-25 11:01:25 +00:00
// If the user has reached the max page count, we disable the "add page" button
const maxPageCountReached = useValue(
'maxPageCountReached',
() => editor.getPages().length >= MAX_PAGES,
[editor]
)
2023-04-25 11:01:25 +00:00
const isCoarsePointer = useValue(
'isCoarsePointer',
() => editor.getInstanceState().isCoarsePointer,
[editor]
)
2023-04-25 11:01:25 +00:00
// The component has an "editing state" that may be toggled to expose additional controls
const [isEditing, setIsEditing] = useState(false)
const toggleEditing = useCallback(() => {
if (isReadonlyMode) return
setIsEditing((s) => !s)
}, [isReadonlyMode])
const rMutables = useRef({
isPointing: false,
status: 'idle' as 'idle' | 'pointing' | 'dragging',
pointing: null as { id: string; index: number } | null,
startY: 0,
startIndex: 0,
dragIndex: 0,
})
const [sortablePositionItems, setSortablePositionItems] = useState(
Object.fromEntries(
pages.map((page, i) => [page.id, { y: i * ITEM_HEIGHT, offsetY: 0, isSelected: false }])
)
)
// Update the sortable position items when the pages change
useLayoutEffect(() => {
setSortablePositionItems(
Object.fromEntries(
pages.map((page, i) => [page.id, { y: i * ITEM_HEIGHT, offsetY: 0, isSelected: false }])
)
)
}, [ITEM_HEIGHT, pages])
// Scroll the current page into view when the menu opens / when current page changes
useEffect(() => {
if (!isOpen) return
requestAnimationFrame(() => {
const elm = document.querySelector(
[fix] id properties of undefined (#1730) (#1919) This PR fixes id properties of undefined. ```js PageMenu.mjs:89 Uncaught TypeError: Cannot read properties of undefined (reading 'id') at PageMenu2 (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/@tldraw+tldraw@2.0.0-canary.c52ba35ee89f_@types+react-dom@18.2.7_@types+react@18.2.21_react-dom@18.2.0_react@18.2.0/node_modules/@tldraw/tldraw/dist-esm/lib/ui/components/PageMenu/PageMenu.mjs:99:32) at renderWithHooks (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/next@13.4.19_@opentelemetry+api@1.4.1_react-dom@18.2.0_react@18.2.0_sass@1.66.1/node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:10697:18) at updateFunctionComponent (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/next@13.4.19_@opentelemetry+api@1.4.1_react-dom@18.2.0_react@18.2.0_sass@1.66.1/node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:15180:20) ``` ![스크린샷 2023-09-19 오후 6 06 26](https://github.com/tldraw/tldraw/assets/59823089/8161c599-3554-4671-86fb-cf303bf60311) ### Change Type - [x] `patch` — Bug fix [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan - [x] Use google chrome force reload ![hard-refresh-browser-chrome](https://github.com/tldraw/tldraw/assets/59823089/0d0cf030-92b3-48db-bbef-252fc813ea03) - [x] 2\~3 Tldraw pages, 2\~3 peers 1. [tldraw-yjs-example](https://github.com/tldraw/tldraw-yjs-example) quickly reload 2. Apply it to [tldraw-yjs-example](https://github.com/tldraw/tldraw-yjs-example) and then quickly reload 3. Compare the two versions ### Release Notes - Fixed a bug similar #1730
2023-09-19 10:02:01 +00:00
`[data-testid="page-menu-item-${currentPageId}"]`
2023-04-25 11:01:25 +00:00
) as HTMLDivElement
if (elm) {
const container = rSortableContainer.current
if (!container) return
// Scroll into view is slightly borked on iOS Safari
// if top of less than top cuttoff, scroll into view at top
const elmTopPosition = elm.offsetTop
const containerScrollTopPosition = container.scrollTop
if (elmTopPosition < containerScrollTopPosition) {
container.scrollTo({ top: elmTopPosition })
}
// if bottom position is greater than bottom cutoff, scroll into view at bottom
const elmBottomPosition = elmTopPosition + ITEM_HEIGHT
const containerScrollBottomPosition = container.scrollTop + container.offsetHeight
if (elmBottomPosition > containerScrollBottomPosition) {
container.scrollTo({ top: elmBottomPosition - container.offsetHeight })
}
}
})
[fix] id properties of undefined (#1730) (#1919) This PR fixes id properties of undefined. ```js PageMenu.mjs:89 Uncaught TypeError: Cannot read properties of undefined (reading 'id') at PageMenu2 (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/@tldraw+tldraw@2.0.0-canary.c52ba35ee89f_@types+react-dom@18.2.7_@types+react@18.2.21_react-dom@18.2.0_react@18.2.0/node_modules/@tldraw/tldraw/dist-esm/lib/ui/components/PageMenu/PageMenu.mjs:99:32) at renderWithHooks (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/next@13.4.19_@opentelemetry+api@1.4.1_react-dom@18.2.0_react@18.2.0_sass@1.66.1/node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:10697:18) at updateFunctionComponent (webpack-internal:///(app-pages-browser)/./node_modules/.pnpm/next@13.4.19_@opentelemetry+api@1.4.1_react-dom@18.2.0_react@18.2.0_sass@1.66.1/node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:15180:20) ``` ![스크린샷 2023-09-19 오후 6 06 26](https://github.com/tldraw/tldraw/assets/59823089/8161c599-3554-4671-86fb-cf303bf60311) ### Change Type - [x] `patch` — Bug fix [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan - [x] Use google chrome force reload ![hard-refresh-browser-chrome](https://github.com/tldraw/tldraw/assets/59823089/0d0cf030-92b3-48db-bbef-252fc813ea03) - [x] 2\~3 Tldraw pages, 2\~3 peers 1. [tldraw-yjs-example](https://github.com/tldraw/tldraw-yjs-example) quickly reload 2. Apply it to [tldraw-yjs-example](https://github.com/tldraw/tldraw-yjs-example) and then quickly reload 3. Compare the two versions ### Release Notes - Fixed a bug similar #1730
2023-09-19 10:02:01 +00:00
}, [ITEM_HEIGHT, currentPageId, isOpen])
2023-04-25 11:01:25 +00:00
const handlePointerDown = useCallback(
(e: React.PointerEvent<HTMLButtonElement>) => {
const { clientY, currentTarget } = e
const {
dataset: { id, index },
} = currentTarget
if (!id || !index) return
const mut = rMutables.current
tldraw zero - package shuffle (#1710) This PR moves code between our packages so that: - @tldraw/editor is a “core” library with the engine and canvas but no shapes, tools, or other things - @tldraw/tldraw contains everything particular to the experience we’ve built for tldraw At first look, this might seem like a step away from customization and configuration, however I believe it greatly increases the configuration potential of the @tldraw/editor while also providing a more accurate reflection of what configuration options actually exist for @tldraw/tldraw. ## Library changes @tldraw/editor re-exports its dependencies and @tldraw/tldraw re-exports @tldraw/editor. - users of @tldraw/editor WITHOUT @tldraw/tldraw should almost always only import things from @tldraw/editor. - users of @tldraw/tldraw should almost always only import things from @tldraw/tldraw. - @tldraw/polyfills is merged into @tldraw/editor - @tldraw/indices is merged into @tldraw/editor - @tldraw/primitives is merged mostly into @tldraw/editor, partially into @tldraw/tldraw - @tldraw/file-format is merged into @tldraw/tldraw - @tldraw/ui is merged into @tldraw/tldraw Many (many) utils and other code is moved from the editor to tldraw. For example, embeds now are entirely an feature of @tldraw/tldraw. The only big chunk of code left in core is related to arrow handling. ## API Changes The editor can now be used without tldraw's assets. We load them in @tldraw/tldraw instead, so feel free to use whatever fonts or images or whatever that you like with the editor. All tools and shapes (except for the `Group` shape) are moved to @tldraw/tldraw. This includes the `select` tool. You should use the editor with at least one tool, however, so you now also need to send in an `initialState` prop to the Editor / <TldrawEditor> component indicating which state the editor should begin in. The `components` prop now also accepts `SelectionForeground`. The complex selection component that we use for tldraw is moved to @tldraw/tldraw. The default component is quite basic but can easily be replaced via the `components` prop. We pass down our tldraw-flavored SelectionFg via `components`. Likewise with the `Scribble` component: the `DefaultScribble` no longer uses our freehand tech and is a simple path instead. We pass down the tldraw-flavored scribble via `components`. The `ExternalContentManager` (`Editor.externalContentManager`) is removed and replaced with a mapping of types to handlers. - Register new content handlers with `Editor.registerExternalContentHandler`. - Register new asset creation handlers (for files and URLs) with `Editor.registerExternalAssetHandler` ### Change Type - [x] `major` — Breaking change ### Test Plan - [x] Unit Tests - [x] End to end tests ### Release Notes - [@tldraw/editor] lots, wip - [@tldraw/ui] gone, merged to tldraw/tldraw - [@tldraw/polyfills] gone, merged to tldraw/editor - [@tldraw/primitives] gone, merged to tldraw/editor / tldraw/tldraw - [@tldraw/indices] gone, merged to tldraw/editor - [@tldraw/file-format] gone, merged to tldraw/tldraw --------- Co-authored-by: alex <alex@dytry.ch>
2023-07-17 21:22:34 +00:00
setPointerCapture(e.currentTarget, e)
2023-04-25 11:01:25 +00:00
mut.status = 'pointing'
mut.pointing = { id, index: +index! }
const current = sortablePositionItems[id]
const dragY = current.y
mut.startY = clientY
mut.startIndex = Math.max(0, Math.min(Math.round(dragY / ITEM_HEIGHT), pages.length - 1))
},
[ITEM_HEIGHT, pages.length, sortablePositionItems]
)
const handlePointerMove = useCallback(
(e: React.PointerEvent<HTMLButtonElement>) => {
const mut = rMutables.current
if (mut.status === 'pointing') {
const { clientY } = e
const offset = clientY - mut.startY
if (Math.abs(offset) > 5) {
mut.status = 'dragging'
}
}
if (mut.status === 'dragging') {
const { clientY } = e
const offsetY = clientY - mut.startY
const current = sortablePositionItems[mut.pointing!.id]
const { startIndex, pointing } = mut
const dragY = current.y + offsetY
const dragIndex = Math.max(0, Math.min(Math.round(dragY / ITEM_HEIGHT), pages.length - 1))
const next = { ...sortablePositionItems }
next[pointing!.id] = {
y: current.y,
offsetY,
isSelected: true,
}
if (dragIndex !== mut.dragIndex) {
mut.dragIndex = dragIndex
for (let i = 0; i < pages.length; i++) {
const item = pages[i]
if (item.id === mut.pointing!.id) {
continue
}
let { y } = next[item.id]
if (dragIndex === startIndex) {
y = i * ITEM_HEIGHT
} else if (dragIndex < startIndex) {
if (dragIndex <= i && i < startIndex) {
y = (i + 1) * ITEM_HEIGHT
} else {
y = i * ITEM_HEIGHT
}
} else if (dragIndex > startIndex) {
if (dragIndex >= i && i > startIndex) {
y = (i - 1) * ITEM_HEIGHT
} else {
y = i * ITEM_HEIGHT
}
}
if (y !== next[item.id].y) {
next[item.id] = { y, offsetY: 0, isSelected: true }
}
}
}
setSortablePositionItems(next)
}
},
[ITEM_HEIGHT, pages, sortablePositionItems]
)
const handlePointerUp = useCallback(
(e: React.PointerEvent<HTMLButtonElement>) => {
const mut = rMutables.current
if (mut.status === 'dragging') {
const { id, index } = mut.pointing!
onMovePage(editor, id as TLPageId, index, mut.dragIndex)
2023-04-25 11:01:25 +00:00
}
tldraw zero - package shuffle (#1710) This PR moves code between our packages so that: - @tldraw/editor is a “core” library with the engine and canvas but no shapes, tools, or other things - @tldraw/tldraw contains everything particular to the experience we’ve built for tldraw At first look, this might seem like a step away from customization and configuration, however I believe it greatly increases the configuration potential of the @tldraw/editor while also providing a more accurate reflection of what configuration options actually exist for @tldraw/tldraw. ## Library changes @tldraw/editor re-exports its dependencies and @tldraw/tldraw re-exports @tldraw/editor. - users of @tldraw/editor WITHOUT @tldraw/tldraw should almost always only import things from @tldraw/editor. - users of @tldraw/tldraw should almost always only import things from @tldraw/tldraw. - @tldraw/polyfills is merged into @tldraw/editor - @tldraw/indices is merged into @tldraw/editor - @tldraw/primitives is merged mostly into @tldraw/editor, partially into @tldraw/tldraw - @tldraw/file-format is merged into @tldraw/tldraw - @tldraw/ui is merged into @tldraw/tldraw Many (many) utils and other code is moved from the editor to tldraw. For example, embeds now are entirely an feature of @tldraw/tldraw. The only big chunk of code left in core is related to arrow handling. ## API Changes The editor can now be used without tldraw's assets. We load them in @tldraw/tldraw instead, so feel free to use whatever fonts or images or whatever that you like with the editor. All tools and shapes (except for the `Group` shape) are moved to @tldraw/tldraw. This includes the `select` tool. You should use the editor with at least one tool, however, so you now also need to send in an `initialState` prop to the Editor / <TldrawEditor> component indicating which state the editor should begin in. The `components` prop now also accepts `SelectionForeground`. The complex selection component that we use for tldraw is moved to @tldraw/tldraw. The default component is quite basic but can easily be replaced via the `components` prop. We pass down our tldraw-flavored SelectionFg via `components`. Likewise with the `Scribble` component: the `DefaultScribble` no longer uses our freehand tech and is a simple path instead. We pass down the tldraw-flavored scribble via `components`. The `ExternalContentManager` (`Editor.externalContentManager`) is removed and replaced with a mapping of types to handlers. - Register new content handlers with `Editor.registerExternalContentHandler`. - Register new asset creation handlers (for files and URLs) with `Editor.registerExternalAssetHandler` ### Change Type - [x] `major` — Breaking change ### Test Plan - [x] Unit Tests - [x] End to end tests ### Release Notes - [@tldraw/editor] lots, wip - [@tldraw/ui] gone, merged to tldraw/tldraw - [@tldraw/polyfills] gone, merged to tldraw/editor - [@tldraw/primitives] gone, merged to tldraw/editor / tldraw/tldraw - [@tldraw/indices] gone, merged to tldraw/editor - [@tldraw/file-format] gone, merged to tldraw/tldraw --------- Co-authored-by: alex <alex@dytry.ch>
2023-07-17 21:22:34 +00:00
releasePointerCapture(e.currentTarget, e)
2023-04-25 11:01:25 +00:00
mut.status = 'idle'
},
[editor]
2023-04-25 11:01:25 +00:00
)
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLButtonElement>) => {
const mut = rMutables.current
// bail on escape
if (e.key === 'Escape') {
if (mut.status === 'dragging') {
setSortablePositionItems(
Object.fromEntries(
pages.map((page, i) => [
page.id,
{ y: i * ITEM_HEIGHT, offsetY: 0, isSelected: false },
])
)
)
}
mut.status = 'idle'
}
},
[ITEM_HEIGHT, pages]
)
const handleCreatePageClick = useCallback(() => {
if (isReadonlyMode) return
editor.batch(() => {
editor.mark('creating page')
const newPageId = PageRecordType.createId()
editor.createPage({ name: msg('page-menu.new-page-initial-name'), id: newPageId })
editor.setCurrentPage(newPageId)
setIsEditing(true)
})
}, [editor, msg, isReadonlyMode])
2023-04-25 11:01:25 +00:00
return (
<Popover id="pages" onOpenChange={onOpenChange} open={isOpen}>
2023-04-25 11:01:25 +00:00
<PopoverTrigger>
<Button
className="tlui-page-menu__trigger tlui-menu__trigger"
data-testid="main.page-menu"
2023-04-25 11:01:25 +00:00
icon="chevron-down"
type="menu"
2023-04-25 11:01:25 +00:00
title={currentPage.name}
>
<div className="tlui-page-menu__name">{currentPage.name}</div>
</Button>
</PopoverTrigger>
<PopoverContent side="bottom" align="start" sideOffset={6}>
<div className="tlui-page-menu__wrapper">
<div className="tlui-page-menu__header">
<div className="tlui-page-menu__header__title">{msg('page-menu.title')}</div>
{!isReadonlyMode && (
<div className="tlui-buttons__horizontal">
2023-04-25 11:01:25 +00:00
<Button
type="icon"
data-testid="page-menu.edit"
2023-04-25 11:01:25 +00:00
title={msg(isEditing ? 'page-menu.edit-done' : 'page-menu.edit-start')}
icon={isEditing ? 'check' : 'edit'}
onClick={toggleEditing}
/>
<Button
type="icon"
data-testid="page-menu.create"
2023-04-25 11:01:25 +00:00
icon="plus"
title={msg(
maxPageCountReached
? 'page-menu.max-page-count-reached'
: 'page-menu.create-new-page'
)}
disabled={maxPageCountReached}
onClick={handleCreatePageClick}
/>
</div>
2023-04-25 11:01:25 +00:00
)}
</div>
<div
className="tlui-page-menu__list tlui-menu__group"
style={{ height: ITEM_HEIGHT * pages.length + 4 }}
ref={rSortableContainer}
>
{pages.map((page, index) => {
const position = sortablePositionItems[page.id] ?? {
position: index * 40,
offsetY: 0,
}
return isEditing ? (
<div
key={page.id + '_editing'}
data-testid={`page-menu-item-${page.id}`}
2023-04-25 11:01:25 +00:00
className="tlui-page_menu__item__sortable"
style={{
zIndex: page.id === currentPage.id ? 888 : index,
transform: `translate(0px, ${position.y + position.offsetY}px)`,
}}
>
<Button
type="icon"
2023-04-25 11:01:25 +00:00
tabIndex={-1}
className="tlui-page_menu__item__sortable__handle"
icon="drag-handle-dots"
onPointerDown={handlePointerDown}
onPointerUp={handlePointerUp}
onPointerMove={handlePointerMove}
onKeyDown={handleKeyDown}
data-id={page.id}
data-index={index}
/>
{breakpoint < 5 && isCoarsePointer ? (
// sigh, this is a workaround for iOS Safari
// because the device and the radix popover seem
// to be fighting over scroll position. Nothing
// else seems to work!
<Button
type="normal"
2023-04-25 11:01:25 +00:00
className="tlui-page-menu__item__button"
onClick={() => {
const name = window.prompt('Rename page', page.name)
if (name && name !== page.name) {
editor.renamePage(page.id, name)
2023-04-25 11:01:25 +00:00
}
}}
onDoubleClick={toggleEditing}
isChecked={page.id === currentPage.id}
>
<span>{page.name}</span>
</Button>
) : (
<div
className="tlui-page_menu__item__sortable__title"
style={{ height: ITEM_HEIGHT }}
>
<PageItemInput
id={page.id}
name={page.name}
isCurrentPage={page.id === currentPage.id}
/>
</div>
)}
{!isReadonlyMode && (
<div className="tlui-page_menu__item__submenu" data-isediting={isEditing}>
<PageItemSubmenu index={index} item={page} listSize={pages.length} />
</div>
)}
</div>
) : (
<div
key={page.id}
data-testid={`page-menu-item-${page.id}`}
2023-04-25 11:01:25 +00:00
className="tlui-page-menu__item"
>
<Button
type="icon"
2023-04-25 11:01:25 +00:00
className="tlui-page-menu__item__button tlui-page-menu__item__button__checkbox"
`ShapeUtil.getGeometry`, selection rewrite (#1751) This PR is a significant rewrite of our selection / hit testing logic. It - replaces our current geometric helpers (`getBounds`, `getOutline`, `hitTestPoint`, and `hitTestLineSegment`) with a new geometry API - moves our hit testing entirely to JS using geometry - improves selection logic, especially around editing shapes, groups and frames - fixes many minor selection bugs (e.g. shapes behind frames) - removes hit-testing DOM elements from ShapeFill etc. - adds many new tests around selection - adds new tests around selection - makes several superficial changes to surface editor APIs This PR is hard to evaluate. The `selection-omnibus` test suite is intended to describe all of the selection behavior, however all existing tests are also either here preserved and passing or (in a few cases around editing shapes) are modified to reflect the new behavior. ## Geometry All `ShapeUtils` implement `getGeometry`, which returns a single geometry primitive (`Geometry2d`). For example: ```ts class BoxyShapeUtil { getGeometry(shape: BoxyShape) { return new Rectangle2d({ width: shape.props.width, height: shape.props.height, isFilled: true, margin: shape.props.strokeWidth }) } } ``` This geometric primitive is used for all bounds calculation, hit testing, intersection with arrows, etc. There are several geometric primitives that extend `Geometry2d`: - `Arc2d` - `Circle2d` - `CubicBezier2d` - `CubicSpline2d` - `Edge2d` - `Ellipse2d` - `Group2d` - `Polygon2d` - `Rectangle2d` - `Stadium2d` For shapes that have more complicated geometric representations, such as an arrow with a label, the `Group2d` can accept other primitives as its children. ## Hit testing Previously, we did all hit testing via events set on shapes and other elements. In this PR, I've replaced those hit tests with our own calculation for hit tests in JavaScript. This removed the need for many DOM elements, such as hit test area borders and fills which only existed to trigger pointer events. ## Selection We now support selecting "hollow" shapes by clicking inside of them. This involves a lot of new logic but it should work intuitively. See `Editor.getShapeAtPoint` for the (thoroughly commented) implementation. ![Kapture 2023-07-23 at 23 27 27](https://github.com/tldraw/tldraw/assets/23072548/a743275c-acdb-42d9-a3fe-b3e20dce86b6) every sunset is actually the sun hiding in fear and respect of tldraw's quality of interactions This PR also fixes several bugs with scribble selection, in particular around the shift key modifier. ![Kapture 2023-07-24 at 23 34 07](https://github.com/tldraw/tldraw/assets/23072548/871d67d0-8d06-42ae-a2b2-021effba37c5) ...as well as issues with labels and editing. There are **over 100 new tests** for selection covering groups, frames, brushing, scribbling, hovering, and editing. I'll add a few more before I feel comfortable merging this PR. ## Arrow binding Using the same "hollow shape" logic as selection, arrow binding is significantly improved. ![Kapture 2023-07-22 at 07 46 25](https://github.com/tldraw/tldraw/assets/23072548/5aa724b3-b57d-4fb7-92d0-80e34246753c) a thousand wise men could not improve on this ## Moving focus between editing shapes Previously, this was handled in the `editing_shapes` state. This is moved to `useEditableText`, and should generally be considered an advanced implementation detail on a shape-by-shape basis. This addresses a bug that I'd never noticed before, but which can be reproduced by selecting an shape—but not focusing its input—while editing a different shape. Previously, the new shape became the editing shape but its input did not focus. ![Kapture 2023-07-23 at 23 19 09](https://github.com/tldraw/tldraw/assets/23072548/a5e157fb-24a8-42bd-a692-04ce769b1a9c) In this PR, you can select a shape by clicking on its edge or body, or select its input to transfer editing / focus. ![Kapture 2023-07-23 at 23 22 21](https://github.com/tldraw/tldraw/assets/23072548/7384e7ea-9777-4e1a-8f63-15de2166a53a) tldraw, glorious tldraw ### Change Type - [x] `major` — Breaking change ### Test Plan 1. Erase shapes 2. Select shapes 3. Calculate their bounding boxes - [ ] Unit Tests // todo - [ ] End to end tests // todo ### Release Notes - [editor] Remove `ShapeUtil.getBounds`, `ShapeUtil.getOutline`, `ShapeUtil.hitTestPoint`, `ShapeUtil.hitTestLineSegment` - [editor] Add `ShapeUtil.getGeometry` - [editor] Add `Editor.getShapeGeometry`
2023-07-25 16:10:15 +00:00
onClick={() => editor.setCurrentPage(page.id)}
2023-04-25 11:01:25 +00:00
onDoubleClick={toggleEditing}
isChecked={page.id === currentPage.id}
title={msg('page-menu.go-to-page')}
>
<div className="tlui-page-menu__item__button__check">
{page.id === currentPage.id && <Icon icon="check" />}
</div>
<span>{page.name}</span>
</Button>
{!isReadonlyMode && (
<div className="tlui-page_menu__item__submenu">
<PageItemSubmenu
index={index}
item={page}
listSize={pages.length}
onRename={() => {
if (editor.environment.isIos) {
2023-04-25 11:01:25 +00:00
const name = window.prompt('Rename page', page.name)
if (name && name !== page.name) {
editor.renamePage(page.id, name)
2023-04-25 11:01:25 +00:00
}
} else {
editor.batch(() => {
setIsEditing(true)
editor.setCurrentPage(page.id)
})
2023-04-25 11:01:25 +00:00
}
}}
/>
</div>
)}
</div>
)
})}
</div>
</div>
</PopoverContent>
</Popover>
)
}