Annotate shape meta data example (#2453)

Annotate shape meta data example

### Change Type

- [ ] `patch` — Bug fix
- [ ] `minor` — New feature
- [ ] `major` — Breaking change
- [ ] `dependencies` — Changes to package dependencies[^1]
- [x] `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. Add a step-by-step description of how to test your PR here.
2.

- [ ] Unit Tests
- [ ] End to end tests

### Release Notes

- Annotate shape meta data example

---------

Co-authored-by: Steve Ruiz <steveruizok@gmail.com>
This commit is contained in:
Taha 2024-01-12 15:51:00 +00:00 committed by GitHub
parent 78b8b4a7cc
commit 8029bf1d29
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,6 +1,9 @@
import { TLShape, Tldraw, track, useEditor } from '@tldraw/tldraw'
import '@tldraw/tldraw/tldraw.css'
// There's a guide at the bottom of this file!
// [1]
export default function ShapeMetaExample() {
return (
<div className="tldraw__editor">
@ -18,10 +21,10 @@ export default function ShapeMetaExample() {
)
}
// By default, the TLShape type's meta property is { [key: string]: any }, but we can type it
// by unioning the type with a new type that has a meta property of our choosing.
// [2]
type ShapeWithMyMeta = TLShape & { meta: { label: string } }
// [3]
export const ShapeLabelUiWithHelper = track(function ShapeLabelUiWithHelper() {
const editor = useEditor()
const onlySelectedShape = editor.getOnlySelectedShape() as ShapeWithMyMeta | null
@ -47,3 +50,30 @@ export const ShapeLabelUiWithHelper = track(function ShapeLabelUiWithHelper() {
</div>
)
})
/*
This example shows how to use the `getInitialMetaForShape` function to set initial
meta data for a shape and update it.
[1]
In the Tldraw component's `onMount` callback, we override the default
`Editor.getInitialMetaForShape` function. This function is called when
a new shape is created and provides the `meta` property value for the
new shape.
[2]
By default, the TLShape type's meta property is { [key: string]: any }, but we can type
it using a union like this.
[3]
This is our minimal ui for editing the meta data of our shapes. We use the `track`
function to make sure this component is reactive, it will re-render when the signals
it is tracking change. Check out the signia docs for more:
https://signia.tldraw.dev/docs/API/signia_react/functions/track
Because our component is a child of the Tldraw component, it has access to the `useEditor`
hook via React context. We use this to get the only selected shape. If there is a single
shape selected, we render the input and update the shape's meta data when the input changes
via the `onChange` function.
*/