updates docs / readmes / adds contributor guide

This commit is contained in:
Steve Ruiz 2021-11-11 12:11:21 +00:00
parent 5be36d9bd8
commit 84a91ccc70
9 changed files with 468 additions and 658 deletions

80
CODE_OF_CONDUCT.md Normal file
View file

@ -0,0 +1,80 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address, without their explicit permission
- Contacting individual members, contributors, or leaders privately, outside designated community mechanisms, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at opensource@github.com. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at <https://www.contributor-covenant.org/version/2/0/code_of_conduct.html>.
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at <https://www.contributor-covenant.org/faq>. Translations are available at <https://www.contributor-covenant.org/translations>.

80
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,80 @@
# Welcome to the TLDraw contributing guide <!-- omit in toc -->
Thank you for investing your time in contributing to our project! Any contribution you make will be reflected in the @tldraw/tldraw package and at [tldraw.com](https://tldraw.com).
Read our [Code of Conduct](./CODE_OF_CONDUCT.md) to keep our community approachable and respectable.
In this guide you will get an overview of the contribution workflow from opening an issue, creating a PR, reviewing, and merging the PR.
Use the table of contents icon <img src="./assets/images/table-of-contents.png" width="25" height="25" /> on the top left corner of this document to get to a specific section of this guide quickly.
## New contributor guide
To get an overview of the project, read the [README](README.md). Here are some resources to help you get started with open source contributions:
- [Finding ways to contribute to open source on GitHub](https://docs.github.com/en/get-started/exploring-projects-on-github/finding-ways-to-contribute-to-open-source-on-github)
- [Set up Git](https://docs.github.com/en/get-started/quickstart/set-up-git)
- [GitHub flow](https://docs.github.com/en/get-started/quickstart/github-flow)
- [Collaborating with pull requests](https://docs.github.com/en/github/collaborating-with-pull-requests)
## Getting started
Join the [Discord channel](https://discord.gg/s4FXZ6fppJ). If you have questions or feedback, this is the best place to reach the team and other contributors directly.
### Issues
#### Create a new issue
If you spot a problem, [search if an issue already exists](https://github.com/tldraw/tldraw/issues). If a related issue doesn't exist, you can open a new issue using a relevant [issue form](https://github.com/tldraw/tldraw/issues/new/choose).
#### Solve an issue
Scan through our [existing issues](https://github.com/tldraw/tldraw/issues) to find one that interests you. You can narrow down the search using `labels` as filters. See [Labels](/contributing/how-to-use-labels.md) for more information. If you find an issue to work on, you are welcome to open a PR with a fix.
### Make Changes
#### Make changes locally
1. [Install Git LFS](https://docs.github.com/en/github/managing-large-files/versioning-large-files/installing-git-large-file-storage).
2. Fork the repository.
- Using GitHub Desktop:
- [Getting started with GitHub Desktop](https://docs.github.com/en/desktop/installing-and-configuring-github-desktop/getting-started-with-github-desktop) will guide you through setting up Desktop.
- Once Desktop is set up, you can use it to [fork the repo](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-and-forking-repositories-from-github-desktop)!
- Using the command line:
- [Fork the repo](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo#fork-an-example-repository) so that you can make your changes without affecting the original project until you're ready to merge them.
- GitHub Codespaces:
- [Fork, edit, and preview](https://docs.github.com/en/free-pro-team@latest/github/developing-online-with-codespaces/creating-a-codespace) using [GitHub Codespaces](https://github.com/features/codespaces) without having to install and run the project locally.
3. Install or update to **Node.js v16**.
4. Create a working branch and start with your changes!
5. Follow the [the development guide](guides/development.md).
### Commit your update
Commit the changes once you are happy with them.
### Pull Request
When you're finished with the changes, create a pull request, also known as a PR.
- Fill the "Ready for review" template so that we can review your PR. This template helps reviewers understand your changes as well as the purpose of your pull request.
- Don't forget to [link PR to issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) if you are solving one.
- Enable the checkbox to [allow maintainer edits](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/allowing-changes-to-a-pull-request-branch-created-from-a-fork) so the branch can be updated for a merge.
Once you submit your PR, a team member will review your proposal. We may ask questions or request for additional information.
- We may ask for changes to be made before a PR can be merged, either using [suggested changes](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/incorporating-feedback-in-your-pull-request) or pull request comments. You can apply suggested changes directly through the UI. You can make any other changes in your fork, then commit them to your branch.
- As you update your PR and apply changes, mark each conversation as [resolved](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request#resolving-conversations).
- If you run into any merge issues, checkout this [git tutorial](https://lab.github.com/githubtraining/managing-merge-conflicts) to help you resolve merge conflicts and other issues.
### Your PR is merged!
Congratulations :tada::tada: The GitHub team thanks you :sparkles:.
Once your PR is merged, your contributions will become part of the next TLDraw release, and will be visible in the [TLDraw app](https://tldraw.com).

286
README.md
View file

@ -4,9 +4,9 @@
# @tldraw/tldraw
This package contains the [tldraw](https://tldraw.com) editor as a React component named `<TLDraw>`. You can use this package to embed the editor in any React application.
This package contains the [TLDraw](https://tldraw.com) editor as a React component named `<TLDraw>`. You can use this package to embed the editor in any React application.
🎨 Want to build your own tldraw-ish app instead? Try [@tldraw/core](https://github.com/tldraw/core).
🎨 Want to build your own TLDraw-ish app instead? Try [@tldraw/core](https://github.com/tldraw/core).
💕 Love this library? Consider [becoming a sponsor](https://github.com/sponsors/steveruizok?frequency=recurring&sponsor=steveruizok).
@ -74,297 +74,35 @@ function App() {
}
```
Internally, the `TLDraw` component's user interface uses this API to make changes to the component's state. See the `TLDrawState` section for more on this API.
Internally, the `TLDraw` component's user interface uses this API to make changes to the component's state. See the `TLDrawState` section of the [documentation](guides/documentation) for more on this API.
### Responding to Changes
You can respond to changes and user actions using the `onChange` callback.
You can respond to changes and user actions using the `onChange` callback. For more specific changes, you can also use the `onPatch`, `onCommand`, or `onPersist` callbacks. See the [documentation](guides/documentation) for more.
```tsx
import { TLDraw, TLDrawState } from '@tldraw/tldraw'
function App() {
const handleChange = React.useCallback((state: TLDrawState, reason: string) => {}, [])
return <TLDraw onMount={handleMount} />
}
```
Internally, the `TLDraw` component's user interface uses this API to make changes to the component's state. See the `TLDrawState` section for more on this API.
## Documentation
### `TLDraw`
The `TLDraw` React component is the [tldraw](https://tldraw.com) editor exported as a standalone component. You can control the editor through props, or through the `TLDrawState`'s imperative API. **All props are optional.**
| Prop | Type | Description |
| ----------------- | ---------------- | --------------------------------------------------------------------------------------------------------- |
| `id` | `string` | An id under which to persist the component's state. |
| `document` | `TLDrawDocument` | An initial [`TLDrawDocument`](#tldrawdocument) object. |
| `currentPageId` | `string` | A current page id, referencing the `TLDrawDocument` object provided via the `document` prop. |
| `autofocus` | `boolean` | Whether the editor should immediately receive focus. Defaults to true. |
| `showMenu` | `boolean` | Whether to show the menu. |
| `showPages` | `boolean` | Whether to show the pages menu. |
| `showStyles` | `boolean` | Whether to show the styles menu. |
| `showTools` | `boolean` | Whether to show the tools. |
| `showUI` | `boolean` | Whether to show any UI other than the canvas. |
| `onMount` | `Function` | Called when the editor first mounts, receiving the current `TLDrawState`. |
| `onPatch` | `Function` | Called when the state is updated via a patch. |
| `onCommand` | `Function` | Called when the state is updated via a command. |
| `onPersist` | `Function` | Called when the state is persisted after an action. |
| `onChange` | `Function` | Called when the `TLDrawState` updates for any reason. |
| `onUserChange` | `Function` | Called when the user's "presence" information changes. |
| `onUndo` | `Function` | Called when the `TLDrawState` updates after an undo. |
| `onRedo` | `Function` | Called when the `TLDrawState` updates after a redo. |
| `onSignIn` | `Function` | Called when the user selects Sign In from the menu. |
| `onSignOut` | `Function` | Called when the user selects Sign Out from the menu. |
| `onNewProject` | `Function` | Called when the user when the user creates a new project through the menu or through a keyboard shortcut. |
| `onSaveProject` | `Function` | Called when the user saves a project through the menu or through a keyboard shortcut. |
| `onSaveProjectAs` | `Function` | Called when the user saves a project as a new project through the menu or through a keyboard shortcut. |
| `onOpenProject` | `Function` | Called when the user opens new project through the menu or through a keyboard shortcut. |
> **Note**: For help with the file-related callbacks, see `useFileSystem`.
### `useFileSystem`
You can use the `useFileSystem` hook to get prepared callbacks for `onNewProject`, `onOpenProject`, `onSaveProject`, and `onSaveProjectAs`. These callbacks allow a user to save files via the [FileSystem](https://developer.mozilla.org/en-US/docs/Web/API/FileSystem) API.
```ts
import { TLDraw, useFileSystem } from '@tldraw/tldraw'
function App() {
const fileSystemEvents = useFileSystem()
return <TLDraw {...fileSystemEvents} />
}
```
### `TLDrawDocument`
You can initialize or control the `<TLDraw>` component via its `document` property. A `TLDrawDocument` is an object with three properties:
- `id` - A unique ID for this document
- `pages` - A table of `TLDrawPage` objects
- `pageStates` - A table of `TLPageState` objects
- `version` - The document's version, used internally for migrations.
```ts
import { TLDrawDocument, TLDrawState } from '@tldraw/tldraw'
const myDocument: TLDrawDocument = {
id: 'doc',
version: TLDrawState.version,
pages: {
page1: {
id: 'page1',
shapes: {},
bindings: {},
},
},
pageStates: {
page1: {
id: 'page1',
selectedIds: [],
currentParentId: 'page1',
camera: {
point: [0, 0],
zoom: 1,
},
},
},
}
function App() {
return <TLDraw document={myDocument} />
}
```
**Tip:** TLDraw is built on [@tldraw/core](https://github.com/tldraw/core). The pages and pageStates in TLDraw are objects containing `TLPage` and `TLPageState` objects from the core library. For more about these types, check out the [@tldraw/core](https://github.com/tldraw/core) documentation.
**Important:** In the `pages` object, each `TLPage` object must be keyed under its `id` property. Likewise, each `TLPageState` object must be keyed under its `id`. In addition, each `TLPageState` object must have an `id` that matches its corresponding page.
### Shapes
Your `TLPage` objects may include shapes: objects that fit one of the `TLDrawShape` interfaces listed below. All `TLDrawShapes` extends a common interface:
| Property | Type | Description |
| --------------------- | ---------------- | --------------------------------------------------------------- |
| `id` | `string` | A unique ID for the shape. |
| `name` | `string` | The shape's name. |
| `type` | `string` | The shape's type. |
| `parentId` | `string` | The ID of the shape's parent (a shape or its page). |
| `childIndex` | `number` | The shape's order within its parent's children, indexed from 1. |
| `point` | `number[]` | The `[x, y]` position of the shape. |
| `rotation` | `number[]` | (optional) The shape's rotation in radians. |
| `children` | `string[]` | (optional) The shape's child shape ids. |
| `handles` | `TLDrawHandle{}` | (optional) A table of `TLHandle` objects. |
| `isLocked` | `boolean` | (optional) True if the shape is locked. |
| `isHidden` | `boolean` | (optional) True if the shape is hidden. |
| `isEditing` | `boolean` | (optional) True if the shape is currently editing. |
| `isGenerated` | `boolean` | (optional) True if the shape is generated. |
| `isAspectRatioLocked` | `boolean` | (optional) True if the shape's aspect ratio is locked. |
> **Important:** In order for re-ordering to work, a shape's `childIndex` values _must_ start from 1, not 0. The page or parent shape's "bottom-most" child should have a `childIndex` of 1.
The `ShapeStyle` object is a common style API for all shapes.
| Property | Type | Description |
| ---------- | ------------ | --------------------------------------- |
| `size` | `SizeStyle` | The size of the shape's stroke. |
| `dash` | `DashStyle` | The style of the shape's stroke. |
| `color` | `ColorStyle` | The shape's color. |
| `isFilled` | `boolean` | (optional) True if the shape is filled. |
#### `DrawShape`
A hand-drawn line.
| Property | Type | Description |
| -------- | ------------ | ----------------------------------------- |
| `points` | `number[][]` | An array of points as `[x, y, pressure]`. |
##### `RectangleShape`
A rectangular shape.
| Property | Type | Description |
| -------- | ---------- | --------------------------------------- |
| `size` | `number[]` | The `[width, height]` of the rectangle. |
#### `EllipseShape`
An elliptical shape.
| Property | Type | Description |
| -------- | ---------- | ----------------------------------- |
| `radius` | `number[]` | The `[x, y]` radius of the ellipse. |
#### `ArrowShape`
An arrow that can connect shapes.
| Property | Type | Description |
| ------------- | -------- | ----------------------------------------------------------------------- |
| `handles` | `object` | An object with three `TLHandle` properties: `start`, `end`, and `bend`. |
| `decorations` | `object` | An object with two properties `start`, `end`, and `bend`. |
#### `TextShape`
A line of text.
| Property | Type | Description |
| -------- | -------- | ------------------------- |
| `text` | `string` | The shape's text content. |
#### `StickyShape`
A sticky note.
| Property | Type | Description |
| -------- | -------- | ------------------------- |
| `text` | `string` | The shape's text content. |
### Bindings
A binding is a connection **from** one shape and **to** another shape. At the moment, only arrows may be bound "from". Most shapes may be bound "to", except other `ArrowShape` and `DrawShape`s.
| Property | Type | Description |
| ---------- | ---------------- | -------------------------------------------------------- |
| `id` | `string` | The binding's own unique ID. |
| `fromId` | `string` | The id of the `ArrowShape` that the binding is bound to. |
| `toId` | `string` | The id of the other shape that the binding is bound to. |
| `handleId` | `start` or `end` | The connected arrow handle. |
| `distance` | `number` | The distance from the bound point. |
| `point` | `number[]` | A normalized point representing the bound point. |
### `TLDrawState` API
You can change the `TLDraw` component's state through an imperative API called `TLDrawState`. To access this API, use the `onMount` callback, or any of the component's callback props, like `onPersist`.
```tsx
import { TLDraw, TLDrawState } from '@tldraw/tldraw'
function App() {
const handleMount = React.useCallback((state: TLDrawState) => {
state.selectAll()
const handleChange = React.useCallback((state: TLDrawState, reason: string) => {
// Do something with the change
}, [])
return <TLDraw onMount={handleMount} />
}
```
To view the full documentation of the `TLDrawState` API, generate the project's documentation by running `yarn docs` from the root folder, then open the file at:
## Documentation
```
/packages/tldraw/docs/classes/TLDrawState.html
```
See the project's [documentation](/guides/documentation).
Here are some useful methods:
## Contribution
- `loadDocument`
- `select`
- `selectAll`
- `selectNone`
- `delete`
- `deleteAll`
- `deletePage`
- `changePage`
- `cut`
- `copy`
- `paste`
- `copyJson`
- `copySvg`
- `undo`
- `redo`
- `zoomIn`
- `zoomOut`
- `zoomToContent`
- `zoomToSelection`
- `zoomToFit`
- `zoomTo`
- `resetZoom`
- `setCamera`
- `resetCamera`
- `align`
- `distribute`
- `stretch`
- `nudge`
- `duplicate`
- `flipHorizontal`
- `flipVertical`
- `rotate`
- `style`
- `group`
- `ungroup`
- `createShapes`
- `updateShapes`
- `updateDocument`
- `updateUsers`
- `removeUser`
- `setSetting`
- `selectTool`
- `cancel`
See the [contributing guide](/CONTRIBUTING.md).
Check the generated docs, source or the TypeScript types for more on these and other methods.
## Development
## Local Development
From the root folder:
- Run `yarn` to install dependencies.
- Run `yarn start` to start the development server for the package and for the example.
- Open `localhost:5420` to view the example project.
**Note:** The multiplayer examples and endpoints currently require an API key from [Liveblocks](https://liveblocks.io/), however the storage services that are used in TLDraw are currently in alpha and (as of November 2021) not accessible to the general public. You won't be able to authenticate and run these parts of the project.
Other scripts:
- Run `yarn test` to execute unit tests via [Jest](https://jestjs.io).
- Run `yarn docs` to build the docs via [ts-doc](https://typedoc.org/).
See the [development guide](/guides/development.md).
## Example

17
guides/development.md Normal file
View file

@ -0,0 +1,17 @@
# Development
From the root folder:
- Run `yarn` to install dependencies.
- Run `yarn start` to start the development server for the package and for the example.
- Open `localhost:5420` to view the example project.
**Note:** The multiplayer examples and endpoints currently require an API key from [Liveblocks](https://liveblocks.io/), however the storage services that are used in TLDraw are currently in alpha and (as of November 2021) not accessible to the general public. You won't be able to authenticate and run these parts of the project.
Other scripts:
- Run `yarn test` to execute unit tests via [Jest](https://jestjs.io).
- Run `yarn docs` to build the docs via [ts-doc](https://typedoc.org/).

268
guides/documentation.md Normal file
View file

@ -0,0 +1,268 @@
# Documentation
## Introduction
This file contains the documentatin for the `<TLDraw>` component as well as the data model that the component accepts.
In addition to the docs written below, this project also includes **generated documentation**. To view the generated docs:
1. Run `yarn docs` from the root folder
2. Open the file at:
```
/packages/tldraw/docs/classes/TLDrawState.html
```
## `TLDraw`
The `TLDraw` React component is the [tldraw](https://tldraw.com) editor exported as a standalone component. You can control the editor through props, or through the `TLDrawState`'s imperative API. **All props are optional.**
| Prop | Type | Description |
| ----------------- | ---------------- | --------------------------------------------------------------------------------------------------------- |
| `id` | `string` | An id under which to persist the component's state. |
| `document` | `TLDrawDocument` | An initial [`TLDrawDocument`](#tldrawdocument) object. |
| `currentPageId` | `string` | A current page id, referencing the `TLDrawDocument` object provided via the `document` prop. |
| `autofocus` | `boolean` | Whether the editor should immediately receive focus. Defaults to true. |
| `showMenu` | `boolean` | Whether to show the menu. |
| `showPages` | `boolean` | Whether to show the pages menu. |
| `showStyles` | `boolean` | Whether to show the styles menu. |
| `showTools` | `boolean` | Whether to show the tools. |
| `showUI` | `boolean` | Whether to show any UI other than the canvas. |
| `onMount` | `Function` | Called when the editor first mounts, receiving the current `TLDrawState`. |
| `onPatch` | `Function` | Called when the state is updated via a patch. |
| `onCommand` | `Function` | Called when the state is updated via a command. |
| `onPersist` | `Function` | Called when the state is persisted after an action. |
| `onChange` | `Function` | Called when the `TLDrawState` updates for any reason. |
| `onUserChange` | `Function` | Called when the user's "presence" information changes. |
| `onUndo` | `Function` | Called when the `TLDrawState` updates after an undo. |
| `onRedo` | `Function` | Called when the `TLDrawState` updates after a redo. |
| `onSignIn` | `Function` | Called when the user selects Sign In from the menu. |
| `onSignOut` | `Function` | Called when the user selects Sign Out from the menu. |
| `onNewProject` | `Function` | Called when the user when the user creates a new project through the menu or through a keyboard shortcut. |
| `onSaveProject` | `Function` | Called when the user saves a project through the menu or through a keyboard shortcut. |
| `onSaveProjectAs` | `Function` | Called when the user saves a project as a new project through the menu or through a keyboard shortcut. |
| `onOpenProject` | `Function` | Called when the user opens new project through the menu or through a keyboard shortcut. |
> **Note**: For help with the file-related callbacks, see `useFileSystem`.
## `useFileSystem`
You can use the `useFileSystem` hook to get prepared callbacks for `onNewProject`, `onOpenProject`, `onSaveProject`, and `onSaveProjectAs`. These callbacks allow a user to save files via the [FileSystem](https://developer.mozilla.org/en-US/docs/Web/API/FileSystem) API.
```ts
import { TLDraw, useFileSystem } from '@tldraw/tldraw'
function App() {
const fileSystemEvents = useFileSystem()
return <TLDraw {...fileSystemEvents} />
}
```
## `TLDrawDocument`
You can initialize or control the `<TLDraw>` component via its `document` property. A `TLDrawDocument` is an object with three properties:
- `id` - A unique ID for this document
- `pages` - A table of `TLDrawPage` objects
- `pageStates` - A table of `TLPageState` objects
- `version` - The document's version, used internally for migrations.
```ts
import { TLDrawDocument, TLDrawState } from '@tldraw/tldraw'
const myDocument: TLDrawDocument = {
id: 'doc',
version: TLDrawState.version,
pages: {
page1: {
id: 'page1',
shapes: {},
bindings: {},
},
},
pageStates: {
page1: {
id: 'page1',
selectedIds: [],
currentParentId: 'page1',
camera: {
point: [0, 0],
zoom: 1,
},
},
},
}
function App() {
return <TLDraw document={myDocument} />
}
```
**Tip:** TLDraw is built on [@tldraw/core](https://github.com/tldraw/core). The pages and pageStates in TLDraw are objects containing `TLPage` and `TLPageState` objects from the core library. For more about these types, check out the [@tldraw/core](https://github.com/tldraw/core) documentation.
**Important:** In the `pages` object, each `TLPage` object must be keyed under its `id` property. Likewise, each `TLPageState` object must be keyed under its `id`. In addition, each `TLPageState` object must have an `id` that matches its corresponding page.
## Shapes
Your `TLPage` objects may include shapes: objects that fit one of the `TLDrawShape` interfaces listed below. All `TLDrawShapes` extends a common interface:
| Property | Type | Description |
| --------------------- | ---------------- | --------------------------------------------------------------- |
| `id` | `string` | A unique ID for the shape. |
| `name` | `string` | The shape's name. |
| `type` | `string` | The shape's type. |
| `parentId` | `string` | The ID of the shape's parent (a shape or its page). |
| `childIndex` | `number` | The shape's order within its parent's children, indexed from 1. |
| `point` | `number[]` | The `[x, y]` position of the shape. |
| `rotation` | `number[]` | (optional) The shape's rotation in radians. |
| `children` | `string[]` | (optional) The shape's child shape ids. |
| `handles` | `TLDrawHandle{}` | (optional) A table of `TLHandle` objects. |
| `isLocked` | `boolean` | (optional) True if the shape is locked. |
| `isHidden` | `boolean` | (optional) True if the shape is hidden. |
| `isEditing` | `boolean` | (optional) True if the shape is currently editing. |
| `isGenerated` | `boolean` | (optional) True if the shape is generated. |
| `isAspectRatioLocked` | `boolean` | (optional) True if the shape's aspect ratio is locked. |
> **Important:** In order for re-ordering to work, a shape's `childIndex` values _must_ start from 1, not 0. The page or parent shape's "bottom-most" child should have a `childIndex` of 1.
The `ShapeStyle` object is a common style API for all shapes.
| Property | Type | Description |
| ---------- | ------------ | --------------------------------------- |
| `size` | `SizeStyle` | The size of the shape's stroke. |
| `dash` | `DashStyle` | The style of the shape's stroke. |
| `color` | `ColorStyle` | The shape's color. |
| `isFilled` | `boolean` | (optional) True if the shape is filled. |
### `DrawShape`
A hand-drawn line.
| Property | Type | Description |
| -------- | ------------ | ----------------------------------------- |
| `points` | `number[][]` | An array of points as `[x, y, pressure]`. |
#### `RectangleShape`
A rectangular shape.
| Property | Type | Description |
| -------- | ---------- | --------------------------------------- |
| `size` | `number[]` | The `[width, height]` of the rectangle. |
### `EllipseShape`
An elliptical shape.
| Property | Type | Description |
| -------- | ---------- | ----------------------------------- |
| `radius` | `number[]` | The `[x, y]` radius of the ellipse. |
### `ArrowShape`
An arrow that can connect shapes.
| Property | Type | Description |
| ------------- | -------- | ----------------------------------------------------------------------- |
| `handles` | `object` | An object with three `TLHandle` properties: `start`, `end`, and `bend`. |
| `decorations` | `object` | An object with two properties `start`, `end`, and `bend`. |
### `TextShape`
A line of text.
| Property | Type | Description |
| -------- | -------- | ------------------------- |
| `text` | `string` | The shape's text content. |
### `StickyShape`
A sticky note.
| Property | Type | Description |
| -------- | -------- | ------------------------- |
| `text` | `string` | The shape's text content. |
## Bindings
A binding is a connection **from** one shape and **to** another shape. At the moment, only arrows may be bound "from". Most shapes may be bound "to", except other `ArrowShape` and `DrawShape`s.
| Property | Type | Description |
| ---------- | ---------------- | -------------------------------------------------------- |
| `id` | `string` | The binding's own unique ID. |
| `fromId` | `string` | The id of the `ArrowShape` that the binding is bound to. |
| `toId` | `string` | The id of the other shape that the binding is bound to. |
| `handleId` | `start` or `end` | The connected arrow handle. |
| `distance` | `number` | The distance from the bound point. |
| `point` | `number[]` | A normalized point representing the bound point. |
## `TLDrawState` API
You can change the `TLDraw` component's state through an imperative API called `TLDrawState`. To access this API, use the `onMount` callback, or any of the component's callback props, like `onPersist`.
```tsx
import { TLDraw, TLDrawState } from '@tldraw/tldraw'
function App() {
const handleMount = React.useCallback((state: TLDrawState) => {
state.selectAll()
}, [])
return <TLDraw onMount={handleMount} />
}
```
To view the full documentation of the `TLDrawState` API, generate the project's documentation by running `yarn docs` from the root folder, then open the file at:
```
/packages/tldraw/docs/classes/TLDrawState.html
```
Here are some useful methods:
- `loadDocument`
- `select`
- `selectAll`
- `selectNone`
- `delete`
- `deleteAll`
- `deletePage`
- `changePage`
- `cut`
- `copy`
- `paste`
- `copyJson`
- `copySvg`
- `undo`
- `redo`
- `zoomIn`
- `zoomOut`
- `zoomToContent`
- `zoomToSelection`
- `zoomToFit`
- `zoomTo`
- `resetZoom`
- `setCamera`
- `resetCamera`
- `align`
- `distribute`
- `stretch`
- `nudge`
- `duplicate`
- `flipHorizontal`
- `flipVertical`
- `rotate`
- `style`
- `group`
- `ungroup`
- `createShapes`
- `updateShapes`
- `updateDocument`
- `updateUsers`
- `removeUser`
- `setSetting`
- `selectTool`
- `cancel`
Check the generated docs, source or the TypeScript types for more on these and other methods.

5
guides/publishing.md Normal file
View file

@ -0,0 +1,5 @@
# Publishing
At the moment, publishing is done by hand by the project's maintainers.
This guide will be updated when more information is available.

View file

@ -4,388 +4,10 @@
# @tldraw/tldraw
This package contains the [tldraw](https://tldraw.com) editor as a React component named `<TLDraw>`. You can use this package to embed the editor in any React application.
This package contains the [TLDraw](https://tldraw.com) editor as a React component named `<TLDraw>`. You can use this package to embed the editor in any React application.
🎨 Want to build your own tldraw-ish app instead? Try [@tldraw/core](https://github.com/tldraw/core).
🎨 Want to build your own TLDraw-ish app instead? Try [@tldraw/core](https://github.com/tldraw/core).
💕 Love this library? Consider [becoming a sponsor](https://github.com/sponsors/steveruizok?frequency=recurring&sponsor=steveruizok).
## Installation
Use your package manager of choice to install `@tldraw/tldraw` and its peer dependencies.
```bash
yarn add @tldraw/tldraw
# or
npm i @tldraw/tldraw
```
## Usage
Import the `TLDraw` React component and use it in your app.
```tsx
import { TLDraw } from '@tldraw/tldraw'
function App() {
return <TLDraw />
}
```
### Persisting the State
You can use the `id` to persist the state in a user's browser storage.
```tsx
import { TLDraw } from '@tldraw/tldraw'
function App() {
return <TLDraw id="myState" />
}
```
### Controlling the Component through Props
You can control the `TLDraw` component through its props.
```tsx
import { TLDraw, TLDrawDocument } from '@tldraw/tldraw'
function App() {
const myDocument: TLDrawDocument = {}
return <TLDraw document={document} />
}
```
### Controlling the Component through the TLDrawState API
You can also control the `TLDraw` component imperatively through the `TLDrawState` API.
```tsx
import { TLDraw, TLDrawState } from '@tldraw/tldraw'
function App() {
const handleMount = React.useCallback((state: TLDrawState) => {
state.selectAll()
}, [])
return <TLDraw onMount={handleMount} />
}
```
Internally, the `TLDraw` component's user interface uses this API to make changes to the component's state. See the `TLDrawState` section for more on this API.
### Responding to Changes
You can respond to changes and user actions using the `onChange` callback.
```tsx
import { TLDraw, TLDrawState } from '@tldraw/tldraw'
function App() {
const handleChange = React.useCallback((state: TLDrawState, reason: string) => {}, [])
return <TLDraw onMount={handleMount} />
}
```
Internally, the `TLDraw` component's user interface uses this API to make changes to the component's state. See the `TLDrawState` section for more on this API.
## Documentation
### `TLDraw`
The `TLDraw` React component is the [tldraw](https://tldraw.com) editor exported as a standalone component. You can control the editor through props, or through the `TLDrawState`'s imperative API. **All props are optional.**
| Prop | Type | Description |
| ----------------- | ---------------- | --------------------------------------------------------------------------------------------------------- |
| `id` | `string` | An id under which to persist the component's state. |
| `document` | `TLDrawDocument` | An initial [`TLDrawDocument`](#tldrawdocument) object. |
| `currentPageId` | `string` | A current page id, referencing the `TLDrawDocument` object provided via the `document` prop. |
| `autofocus` | `boolean` | Whether the editor should immediately receive focus. Defaults to true. |
| `showMenu` | `boolean` | Whether to show the menu. |
| `showPages` | `boolean` | Whether to show the pages menu. |
| `showStyles` | `boolean` | Whether to show the styles menu. |
| `showTools` | `boolean` | Whether to show the tools. |
| `showUI` | `boolean` | Whether to show any UI other than the canvas. |
| `onMount` | `Function` | Called when the editor first mounts, receiving the current `TLDrawState`. |
| `onPatch` | `Function` | Called when the state is updated via a patch. |
| `onCommand` | `Function` | Called when the state is updated via a command. |
| `onPersist` | `Function` | Called when the state is persisted after an action. |
| `onChange` | `Function` | Called when the `TLDrawState` updates for any reason. |
| `onUserChange` | `Function` | Called when the user's "presence" information changes. |
| `onUndo` | `Function` | Called when the `TLDrawState` updates after an undo. |
| `onRedo` | `Function` | Called when the `TLDrawState` updates after a redo. |
| `onSignIn` | `Function` | Called when the user selects Sign In from the menu. |
| `onSignOut` | `Function` | Called when the user selects Sign Out from the menu. |
| `onNewProject` | `Function` | Called when the user when the user creates a new project through the menu or through a keyboard shortcut. |
| `onSaveProject` | `Function` | Called when the user saves a project through the menu or through a keyboard shortcut. |
| `onSaveProjectAs` | `Function` | Called when the user saves a project as a new project through the menu or through a keyboard shortcut. |
| `onOpenProject` | `Function` | Called when the user opens new project through the menu or through a keyboard shortcut. |
> **Note**: For help with the file-related callbacks, see `useFileSystem`.
### `useFileSystem`
You can use the `useFileSystem` hook to get prepared callbacks for `onNewProject`, `onOpenProject`, `onSaveProject`, and `onSaveProjectAs`. These callbacks allow a user to save files via the [FileSystem](https://developer.mozilla.org/en-US/docs/Web/API/FileSystem) API.
```ts
import { TLDraw, useFileSystem } from '@tldraw/tldraw'
function App() {
const fileSystemEvents = useFileSystem()
return <TLDraw {...fileSystemEvents} />
}
```
### `TLDrawDocument`
You can initialize or control the `<TLDraw>` component via its `document` property. A `TLDrawDocument` is an object with three properties:
- `id` - A unique ID for this document
- `pages` - A table of `TLDrawPage` objects
- `pageStates` - A table of `TLPageState` objects
- `version` - The document's version, used internally for migrations.
```ts
import { TLDrawDocument, TLDrawState } from '@tldraw/tldraw'
const myDocument: TLDrawDocument = {
id: 'doc',
version: TLDrawState.version,
pages: {
page1: {
id: 'page1',
shapes: {},
bindings: {},
},
},
pageStates: {
page1: {
id: 'page1',
selectedIds: [],
currentParentId: 'page1',
camera: {
point: [0, 0],
zoom: 1,
},
},
},
}
function App() {
return <TLDraw document={myDocument} />
}
```
**Tip:** TLDraw is built on [@tldraw/core](https://github.com/tldraw/core). The pages and pageStates in TLDraw are objects containing `TLPage` and `TLPageState` objects from the core library. For more about these types, check out the [@tldraw/core](https://github.com/tldraw/core) documentation.
**Important:** In the `pages` object, each `TLPage` object must be keyed under its `id` property. Likewise, each `TLPageState` object must be keyed under its `id`. In addition, each `TLPageState` object must have an `id` that matches its corresponding page.
### Shapes
Your `TLPage` objects may include shapes: objects that fit one of the `TLDrawShape` interfaces listed below. All `TLDrawShapes` extends a common interface:
| Property | Type | Description |
| --------------------- | ---------------- | --------------------------------------------------------------- |
| `id` | `string` | A unique ID for the shape. |
| `name` | `string` | The shape's name. |
| `type` | `string` | The shape's type. |
| `parentId` | `string` | The ID of the shape's parent (a shape or its page). |
| `childIndex` | `number` | The shape's order within its parent's children, indexed from 1. |
| `point` | `number[]` | The `[x, y]` position of the shape. |
| `rotation` | `number[]` | (optional) The shape's rotation in radians. |
| `children` | `string[]` | (optional) The shape's child shape ids. |
| `handles` | `TLDrawHandle{}` | (optional) A table of `TLHandle` objects. |
| `isLocked` | `boolean` | (optional) True if the shape is locked. |
| `isHidden` | `boolean` | (optional) True if the shape is hidden. |
| `isEditing` | `boolean` | (optional) True if the shape is currently editing. |
| `isGenerated` | `boolean` | (optional) True if the shape is generated. |
| `isAspectRatioLocked` | `boolean` | (optional) True if the shape's aspect ratio is locked. |
> **Important:** In order for re-ordering to work, a shape's `childIndex` values _must_ start from 1, not 0. The page or parent shape's "bottom-most" child should have a `childIndex` of 1.
The `ShapeStyle` object is a common style API for all shapes.
| Property | Type | Description |
| ---------- | ------------ | --------------------------------------- |
| `size` | `SizeStyle` | The size of the shape's stroke. |
| `dash` | `DashStyle` | The style of the shape's stroke. |
| `color` | `ColorStyle` | The shape's color. |
| `isFilled` | `boolean` | (optional) True if the shape is filled. |
#### `DrawShape`
A hand-drawn line.
| Property | Type | Description |
| -------- | ------------ | ----------------------------------------- |
| `points` | `number[][]` | An array of points as `[x, y, pressure]`. |
##### `RectangleShape`
A rectangular shape.
| Property | Type | Description |
| -------- | ---------- | --------------------------------------- |
| `size` | `number[]` | The `[width, height]` of the rectangle. |
#### `EllipseShape`
An elliptical shape.
| Property | Type | Description |
| -------- | ---------- | ----------------------------------- |
| `radius` | `number[]` | The `[x, y]` radius of the ellipse. |
#### `ArrowShape`
An arrow that can connect shapes.
| Property | Type | Description |
| ------------- | -------- | ----------------------------------------------------------------------- |
| `handles` | `object` | An object with three `TLHandle` properties: `start`, `end`, and `bend`. |
| `decorations` | `object` | An object with two properties `start`, `end`, and `bend`. |
#### `TextShape`
A line of text.
| Property | Type | Description |
| -------- | -------- | ------------------------- |
| `text` | `string` | The shape's text content. |
#### `StickyShape`
A sticky note.
| Property | Type | Description |
| -------- | -------- | ------------------------- |
| `text` | `string` | The shape's text content. |
### Bindings
A binding is a connection **from** one shape and **to** another shape. At the moment, only arrows may be bound "from". Most shapes may be bound "to", except other `ArrowShape` and `DrawShape`s.
| Property | Type | Description |
| ---------- | ---------------- | -------------------------------------------------------- |
| `id` | `string` | The binding's own unique ID. |
| `fromId` | `string` | The id of the `ArrowShape` that the binding is bound to. |
| `toId` | `string` | The id of the other shape that the binding is bound to. |
| `handleId` | `start` or `end` | The connected arrow handle. |
| `distance` | `number` | The distance from the bound point. |
| `point` | `number[]` | A normalized point representing the bound point. |
### `TLDrawState` API
You can change the `TLDraw` component's state through an imperative API called `TLDrawState`. To access this API, use the `onMount` callback, or any of the component's callback props, like `onPersist`.
```tsx
import { TLDraw, TLDrawState } from '@tldraw/tldraw'
function App() {
const handleMount = React.useCallback((state: TLDrawState) => {
state.selectAll()
}, [])
return <TLDraw onMount={handleMount} />
}
```
To view the full documentation of the `TLDrawState` API, generate the project's documentation by running `yarn docs` from the root folder, then open the file at:
```
/packages/tldraw/docs/classes/TLDrawState.html
```
Here are some useful methods:
- `loadDocument`
- `select`
- `selectAll`
- `selectNone`
- `delete`
- `deleteAll`
- `deletePage`
- `changePage`
- `cut`
- `copy`
- `paste`
- `copyJson`
- `copySvg`
- `undo`
- `redo`
- `zoomIn`
- `zoomOut`
- `zoomToContent`
- `zoomToSelection`
- `zoomToFit`
- `zoomTo`
- `resetZoom`
- `setCamera`
- `resetCamera`
- `align`
- `distribute`
- `stretch`
- `nudge`
- `duplicate`
- `flipHorizontal`
- `flipVertical`
- `rotate`
- `style`
- `group`
- `ungroup`
- `createShapes`
- `updateShapes`
- `updateDocument`
- `updateUsers`
- `removeUser`
- `setSetting`
- `selectTool`
- `cancel`
Check the generated docs, source or the TypeScript types for more on these and other methods.
## Local Development
From the root folder:
- Run `yarn` to install dependencies.
- Run `yarn start` to start the development server for the package and for the example.
- Open `localhost:5420` to view the example project.
**Note:** The multiplayer examples and endpoints currently require an API key from [Liveblocks](https://liveblocks.io/), however the storage services that are used in TLDraw are currently in alpha and (as of November 2021) not accessible to the general public. You won't be able to authenticate and run these parts of the project.
Other scripts:
- Run `yarn test` to execute unit tests via [Jest](https://jestjs.io).
- Run `yarn docs` to build the docs via [ts-doc](https://typedoc.org/).
## Example
See the `example` folder for examples of how to use the `<TLDraw/>` component.
## Community
### Support
Need help? Please [open an issue](https://github.com/tldraw/tldraw/issues/new) for support.
### Discussion
Want to connect with other devs? Visit the [Discord channel](https://discord.gg/s4FXZ6fppJ).
### License
This project is licensed under MIT.
If you're using the library in a commercial product, please consider [becoming a sponsor](https://github.com/sponsors/steveruizok?frequency=recurring&sponsor=steveruizok).
## Author
- [@steveruizok](https://twitter.com/steveruizok)
For documentation, see the [TLDraw](https://github.com/tldraw) repository.

View file

@ -24,7 +24,7 @@
"scripts": {
"start:electron": "yarn start",
"start": "node scripts/dev & yarn types:dev",
"build": "node scripts/build && yarn types:build && node scripts/copy-readme",
"build": "node scripts/build && yarn types:build && node scripts/copy-files",
"types:dev": "tsc -w",
"types:build": "tsc -p tsconfig.build.json && tsconfig-replace-paths -p tsconfig.build.json",
"lint": "eslint src/ --ext .ts,.tsx",

View file

@ -1,7 +1,7 @@
/* eslint-disable */
const fs = require('fs')
const filesToCopy = ['README.md', 'CHANGELOG.md', 'LICENSE.md', 'card-repo.png']
const filesToCopy = ['CHANGELOG.md', 'LICENSE.md', 'card-repo.png']
filesToCopy.forEach((file) => {
fs.copyFile(`../../${file}`, `./${file}`, (err) => {