Tldraw/packages/editor/src/lib/editor/shapes/ShapeUtil.ts

615 wiersze
16 KiB
TypeScript
Czysty Zwykły widok Historia

2023-04-25 11:01:25 +00:00
/* eslint-disable @typescript-eslint/no-unused-vars */
2024-04-16 11:13:54 +00:00
import { LegacyMigrations, MigrationSequence } from '@tldraw/store'
import {
ShapeProps,
TLHandle,
TLShape,
TLShapePartial,
TLShapePropsMigrations,
TLUnknownShape,
} from '@tldraw/tlschema'
React-powered SVG exports (#3117) ## Migration path 1. If any of your shapes implement `toSvg` for exports, you'll need to replace your implementation with a new version that returns JSX (it's a react component) instead of manually constructing SVG DOM nodes 2. `editor.getSvg` is deprecated. It still works, but will be going away in a future release. If you still need SVGs as DOM elements rather than strings, use `new DOMParser().parseFromString(svgString, 'image/svg+xml').firstElementChild` ## The change in detail At the moment, our SVG exports very carefully try to recreate the visuals of our shapes by manually constructing SVG DOM nodes. On its own this is really painful, but it also results in a lot of duplicated logic between the `component` and `getSvg` methods of shape utils. In #3020, we looked at using string concatenation & DOMParser to make this a bit less painful. This works, but requires specifying namespaces everywhere, is still pretty painful (no syntax highlighting or formatting), and still results in all that duplicated logic. I briefly experimented with creating my own version of the javascript language that let you embed XML like syntax directly. I was going to call it EXTREME JAVASCRIPT or XJS for short, but then I noticed that we already wrote the whole of tldraw in this thing called react and a (imo much worse named) version of the javascript xml thing already existed. Given the entire library already depends on react, what would it look like if we just used react directly for these exports? Turns out things get a lot simpler! Take a look at lmk what you think This diff was intended as a proof of concept, but is actually pretty close to being landable. The main thing is that here, I've deliberately leant into this being a big breaking change to see just how much code we could delete (turns out: lots). We could if we wanted to make this without making it a breaking change at all, but it would add back a lot of complexity on our side and run a fair bit slower --------- Co-authored-by: huppy-bot[bot] <128400622+huppy-bot[bot]@users.noreply.github.com>
2024-03-25 14:16:55 +00:00
import { ReactElement } from 'react'
import { Box } from '../../primitives/Box'
import { Vec } from '../../primitives/Vec'
`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
import { Geometry2d } from '../../primitives/geometry/Geometry2d'
import type { Editor } from '../Editor'
[Snapping 3/5] Custom snapping API (#2793) This diff adds an API for customising our existing snap types. These are: 1. Bound snapping. When translating or resizing a shape, it'll snap to certain key points on the bounds of particular shapes. Previously, these were hard-coded to the corners and center of the bounding box of the shape. Now, a shape can bring its own (e.g. a triangle may add snapping for its 3 corners, and it's centroid rather than bounding box center. 2. Handle outline snapping. When dragging a handle, it'll snap to the outline of other shapes geometry. Now, shapes can return different geometry for this sort of snapping if they like. Each of these is customised through a method on `ShapeUtil`: `getBoundsSnapGeometry` and `getHandleSnapGeometry`. These return interfaces describing the different geometry that can be snapped to in both these cases. Currently, each returns an object with a single property, but there are more types of snapping coming in follow-up PRs. When reviewing this PR, start with the definitions of `BoundsSnapGeometry` in `BoundsSnaps.ts` and `HandleSnapGeometry` in `HandleSnaps.ts` This doesn't add point snapping - i'll add that in a follow-up! It'll be customisable with the `getHandleSnapGeometry` API. Fixes TLD-2197 This PR is part of a series - please don't merge it until the things before it have landed! 1. #2827 4. #2831 5. #2793 (you are here) 6. #2841 7. #2845 ### Change Type - [x] `minor` — New feature [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan - [x] Unit Tests ### Release Notes - Add `ShapeUtil.getSnapInfo` for customising shape snaps.
2024-02-15 15:10:04 +00:00
import { BoundsSnapGeometry } from '../managers/SnapManager/BoundsSnaps'
import { HandleSnapGeometry } from '../managers/SnapManager/HandleSnaps'
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 { SvgExportContext } from '../types/SvgExportContext'
2023-04-25 11:01:25 +00:00
import { TLResizeHandle } from '../types/selection-types'
/** @public */
export interface TLShapeUtilConstructor<
T extends TLUnknownShape,
U extends ShapeUtil<T> = ShapeUtil<T>,
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
new (editor: Editor): U
[refactor] User-facing APIs (#1478) This PR updates our user-facing APIs for the Tldraw and TldrawEditor components, as well as the Editor (App). It mainly incorporates surface changes from #1450 without any changes to validators or migrators, incorporating feedback / discussion with @SomeHats and @ds300. Here we: - remove the TldrawEditorConfig - bring back a loose version of shape definitions - make a separation between "core" shapes and "default" shapes - do not allow custom shapes, migrators or validators to overwrite core shapes - but _do_ allow new shapes ## `<Tldraw>` component In this PR, the `Tldraw` component wraps both the `TldrawEditor` component and our `TldrawUi` component. It accepts a union of props for both components. Previously, this component also added local syncing via a `useLocalSyncClient` hook call, however that has been pushed down to the `TldrawEditor` component. ## `<TldrawEditor>` component The `TldrawEditor` component now more neatly wraps up the different ways that the editor can be configured. ## The store prop (`TldrawEditorProps.store`) There are three main ways for the `TldrawEditor` component to be run: 1. with an externally defined store 2. with an externally defined syncing store (local or remote) 3. with an internally defined store 4. with an internally defined locally syncing store The `store` prop allows for these configurations. If the `store` prop is defined, it may be defined either as a `TLStore` or as a `SyncedStore`. If the store is a `TLStore`, then the Editor will assume that the store is ready to go; if it is defined as a SyncedStore, then the component will display the loading / error screens as needed, or the final editor once the store's status is "synced". When the store is left undefined, then the `TldrawEditor` will create its own internal store using the optional `instanceId`, `initialData`, or `shapes` props to define the store / store schema. If the `persistenceKey` prop is left undefined, then the store will not be synced. If the `persistenceKey` is defined, then the store will be synced locally. In the future, we may also here accept the API key / roomId / etc for creating a remotely synced store. The `SyncedStore` type has been expanded to also include types used for remote syncing, e.g. with `ConnectionStatus`. ## Tools By default, the App has two "baked-in" tools: the select tool and the zoom tool. These cannot (for now) be replaced or removed. The default tools are used by default, but may be replaced by other tools if provided. ## Shapes By default, the App has a set of "core" shapes: - group - embed - bookmark - image - video - text That cannot by overwritten because they're created by the app at different moments, such as when double clicking on the canvas or via a copy and paste event. In follow up PRs, we'll split these out so that users can replace parts of the code where these shapes are created. ### Change Type - [x] `major` — Breaking Change ### Test Plan - [x] Unit Tests
2023-06-01 15:47:34 +00:00
type: T['type']
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
props?: ShapeProps<T>
2024-04-16 11:13:54 +00:00
migrations?: LegacyMigrations | TLShapePropsMigrations | MigrationSequence
2023-04-25 11:01:25 +00:00
}
/** @public */
export type TLShapeUtilFlag<T> = (shape: T) => boolean
/** @public */
export interface TLShapeUtilCanvasSvgDef {
key: string
component: React.ComponentType
}
2023-04-25 11:01:25 +00:00
/** @public */
export abstract class ShapeUtil<Shape extends TLUnknownShape = TLUnknownShape> {
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
constructor(public editor: Editor) {}
static props?: ShapeProps<TLUnknownShape>
2024-04-16 11:13:54 +00:00
static migrations?: LegacyMigrations | TLShapePropsMigrations
2023-04-25 11:01:25 +00:00
/**
* The type of the shape util, which should match the shape's type.
*
* @public
*/
static type: string
2023-04-25 11:01:25 +00:00
`ShapeUtil` refactor, `Editor` cleanup (#1611) This PR improves the ergonomics of `ShapeUtil` classes. ### Cached methods First, I've remove the cached methods (such as `bounds`) from the `ShapeUtil` class and lifted this to the `Editor` class. Previously, calling `ShapeUtil.getBounds` would return the un-cached bounds of a shape, while calling `ShapeUtil.bounds` would return the cached bounds of a shape. We also had `Editor.getBounds`, which would call `ShapeUtil.bounds`. It was confusing. The cached methods like `outline` were also marked with "please don't override", which suggested the architecture was just wrong. The only weirdness from this is that utils sometimes reach out to the editor for cached versions of data rather than calling their own cached methods. It's still an easier story to tell than what we had before. ### More defaults We now have three and only three `abstract` methods for a `ShapeUtil`: - `getDefaultProps` (renamed from `defaultProps`) - `getBounds`, - `component` - `indicator` Previously, we also had `getCenter` as an abstract method, though this was usually just the middle of the bounds anyway. ### Editing bounds This PR removes the concept of editingBounds. The viewport will no longer animate to editing shapes. ### Active area manager This PR also removes the active area manager, which was not being used in the way we expected it to be. ### Dpr manager This PR removes the dpr manager and uses a hook instead to update it from React. This is one less runtime browser dependency in the app, one less thing to document. ### Moving things around This PR also continues to try to organize related methods and properties in the editor. ### Change Type - [x] `major` — Breaking change ### Release Notes - [editor] renames `defaultProps` to `getDefaultProps` - [editor] removes `outline`, `outlineSegments`, `handles`, `bounds` - [editor] renames `renderBackground` to `backgroundComponent`
2023-06-19 14:01:18 +00:00
/**
* Get the default props for a shape.
*
* @public
*/
abstract getDefaultProps(): Shape['props']
`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
/**
* Get the shape's geometry.
*
* @param shape - The shape.
* @public
*/
abstract getGeometry(shape: Shape): Geometry2d
`ShapeUtil` refactor, `Editor` cleanup (#1611) This PR improves the ergonomics of `ShapeUtil` classes. ### Cached methods First, I've remove the cached methods (such as `bounds`) from the `ShapeUtil` class and lifted this to the `Editor` class. Previously, calling `ShapeUtil.getBounds` would return the un-cached bounds of a shape, while calling `ShapeUtil.bounds` would return the cached bounds of a shape. We also had `Editor.getBounds`, which would call `ShapeUtil.bounds`. It was confusing. The cached methods like `outline` were also marked with "please don't override", which suggested the architecture was just wrong. The only weirdness from this is that utils sometimes reach out to the editor for cached versions of data rather than calling their own cached methods. It's still an easier story to tell than what we had before. ### More defaults We now have three and only three `abstract` methods for a `ShapeUtil`: - `getDefaultProps` (renamed from `defaultProps`) - `getBounds`, - `component` - `indicator` Previously, we also had `getCenter` as an abstract method, though this was usually just the middle of the bounds anyway. ### Editing bounds This PR removes the concept of editingBounds. The viewport will no longer animate to editing shapes. ### Active area manager This PR also removes the active area manager, which was not being used in the way we expected it to be. ### Dpr manager This PR removes the dpr manager and uses a hook instead to update it from React. This is one less runtime browser dependency in the app, one less thing to document. ### Moving things around This PR also continues to try to organize related methods and properties in the editor. ### Change Type - [x] `major` — Breaking change ### Release Notes - [editor] renames `defaultProps` to `getDefaultProps` - [editor] removes `outline`, `outlineSegments`, `handles`, `bounds` - [editor] renames `renderBackground` to `backgroundComponent`
2023-06-19 14:01:18 +00:00
/**
* Get a JSX element for the shape (as an HTML element).
*
* @param shape - The shape.
* @public
*/
abstract component(shape: Shape): any
/**
* Get JSX describing the shape's indicator (as an SVG element).
*
* @param shape - The shape.
* @public
*/
abstract indicator(shape: Shape): any
/**
* Whether the shape can be snapped to by another shape.
*
* @public
*/
canSnap: TLShapeUtilFlag<Shape> = () => true
2023-04-25 11:01:25 +00:00
/**
* Whether the shape can be scrolled while editing.
*
* @public
*/
canScroll: TLShapeUtilFlag<Shape> = () => false
2023-04-25 11:01:25 +00:00
/**
* Whether the shape can be bound to by an arrow.
*
* @param _otherShape - The other shape attempting to bind to this shape.
* @public
*/
canBind = <K>(_shape: Shape, _otherShape?: K) => true
2023-04-25 11:01:25 +00:00
/**
* Whether the shape can be double clicked to edit.
*
* @public
*/
canEdit: TLShapeUtilFlag<Shape> = () => false
2023-04-25 11:01:25 +00:00
/**
* Whether the shape can be resized.
*
* @public
*/
canResize: TLShapeUtilFlag<Shape> = () => true
2023-04-25 11:01:25 +00:00
/**
* Whether the shape can be edited in read-only mode.
*
* @public
*/
canEditInReadOnly: TLShapeUtilFlag<Shape> = () => false
2023-04-25 11:01:25 +00:00
/**
* Whether the shape can be cropped.
*
* @public
*/
canCrop: TLShapeUtilFlag<Shape> = () => false
2023-04-25 11:01:25 +00:00
/**
`ShapeUtil` refactor, `Editor` cleanup (#1611) This PR improves the ergonomics of `ShapeUtil` classes. ### Cached methods First, I've remove the cached methods (such as `bounds`) from the `ShapeUtil` class and lifted this to the `Editor` class. Previously, calling `ShapeUtil.getBounds` would return the un-cached bounds of a shape, while calling `ShapeUtil.bounds` would return the cached bounds of a shape. We also had `Editor.getBounds`, which would call `ShapeUtil.bounds`. It was confusing. The cached methods like `outline` were also marked with "please don't override", which suggested the architecture was just wrong. The only weirdness from this is that utils sometimes reach out to the editor for cached versions of data rather than calling their own cached methods. It's still an easier story to tell than what we had before. ### More defaults We now have three and only three `abstract` methods for a `ShapeUtil`: - `getDefaultProps` (renamed from `defaultProps`) - `getBounds`, - `component` - `indicator` Previously, we also had `getCenter` as an abstract method, though this was usually just the middle of the bounds anyway. ### Editing bounds This PR removes the concept of editingBounds. The viewport will no longer animate to editing shapes. ### Active area manager This PR also removes the active area manager, which was not being used in the way we expected it to be. ### Dpr manager This PR removes the dpr manager and uses a hook instead to update it from React. This is one less runtime browser dependency in the app, one less thing to document. ### Moving things around This PR also continues to try to organize related methods and properties in the editor. ### Change Type - [x] `major` — Breaking change ### Release Notes - [editor] renames `defaultProps` to `getDefaultProps` - [editor] removes `outline`, `outlineSegments`, `handles`, `bounds` - [editor] renames `renderBackground` to `backgroundComponent`
2023-06-19 14:01:18 +00:00
* Does this shape provide a background for its children? If this is true,
* then any children with a `renderBackground` method will have their
* backgrounds rendered _above_ this shape. Otherwise, the children's
* backgrounds will be rendered above either the next ancestor that provides
* a background, or the canvas background.
2023-04-25 11:01:25 +00:00
*
`ShapeUtil` refactor, `Editor` cleanup (#1611) This PR improves the ergonomics of `ShapeUtil` classes. ### Cached methods First, I've remove the cached methods (such as `bounds`) from the `ShapeUtil` class and lifted this to the `Editor` class. Previously, calling `ShapeUtil.getBounds` would return the un-cached bounds of a shape, while calling `ShapeUtil.bounds` would return the cached bounds of a shape. We also had `Editor.getBounds`, which would call `ShapeUtil.bounds`. It was confusing. The cached methods like `outline` were also marked with "please don't override", which suggested the architecture was just wrong. The only weirdness from this is that utils sometimes reach out to the editor for cached versions of data rather than calling their own cached methods. It's still an easier story to tell than what we had before. ### More defaults We now have three and only three `abstract` methods for a `ShapeUtil`: - `getDefaultProps` (renamed from `defaultProps`) - `getBounds`, - `component` - `indicator` Previously, we also had `getCenter` as an abstract method, though this was usually just the middle of the bounds anyway. ### Editing bounds This PR removes the concept of editingBounds. The viewport will no longer animate to editing shapes. ### Active area manager This PR also removes the active area manager, which was not being used in the way we expected it to be. ### Dpr manager This PR removes the dpr manager and uses a hook instead to update it from React. This is one less runtime browser dependency in the app, one less thing to document. ### Moving things around This PR also continues to try to organize related methods and properties in the editor. ### Change Type - [x] `major` — Breaking change ### Release Notes - [editor] renames `defaultProps` to `getDefaultProps` - [editor] removes `outline`, `outlineSegments`, `handles`, `bounds` - [editor] renames `renderBackground` to `backgroundComponent`
2023-06-19 14:01:18 +00:00
* @internal
2023-04-25 11:01:25 +00:00
*/
`ShapeUtil` refactor, `Editor` cleanup (#1611) This PR improves the ergonomics of `ShapeUtil` classes. ### Cached methods First, I've remove the cached methods (such as `bounds`) from the `ShapeUtil` class and lifted this to the `Editor` class. Previously, calling `ShapeUtil.getBounds` would return the un-cached bounds of a shape, while calling `ShapeUtil.bounds` would return the cached bounds of a shape. We also had `Editor.getBounds`, which would call `ShapeUtil.bounds`. It was confusing. The cached methods like `outline` were also marked with "please don't override", which suggested the architecture was just wrong. The only weirdness from this is that utils sometimes reach out to the editor for cached versions of data rather than calling their own cached methods. It's still an easier story to tell than what we had before. ### More defaults We now have three and only three `abstract` methods for a `ShapeUtil`: - `getDefaultProps` (renamed from `defaultProps`) - `getBounds`, - `component` - `indicator` Previously, we also had `getCenter` as an abstract method, though this was usually just the middle of the bounds anyway. ### Editing bounds This PR removes the concept of editingBounds. The viewport will no longer animate to editing shapes. ### Active area manager This PR also removes the active area manager, which was not being used in the way we expected it to be. ### Dpr manager This PR removes the dpr manager and uses a hook instead to update it from React. This is one less runtime browser dependency in the app, one less thing to document. ### Moving things around This PR also continues to try to organize related methods and properties in the editor. ### Change Type - [x] `major` — Breaking change ### Release Notes - [editor] renames `defaultProps` to `getDefaultProps` - [editor] removes `outline`, `outlineSegments`, `handles`, `bounds` - [editor] renames `renderBackground` to `backgroundComponent`
2023-06-19 14:01:18 +00:00
providesBackgroundForChildren(shape: Shape): boolean {
return false
2023-04-25 11:01:25 +00:00
}
/**
* Whether the shape should hide its resize handles when selected.
*
* @public
*/
hideResizeHandles: TLShapeUtilFlag<Shape> = () => false
2023-04-25 11:01:25 +00:00
/**
* Whether the shape should hide its rotation handles when selected.
2023-04-25 11:01:25 +00:00
*
* @public
*/
hideRotateHandle: TLShapeUtilFlag<Shape> = () => false
2023-04-25 11:01:25 +00:00
/**
* Whether the shape should hide its selection bounds background when selected.
*
* @public
*/
hideSelectionBoundsBg: TLShapeUtilFlag<Shape> = () => false
2023-04-25 11:01:25 +00:00
/**
* Whether the shape should hide its selection bounds foreground when selected.
*
* @public
*/
hideSelectionBoundsFg: TLShapeUtilFlag<Shape> = () => false
2023-04-25 11:01:25 +00:00
/**
* Whether the shape's aspect ratio is locked.
*
* @public
*/
isAspectRatioLocked: TLShapeUtilFlag<Shape> = () => false
2023-04-25 11:01:25 +00:00
/**
* Get a JSX element for the shape (as an HTML element) to be rendered as part of the canvas background - behind any other shape content.
*
* @param shape - The shape.
* @internal
*/
`ShapeUtil` refactor, `Editor` cleanup (#1611) This PR improves the ergonomics of `ShapeUtil` classes. ### Cached methods First, I've remove the cached methods (such as `bounds`) from the `ShapeUtil` class and lifted this to the `Editor` class. Previously, calling `ShapeUtil.getBounds` would return the un-cached bounds of a shape, while calling `ShapeUtil.bounds` would return the cached bounds of a shape. We also had `Editor.getBounds`, which would call `ShapeUtil.bounds`. It was confusing. The cached methods like `outline` were also marked with "please don't override", which suggested the architecture was just wrong. The only weirdness from this is that utils sometimes reach out to the editor for cached versions of data rather than calling their own cached methods. It's still an easier story to tell than what we had before. ### More defaults We now have three and only three `abstract` methods for a `ShapeUtil`: - `getDefaultProps` (renamed from `defaultProps`) - `getBounds`, - `component` - `indicator` Previously, we also had `getCenter` as an abstract method, though this was usually just the middle of the bounds anyway. ### Editing bounds This PR removes the concept of editingBounds. The viewport will no longer animate to editing shapes. ### Active area manager This PR also removes the active area manager, which was not being used in the way we expected it to be. ### Dpr manager This PR removes the dpr manager and uses a hook instead to update it from React. This is one less runtime browser dependency in the app, one less thing to document. ### Moving things around This PR also continues to try to organize related methods and properties in the editor. ### Change Type - [x] `major` — Breaking change ### Release Notes - [editor] renames `defaultProps` to `getDefaultProps` - [editor] removes `outline`, `outlineSegments`, `handles`, `bounds` - [editor] renames `renderBackground` to `backgroundComponent`
2023-06-19 14:01:18 +00:00
backgroundComponent?(shape: Shape): any
2023-04-25 11:01:25 +00:00
/**
* Get an array of handle models for the shape. This is an optional method.
*
* @example
*
* ```ts
* util.getHandles?.(myShape)
* ```
*
* @param shape - The shape.
* @public
*/
`ShapeUtil` refactor, `Editor` cleanup (#1611) This PR improves the ergonomics of `ShapeUtil` classes. ### Cached methods First, I've remove the cached methods (such as `bounds`) from the `ShapeUtil` class and lifted this to the `Editor` class. Previously, calling `ShapeUtil.getBounds` would return the un-cached bounds of a shape, while calling `ShapeUtil.bounds` would return the cached bounds of a shape. We also had `Editor.getBounds`, which would call `ShapeUtil.bounds`. It was confusing. The cached methods like `outline` were also marked with "please don't override", which suggested the architecture was just wrong. The only weirdness from this is that utils sometimes reach out to the editor for cached versions of data rather than calling their own cached methods. It's still an easier story to tell than what we had before. ### More defaults We now have three and only three `abstract` methods for a `ShapeUtil`: - `getDefaultProps` (renamed from `defaultProps`) - `getBounds`, - `component` - `indicator` Previously, we also had `getCenter` as an abstract method, though this was usually just the middle of the bounds anyway. ### Editing bounds This PR removes the concept of editingBounds. The viewport will no longer animate to editing shapes. ### Active area manager This PR also removes the active area manager, which was not being used in the way we expected it to be. ### Dpr manager This PR removes the dpr manager and uses a hook instead to update it from React. This is one less runtime browser dependency in the app, one less thing to document. ### Moving things around This PR also continues to try to organize related methods and properties in the editor. ### Change Type - [x] `major` — Breaking change ### Release Notes - [editor] renames `defaultProps` to `getDefaultProps` - [editor] removes `outline`, `outlineSegments`, `handles`, `bounds` - [editor] renames `renderBackground` to `backgroundComponent`
2023-06-19 14:01:18 +00:00
getHandles?(shape: Shape): TLHandle[]
2023-04-25 11:01:25 +00:00
/**
* Get whether the shape can receive children of a given type.
*
* @param type - The shape type.
* @public
*/
canReceiveNewChildrenOfType(shape: Shape, type: TLShape['type']) {
2023-04-25 11:01:25 +00:00
return false
}
/**
* Get whether the shape can receive children of a given type.
*
* @param shape - The shape type.
* @param shapes - The shapes that are being dropped.
* @public
*/
canDropShapes(shape: Shape, shapes: TLShape[]) {
2023-04-25 11:01:25 +00:00
return false
}
/**
* Get the shape as an SVG object.
*
* @param shape - The shape.
* @param ctx - The export context for the SVG - used for adding e.g. \<def\>s
2023-04-25 11:01:25 +00:00
* @returns An SVG element.
* @public
*/
React-powered SVG exports (#3117) ## Migration path 1. If any of your shapes implement `toSvg` for exports, you'll need to replace your implementation with a new version that returns JSX (it's a react component) instead of manually constructing SVG DOM nodes 2. `editor.getSvg` is deprecated. It still works, but will be going away in a future release. If you still need SVGs as DOM elements rather than strings, use `new DOMParser().parseFromString(svgString, 'image/svg+xml').firstElementChild` ## The change in detail At the moment, our SVG exports very carefully try to recreate the visuals of our shapes by manually constructing SVG DOM nodes. On its own this is really painful, but it also results in a lot of duplicated logic between the `component` and `getSvg` methods of shape utils. In #3020, we looked at using string concatenation & DOMParser to make this a bit less painful. This works, but requires specifying namespaces everywhere, is still pretty painful (no syntax highlighting or formatting), and still results in all that duplicated logic. I briefly experimented with creating my own version of the javascript language that let you embed XML like syntax directly. I was going to call it EXTREME JAVASCRIPT or XJS for short, but then I noticed that we already wrote the whole of tldraw in this thing called react and a (imo much worse named) version of the javascript xml thing already existed. Given the entire library already depends on react, what would it look like if we just used react directly for these exports? Turns out things get a lot simpler! Take a look at lmk what you think This diff was intended as a proof of concept, but is actually pretty close to being landable. The main thing is that here, I've deliberately leant into this being a big breaking change to see just how much code we could delete (turns out: lots). We could if we wanted to make this without making it a breaking change at all, but it would add back a lot of complexity on our side and run a fair bit slower --------- Co-authored-by: huppy-bot[bot] <128400622+huppy-bot[bot]@users.noreply.github.com>
2024-03-25 14:16:55 +00:00
toSvg?(shape: Shape, ctx: SvgExportContext): ReactElement | null | Promise<ReactElement | null>
2023-04-25 11:01:25 +00:00
/**
* Get the shape's background layer as an SVG object.
*
* @param shape - The shape.
* @param ctx - ctx - The export context for the SVG - used for adding e.g. \<def\>s
* @returns An SVG element.
* @public
*/
React-powered SVG exports (#3117) ## Migration path 1. If any of your shapes implement `toSvg` for exports, you'll need to replace your implementation with a new version that returns JSX (it's a react component) instead of manually constructing SVG DOM nodes 2. `editor.getSvg` is deprecated. It still works, but will be going away in a future release. If you still need SVGs as DOM elements rather than strings, use `new DOMParser().parseFromString(svgString, 'image/svg+xml').firstElementChild` ## The change in detail At the moment, our SVG exports very carefully try to recreate the visuals of our shapes by manually constructing SVG DOM nodes. On its own this is really painful, but it also results in a lot of duplicated logic between the `component` and `getSvg` methods of shape utils. In #3020, we looked at using string concatenation & DOMParser to make this a bit less painful. This works, but requires specifying namespaces everywhere, is still pretty painful (no syntax highlighting or formatting), and still results in all that duplicated logic. I briefly experimented with creating my own version of the javascript language that let you embed XML like syntax directly. I was going to call it EXTREME JAVASCRIPT or XJS for short, but then I noticed that we already wrote the whole of tldraw in this thing called react and a (imo much worse named) version of the javascript xml thing already existed. Given the entire library already depends on react, what would it look like if we just used react directly for these exports? Turns out things get a lot simpler! Take a look at lmk what you think This diff was intended as a proof of concept, but is actually pretty close to being landable. The main thing is that here, I've deliberately leant into this being a big breaking change to see just how much code we could delete (turns out: lots). We could if we wanted to make this without making it a breaking change at all, but it would add back a lot of complexity on our side and run a fair bit slower --------- Co-authored-by: huppy-bot[bot] <128400622+huppy-bot[bot]@users.noreply.github.com>
2024-03-25 14:16:55 +00:00
toBackgroundSvg?(
shape: Shape,
ctx: SvgExportContext
): ReactElement | null | Promise<ReactElement | null>
`ShapeUtil` refactor, `Editor` cleanup (#1611) This PR improves the ergonomics of `ShapeUtil` classes. ### Cached methods First, I've remove the cached methods (such as `bounds`) from the `ShapeUtil` class and lifted this to the `Editor` class. Previously, calling `ShapeUtil.getBounds` would return the un-cached bounds of a shape, while calling `ShapeUtil.bounds` would return the cached bounds of a shape. We also had `Editor.getBounds`, which would call `ShapeUtil.bounds`. It was confusing. The cached methods like `outline` were also marked with "please don't override", which suggested the architecture was just wrong. The only weirdness from this is that utils sometimes reach out to the editor for cached versions of data rather than calling their own cached methods. It's still an easier story to tell than what we had before. ### More defaults We now have three and only three `abstract` methods for a `ShapeUtil`: - `getDefaultProps` (renamed from `defaultProps`) - `getBounds`, - `component` - `indicator` Previously, we also had `getCenter` as an abstract method, though this was usually just the middle of the bounds anyway. ### Editing bounds This PR removes the concept of editingBounds. The viewport will no longer animate to editing shapes. ### Active area manager This PR also removes the active area manager, which was not being used in the way we expected it to be. ### Dpr manager This PR removes the dpr manager and uses a hook instead to update it from React. This is one less runtime browser dependency in the app, one less thing to document. ### Moving things around This PR also continues to try to organize related methods and properties in the editor. ### Change Type - [x] `major` — Breaking change ### Release Notes - [editor] renames `defaultProps` to `getDefaultProps` - [editor] removes `outline`, `outlineSegments`, `handles`, `bounds` - [editor] renames `renderBackground` to `backgroundComponent`
2023-06-19 14:01:18 +00:00
/** @internal */
expandSelectionOutlinePx(shape: Shape): number {
return 0
}
/**
* Return elements to be added to the \<defs\> section of the canvases SVG context. This can be
* used to define SVG content (e.g. patterns & masks) that can be referred to by ID from svg
* elements returned by `component`.
*
* Each def should have a unique `key`. If multiple defs from different shapes all have the same
* key, only one will be used.
*/
getCanvasSvgDefs(): TLShapeUtilCanvasSvgDef[] {
return []
}
[Snapping 3/5] Custom snapping API (#2793) This diff adds an API for customising our existing snap types. These are: 1. Bound snapping. When translating or resizing a shape, it'll snap to certain key points on the bounds of particular shapes. Previously, these were hard-coded to the corners and center of the bounding box of the shape. Now, a shape can bring its own (e.g. a triangle may add snapping for its 3 corners, and it's centroid rather than bounding box center. 2. Handle outline snapping. When dragging a handle, it'll snap to the outline of other shapes geometry. Now, shapes can return different geometry for this sort of snapping if they like. Each of these is customised through a method on `ShapeUtil`: `getBoundsSnapGeometry` and `getHandleSnapGeometry`. These return interfaces describing the different geometry that can be snapped to in both these cases. Currently, each returns an object with a single property, but there are more types of snapping coming in follow-up PRs. When reviewing this PR, start with the definitions of `BoundsSnapGeometry` in `BoundsSnaps.ts` and `HandleSnapGeometry` in `HandleSnaps.ts` This doesn't add point snapping - i'll add that in a follow-up! It'll be customisable with the `getHandleSnapGeometry` API. Fixes TLD-2197 This PR is part of a series - please don't merge it until the things before it have landed! 1. #2827 4. #2831 5. #2793 (you are here) 6. #2841 7. #2845 ### Change Type - [x] `minor` — New feature [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan - [x] Unit Tests ### Release Notes - Add `ShapeUtil.getSnapInfo` for customising shape snaps.
2024-02-15 15:10:04 +00:00
/**
* Get the geometry to use when snapping to this this shape in translate/resize operations. See
* {@link BoundsSnapGeometry} for details.
*/
getBoundsSnapGeometry(shape: Shape): BoundsSnapGeometry {
return {}
}
/**
* Get the geometry to use when snapping handles to this shape. See {@link HandleSnapGeometry}
* for details.
*/
getHandleSnapGeometry(shape: Shape): HandleSnapGeometry {
return {}
}
2023-04-25 11:01:25 +00:00
// Events
/**
* A callback called just before a shape is created. This method provides a last chance to modify
* the created shape.
*
* @example
*
* ```ts
* onBeforeCreate = (next) => {
* return { ...next, x: next.x + 1 }
2023-04-25 11:01:25 +00:00
* }
* ```
*
* @param next - The next shape.
* @returns The next shape or void.
* @public
*/
onBeforeCreate?: TLOnBeforeCreateHandler<Shape>
2023-04-25 11:01:25 +00:00
/**
* A callback called just before a shape is updated. This method provides a last chance to modify
* the updated shape.
*
* @example
*
* ```ts
* onBeforeUpdate = (prev, next) => {
* if (prev.x === next.x) {
* return { ...next, x: next.x + 1 }
* }
* }
* ```
*
* @param prev - The previous shape.
* @param next - The next shape.
* @returns The next shape or void.
* @public
*/
onBeforeUpdate?: TLOnBeforeUpdateHandler<Shape>
2023-04-25 11:01:25 +00:00
/**
* A callback called when some other shapes are dragged over this one.
*
* @example
*
* ```ts
* onDragShapesOver = (shape, shapes) => {
Stickies: release candidate (#3249) This PR is the target for the stickies PRs that are moving forward. It should collect changes. - [x] New icon - [x] Improved shadows - [x] Shadow LOD - [x] New colors / theme options - [x] Shrink text size to avoid word breaks on the x axis - [x] Hide indicator whilst typing (reverted) - [x] Adjacent note positions - [x] buttons / clone handles - [x] position helpers for creating / translating (pits) - [x] keyboard shortcuts: (Tab, Shift+tab (RTL aware), Cmd-Enter, Shift+Cmd+enter) - [x] multiple shape translating - [x] Text editing - [x] Edit on type (feature flagged) - [x] click goes in correct place - [x] Notes as parents (reverted) - [x] Update colors - [x] Update SVG appearance ### Change Type - [x] `sdk` — Changes the tldraw SDK - [x] `feature` — New feature ### Test Plan Todo: fold in test plans for child PRs ### Unit tests: - [ ] Shrink text size to avoid word breaks on the x axis - [x] Adjacent notes - [x] buttons (clone handles) - [x] position helpers (pits) - [x] keyboard shortcuts: (Tab, Shift+tab (RTL aware), Cmd-Enter, Shift+Cmd+enter) - [ ] Text editing - [ ] Edit on type - [ ] click goes in correct place ### Release Notes - Improves sticky notes (see list) --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Mime Čuvalo <mimecuvalo@gmail.com> Co-authored-by: alex <alex@dytry.ch> Co-authored-by: Mitja Bezenšek <mitja.bezensek@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> Co-authored-by: Lu[ke] Wilson <l2wilson94@gmail.com> Co-authored-by: huppy-bot[bot] <128400622+huppy-bot[bot]@users.noreply.github.com>
2024-04-14 18:40:02 +00:00
* this.editor.reparentShapes(shapes, shape.id)
* }
* ```
*
* @param shape - The shape.
* @param shapes - The shapes that are being dragged over this one.
* @public
*/
Stickies: release candidate (#3249) This PR is the target for the stickies PRs that are moving forward. It should collect changes. - [x] New icon - [x] Improved shadows - [x] Shadow LOD - [x] New colors / theme options - [x] Shrink text size to avoid word breaks on the x axis - [x] Hide indicator whilst typing (reverted) - [x] Adjacent note positions - [x] buttons / clone handles - [x] position helpers for creating / translating (pits) - [x] keyboard shortcuts: (Tab, Shift+tab (RTL aware), Cmd-Enter, Shift+Cmd+enter) - [x] multiple shape translating - [x] Text editing - [x] Edit on type (feature flagged) - [x] click goes in correct place - [x] Notes as parents (reverted) - [x] Update colors - [x] Update SVG appearance ### Change Type - [x] `sdk` — Changes the tldraw SDK - [x] `feature` — New feature ### Test Plan Todo: fold in test plans for child PRs ### Unit tests: - [ ] Shrink text size to avoid word breaks on the x axis - [x] Adjacent notes - [x] buttons (clone handles) - [x] position helpers (pits) - [x] keyboard shortcuts: (Tab, Shift+tab (RTL aware), Cmd-Enter, Shift+Cmd+enter) - [ ] Text editing - [ ] Edit on type - [ ] click goes in correct place ### Release Notes - Improves sticky notes (see list) --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Mime Čuvalo <mimecuvalo@gmail.com> Co-authored-by: alex <alex@dytry.ch> Co-authored-by: Mitja Bezenšek <mitja.bezensek@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> Co-authored-by: Lu[ke] Wilson <l2wilson94@gmail.com> Co-authored-by: huppy-bot[bot] <128400622+huppy-bot[bot]@users.noreply.github.com>
2024-04-14 18:40:02 +00:00
onDragShapesOver?: TLOnDragHandler<Shape>
/**
* A callback called when some other shapes are dragged out of this one.
*
* @param shape - The shape.
* @param shapes - The shapes that are being dragged out.
* @public
*/
onDragShapesOut?: TLOnDragHandler<Shape>
/**
* A callback called when some other shapes are dropped over this one.
*
* @param shape - The shape.
* @param shapes - The shapes that are being dropped over this one.
* @public
*/
onDropShapesOver?: TLOnDragHandler<Shape>
2023-04-25 11:01:25 +00:00
/**
* A callback called when a shape starts being resized.
*
* @param shape - The shape.
* @returns A change to apply to the shape, or void.
* @public
*/
onResizeStart?: TLOnResizeStartHandler<Shape>
/**
* A callback called when a shape changes from a resize.
*
* @param shape - The shape at the start of the resize.
* @param info - Info about the resize.
* @returns A change to apply to the shape, or void.
* @public
*/
onResize?: TLOnResizeHandler<Shape>
/**
* A callback called when a shape finishes resizing.
*
* @param initial - The shape at the start of the resize.
* @param current - The current shape.
* @returns A change to apply to the shape, or void.
* @public
*/
onResizeEnd?: TLOnResizeEndHandler<Shape>
2023-04-25 11:01:25 +00:00
/**
* A callback called when a shape starts being translated.
*
* @param shape - The shape.
* @returns A change to apply to the shape, or void.
* @public
*/
onTranslateStart?: TLOnTranslateStartHandler<Shape>
/**
* A callback called when a shape changes from a translation.
*
* @param initial - The shape at the start of the translation.
* @param current - The current shape.
* @returns A change to apply to the shape, or void.
* @public
*/
onTranslate?: TLOnTranslateHandler<Shape>
/**
* A callback called when a shape finishes translating.
*
* @param initial - The shape at the start of the translation.
* @param current - The current shape.
* @returns A change to apply to the shape, or void.
* @public
*/
onTranslateEnd?: TLOnTranslateEndHandler<Shape>
2023-04-25 11:01:25 +00:00
arrows: add ability to change label placement (#2557) This adds the ability to drag the label on an arrow to a different location within the line segment/arc. https://github.com/tldraw/tldraw/assets/469604/dbd2ee35-bebc-48d6-b8ee-fcf12ce91fa5 - A lot of the complexity lay in ensuring a fixed distance from the ends of the arrowheads. - I added a new type of handle `text-adjust` that makes the text box the very handle itself. - I added a `ARROW_HANDLES` enum - we should use more enums! - The bulk of the changes are in ArrowShapeUtil — check that out in particular obviously :) Along the way, I tried to improve a couple spots as I touched them: - added some more documentation to Vec.ts because some of the functions in there were obscure/new to me. (at least the naming, hah) - added `getPointOnCircle` which was being done in a couple places independently and refactored those places. ### Questions - the `getPointOnCircle` API changed. Is this considered breaking and/or should I leave the signature the same? Wasn't sure if it was a big deal or not. - I made `labelPosition` in the schema always but I guess it could have been optional? Lemme know if there's a preference. - Any feedback on tests? Happy to expand those if necessary. ### Change Type - [ ] `patch` — Bug fix - [x] `minor` — New feature - [ ] `major` — Breaking change - [ ] `dependencies` — Changes to package dependencies[^1] - [ ] `documentation` — Changes to the documentation only[^2] - [ ] `tests` — Changes to any test code only[^2] - [ ] `internal` — Any other changes that don't affect the published package[^2] - [ ] I don't know [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. For arrow in [straightArrow, curvedArrow] test the following: a. Label in the middle b. Label at both ends of the arrow c. Test arrows in different directions d. Rotating the endpoints and seeing that the label stays at the end of the arrow at a fixed width. e. Test different stroke widths. f. Test with different arrowheads. 2. Also, test arcs that are more circle like than arc-like. - [x] Unit Tests - [ ] End to end tests ### Release Notes - Adds ability to change label position on arrows. --------- Co-authored-by: Steve Ruiz <steveruizok@gmail.com> Co-authored-by: alex <alex@dytry.ch>
2024-01-24 10:19:20 +00:00
/**
* A callback called when a shape's handle changes.
*
* @param shape - The current shape.
* @param info - An object containing the handle and whether the handle is 'precise' or not.
* @returns A change to apply to the shape, or void.
* @public
*/
onHandleDrag?: TLOnHandleDragHandler<Shape>
/**
* A callback called when a shape starts being rotated.
*
* @param shape - The shape.
* @returns A change to apply to the shape, or void.
* @public
*/
onRotateStart?: TLOnRotateStartHandler<Shape>
/**
* A callback called when a shape changes from a rotation.
*
* @param initial - The shape at the start of the rotation.
* @param current - The current shape.
* @returns A change to apply to the shape, or void.
* @public
*/
onRotate?: TLOnRotateHandler<Shape>
2023-04-25 11:01:25 +00:00
/**
* A callback called when a shape finishes rotating.
*
* @param initial - The shape at the start of the rotation.
* @param current - The current shape.
* @returns A change to apply to the shape, or void.
* @public
*/
onRotateEnd?: TLOnRotateEndHandler<Shape>
/**
* Not currently used.
*
* @internal
*/
onBindingChange?: TLOnBindingChangeHandler<Shape>
/**
* A callback called when a shape's children change.
*
* @param shape - The shape.
* @returns An array of shape updates, or void.
* @public
*/
onChildrenChange?: TLOnChildrenChangeHandler<Shape>
/**
* A callback called when a shape's handle is double clicked.
*
* @param shape - The shape.
* @param handle - The handle that is double-clicked.
* @returns A change to apply to the shape, or void.
* @public
*/
onDoubleClickHandle?: TLOnDoubleClickHandleHandler<Shape>
/**
* A callback called when a shape's edge is double clicked.
*
* @param shape - The shape.
* @returns A change to apply to the shape, or void.
* @public
*/
onDoubleClickEdge?: TLOnDoubleClickHandler<Shape>
/**
* A callback called when a shape is double clicked.
*
* @param shape - The shape.
* @returns A change to apply to the shape, or void.
* @public
*/
onDoubleClick?: TLOnDoubleClickHandler<Shape>
/**
* A callback called when a shape is clicked.
*
* @param shape - The shape.
* @returns A change to apply to the shape, or void.
* @public
*/
onClick?: TLOnClickHandler<Shape>
/**
* A callback called when a shape finishes being editing.
*
* @param shape - The shape.
* @public
*/
onEditEnd?: TLOnEditEndHandler<Shape>
2023-04-25 11:01:25 +00:00
}
/** @public */
export type TLOnBeforeCreateHandler<T extends TLShape> = (next: T) => T | void
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnBeforeUpdateHandler<T extends TLShape> = (prev: T, next: T) => T | void
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnTranslateStartHandler<T extends TLShape> = TLEventStartHandler<T>
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnTranslateHandler<T extends TLShape> = TLEventChangeHandler<T>
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnTranslateEndHandler<T extends TLShape> = TLEventChangeHandler<T>
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnRotateStartHandler<T extends TLShape> = TLEventStartHandler<T>
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnRotateHandler<T extends TLShape> = TLEventChangeHandler<T>
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnRotateEndHandler<T extends TLShape> = TLEventChangeHandler<T>
2023-04-25 11:01:25 +00:00
/**
* The type of resize.
*
* 'scale_shape' - The shape is being scaled, usually as part of a larger selection.
*
2023-04-25 11:01:25 +00:00
* 'resize_bounds' - The user is directly manipulating an individual shape's bounds using a resize
* handle. It is up to shape util implementers to decide how they want to handle the two
* situations.
*
* @public
*/
export type TLResizeMode = 'scale_shape' | 'resize_bounds'
/**
* Info about a resize.
* @param newPoint - The new local position of the shape.
* @param handle - The handle being dragged.
* @param mode - The type of resize.
* @param scaleX - The scale in the x-axis.
* @param scaleY - The scale in the y-axis.
* @param initialBounds - The bounds of the shape at the start of the resize.
* @param initialShape - The shape at the start of the resize.
* @public
*/
export type TLResizeInfo<T extends TLShape> = {
newPoint: Vec
handle: TLResizeHandle
mode: TLResizeMode
scaleX: number
scaleY: number
initialBounds: Box
initialShape: T
}
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnResizeHandler<T extends TLShape> = (
2023-04-25 11:01:25 +00:00
shape: T,
info: TLResizeInfo<T>
`ShapeUtil` refactor, `Editor` cleanup (#1611) This PR improves the ergonomics of `ShapeUtil` classes. ### Cached methods First, I've remove the cached methods (such as `bounds`) from the `ShapeUtil` class and lifted this to the `Editor` class. Previously, calling `ShapeUtil.getBounds` would return the un-cached bounds of a shape, while calling `ShapeUtil.bounds` would return the cached bounds of a shape. We also had `Editor.getBounds`, which would call `ShapeUtil.bounds`. It was confusing. The cached methods like `outline` were also marked with "please don't override", which suggested the architecture was just wrong. The only weirdness from this is that utils sometimes reach out to the editor for cached versions of data rather than calling their own cached methods. It's still an easier story to tell than what we had before. ### More defaults We now have three and only three `abstract` methods for a `ShapeUtil`: - `getDefaultProps` (renamed from `defaultProps`) - `getBounds`, - `component` - `indicator` Previously, we also had `getCenter` as an abstract method, though this was usually just the middle of the bounds anyway. ### Editing bounds This PR removes the concept of editingBounds. The viewport will no longer animate to editing shapes. ### Active area manager This PR also removes the active area manager, which was not being used in the way we expected it to be. ### Dpr manager This PR removes the dpr manager and uses a hook instead to update it from React. This is one less runtime browser dependency in the app, one less thing to document. ### Moving things around This PR also continues to try to organize related methods and properties in the editor. ### Change Type - [x] `major` — Breaking change ### Release Notes - [editor] renames `defaultProps` to `getDefaultProps` - [editor] removes `outline`, `outlineSegments`, `handles`, `bounds` - [editor] renames `renderBackground` to `backgroundComponent`
2023-06-19 14:01:18 +00:00
) => Omit<TLShapePartial<T>, 'id' | 'type'> | undefined | void
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnResizeStartHandler<T extends TLShape> = TLEventStartHandler<T>
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnResizeEndHandler<T extends TLShape> = TLEventChangeHandler<T>
2023-04-25 11:01:25 +00:00
/* -------------------- Dragging -------------------- */
/** @public */
export type TLOnDragHandler<T extends TLShape, R = void> = (shape: T, shapes: TLShape[]) => R
2023-04-25 11:01:25 +00:00
/** @internal */
export type TLOnBindingChangeHandler<T extends TLShape> = (shape: T) => TLShapePartial<T> | void
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnChildrenChangeHandler<T extends TLShape> = (shape: T) => TLShapePartial[] | void
2023-04-25 11:01:25 +00:00
arrows: add ability to change label placement (#2557) This adds the ability to drag the label on an arrow to a different location within the line segment/arc. https://github.com/tldraw/tldraw/assets/469604/dbd2ee35-bebc-48d6-b8ee-fcf12ce91fa5 - A lot of the complexity lay in ensuring a fixed distance from the ends of the arrowheads. - I added a new type of handle `text-adjust` that makes the text box the very handle itself. - I added a `ARROW_HANDLES` enum - we should use more enums! - The bulk of the changes are in ArrowShapeUtil — check that out in particular obviously :) Along the way, I tried to improve a couple spots as I touched them: - added some more documentation to Vec.ts because some of the functions in there were obscure/new to me. (at least the naming, hah) - added `getPointOnCircle` which was being done in a couple places independently and refactored those places. ### Questions - the `getPointOnCircle` API changed. Is this considered breaking and/or should I leave the signature the same? Wasn't sure if it was a big deal or not. - I made `labelPosition` in the schema always but I guess it could have been optional? Lemme know if there's a preference. - Any feedback on tests? Happy to expand those if necessary. ### Change Type - [ ] `patch` — Bug fix - [x] `minor` — New feature - [ ] `major` — Breaking change - [ ] `dependencies` — Changes to package dependencies[^1] - [ ] `documentation` — Changes to the documentation only[^2] - [ ] `tests` — Changes to any test code only[^2] - [ ] `internal` — Any other changes that don't affect the published package[^2] - [ ] I don't know [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. For arrow in [straightArrow, curvedArrow] test the following: a. Label in the middle b. Label at both ends of the arrow c. Test arrows in different directions d. Rotating the endpoints and seeing that the label stays at the end of the arrow at a fixed width. e. Test different stroke widths. f. Test with different arrowheads. 2. Also, test arcs that are more circle like than arc-like. - [x] Unit Tests - [ ] End to end tests ### Release Notes - Adds ability to change label position on arrows. --------- Co-authored-by: Steve Ruiz <steveruizok@gmail.com> Co-authored-by: alex <alex@dytry.ch>
2024-01-24 10:19:20 +00:00
/** @public */
export type TLOnHandleDragHandler<T extends TLShape> = (
2023-04-25 11:01:25 +00:00
shape: T,
info: {
handle: TLHandle
isPrecise: boolean
initial?: T | undefined
2023-04-25 11:01:25 +00:00
}
) => TLShapePartial<T> | void
/** @public */
export type TLOnClickHandler<T extends TLShape> = (shape: T) => TLShapePartial<T> | void
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnEditEndHandler<T extends TLShape> = (shape: T) => void
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnDoubleClickHandler<T extends TLShape> = (shape: T) => TLShapePartial<T> | void
2023-04-25 11:01:25 +00:00
/** @public */
export type TLOnDoubleClickHandleHandler<T extends TLShape> = (
2023-04-25 11:01:25 +00:00
shape: T,
handle: TLHandle
) => TLShapePartial<T> | void
type TLEventStartHandler<T extends TLShape> = (shape: T) => TLShapePartial<T> | void
type TLEventChangeHandler<T extends TLShape> = (initial: T, current: T) => TLShapePartial<T> | void