diff --git a/.eslintignore b/.eslintignore deleted file mode 100644 index 35e915e52..000000000 --- a/.eslintignore +++ /dev/null @@ -1,3 +0,0 @@ -**/node_modules/* -**/out/* -**/.next/* diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 000000000..80e3f6d0b --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,15 @@ +module.exports = { + root: true, + parser: '@typescript-eslint/parser', + plugins: ['@typescript-eslint'], + extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'], + overrides: [ + { + // enable the rule specifically for TypeScript files + files: ['*.ts', '*.tsx'], + rules: { + '@typescript-eslint/explicit-module-boundary-types': [0], + }, + }, + ], +} diff --git a/.eslintrc.json b/.eslintrc.json deleted file mode 100644 index 2b7fe86e0..000000000 --- a/.eslintrc.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "parser": "@typescript-eslint/parser", - "plugins": ["@typescript-eslint"], - "extends": [ - "eslint:recommended", - "plugin:react/recommended", - "plugin:@typescript-eslint/recommended" - // Uncomment the following lines to enable eslint-config-prettier - // Is not enabled right now to avoid issues with the Next.js repo - // "prettier", - ], - "env": { - "es6": true, - "browser": true, - "jest": true, - "node": true - }, - "settings": { - "react": { - "version": "detect" - } - }, - "ignorePatterns": "**/*.js", - "rules": { - "react/react-in-jsx-scope": 0, - "react/display-name": 0, - "react/prop-types": 0, - "@typescript-eslint/no-extra-semi": 0, - "@typescript-eslint/explicit-function-return-type": 0, - "@typescript-eslint/explicit-member-accessibility": 0, - "@typescript-eslint/indent": 0, - "@typescript-eslint/member-delimiter-style": 0, - "@typescript-eslint/no-explicit-any": 0, - "@typescript-eslint/no-var-requires": 0, - "@typescript-eslint/no-use-before-define": 0, - "@typescript-eslint/no-unused-vars": [ - 2, - { - "argsIgnorePattern": "^_" - } - ], - "no-console": [ - 2, - { - "allow": ["warn", "error"] - } - ] - } -} diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index dfe077042..000000000 --- a/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# Auto detect text files and perform LF normalization -* text=auto diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 2af738278..e6a409954 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -5,9 +5,13 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 + # install modules - name: Install modules run: yarn - # unit tests + # build + - name: Build + run: yarn build:packages + # run unit tests - name: Jest Annotations & Coverage uses: mattallty/jest-github-action@v1.0.3 env: diff --git a/.gitignore b/.gitignore index f39130ca3..6b81fa8e9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,37 +1,10 @@ -# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. +node_modules/ +build/ +lib/ +dist/ +docs/ +.idea/* -# dependencies -/dist -/node_modules -/.pnp -.pnp.js - -# testing -/coverage - -# next.js -/.next/ -/out/ - -# production -/build - -# misc .DS_Store -*.pem - -# debug -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# local env files -.env.local -.env.development.local -.env.test.local -.env.production.local - -# vercel -.vercel - -cypress/integration/examples +coverage +*.log diff --git a/.npmignore b/.npmignore new file mode 100644 index 000000000..2da193068 --- /dev/null +++ b/.npmignore @@ -0,0 +1,17 @@ +/.github/ +/.vscode/ +/node_modules/ +/build/ +/tmp/ +.idea/* +/docs/ + +coverage +*.log +.gitlab-ci.yml + +package-lock.json +/*.tgz +/tmp* +/mnt/ +/package/ diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index e1076edfa..000000000 --- a/.prettierrc +++ /dev/null @@ -1,6 +0,0 @@ -{ - "semi": false, - "singleQuote": true, - "tabWidth": 2, - "useTabs": false -} diff --git a/.vscode/snippets.code-snippets b/.vscode/snippets.code-snippets index 047864012..1effdca66 100644 --- a/.vscode/snippets.code-snippets +++ b/.vscode/snippets.code-snippets @@ -1,7 +1,7 @@ { "createComment": { "scope": "typescript,typescriptreact", - "prefix": "/**", + "prefix": "ccc", "body": [ "/**", " * ${1:description}", @@ -10,8 +10,7 @@ " *", " *```ts", " * ${2:example}", - " *```", - " */" + " *```" ], "description": "comment" } diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 000000000..d92be8b96 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,18 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "tsc", + "type": "shell", + "command": "./node_modules/.bin/tsc", + "args": ["--noEmit"], + "presentation": { + "reveal": "never", + "echo": false, + "focus": false, + "panel": "dedicated" + }, + "problemMatcher": "$tsc-watch" + } + ] +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..57d6b4ac9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Chris Hager + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 72023fe76..e44d26593 100644 --- a/README.md +++ b/README.md @@ -15,10 +15,19 @@ To support this project (and gain access to the project while it is in developme ## Documentation -... +In progress! Check the README files in [packages/core](packages/core/README.md) and [packages/tldraw](packages/tldraw/README.md). + +## Examples + +- [@tldraw/core example](https://codesandbox.io/s/tldraw-core-example-88c74) +- [@tldraw/tldraw example](https://codesandbox.io/s/tldraw-example-n539u) ## Local Development +### The tldraw packages + +To work on the packages (@tldraw/core or @tldraw/tldraw), you'll want to run the (extremely fast) dev server. + 1. Download or clone the repository. ```bash @@ -34,357 +43,19 @@ To support this project (and gain access to the project while it is in developme 3. Start the development server. ```bash - yarn dev + yarn start ``` -4. Open the local site at `https://localhost:3000`. +4. Open the local site at `https://localhost:5000`. -This project is a [Next.js](https://nextjs.org/) project. If you've worked with Next.js before, the tldraw code-base and setup instructions should all be very familiar. +### The tldraw app -## How it works +To work on the app itself (that embeds @tldraw/tldraw), run the Next.js app. This won't directly respond to changes to packages, so for concurrent package dev work be sure to use the package dev server instead. (This is being worked on.) -The app's state is a very large state machine located in `state/state.ts`. The machine is organized as a tree of state notes, such as `selecting` and `pinching`. +1. Start the development server. -``` -root -├── loading -└── ready - ├── selecting - │ ├── notPointing - │ ├── pointingBounds - │ ├── translatingSelection - │ └── ... - ├── usingTool - ├── pinching - └── ... -``` + ```bash + yarn start:www + ``` -### State Nodes - -Nodes may be active or inactive. The root node is always active. Depending on what's happened in the app, different branches of the state tree may be active, while other branches may be inactive. - -```ts -pinching: { - onExit: { secretlyDo: 'updateZoomCSS' }, - initial: 'selectPinching', - states: { - selectPinching: { - on: { - STOPPED_PINCHING: { to: 'selecting' }, - }, - }, - toolPinching: { - on: { - STOPPED_PINCHING: { to: 'usingTool.previous' }, - }, - }, - }, -}, -``` - -State nodes are both a way to describe the state (e.g., "the pinching state is active") and a way of organizing events. Each node has a set of events (`on`). When the state receives an event, it will execute the event handlers on each of the machine's _active_ states where the event is present. - -### Event Handlers - -Event handlers contain references to event handler functions: `actions`, `conditions`, `results`, and `async`s. These are defined at the bottom of the state machine's configuration. - -An event handler may be a single action: - -```ts -on: { - MOVED_POINTER: 'updateRotateSession', -} -``` - -Or it may be an array of actions: - -```ts -on: { - MOVED_TO_PAGE: ['moveSelectionToPage', 'zoomCameraToSelectionActual'], -} -``` - -Or it may be an object with conditions under `if` or `unless` and actions under `do`: - -```ts -on: { - SAVED_CODE: { - unless: 'isReadOnly', - do: 'saveCode', - } -} -``` - -An event handler may also contain transitions under `to`: - -```ts -on: { - STOPPED_PINCHING: { to: 'selecting' }, -}, -``` - -As well as nested event handlers under control flow, `then` and `else`. - -```ts -on: { - STOPPED_POINTING: { - if: 'isPressingShiftKey', - then: { - if: 'isPointedShapeSelected', - do: 'pullPointedIdFromSelectedIds', - }, - else: { - if: 'isPointingShape', - do: [ - 'clearSelectedIds', - 'setPointedId', - 'pushPointedIdToSelectedIds', - ], - }, - }, -} -``` - -And finally, an event handler may have arrays of event handler objects. - -```ts -on: { - STOPPED_POINTING: [ - 'completeSession', - { - if: 'isToolLocked', - to: 'dot.creating', - else: { - to: 'selecting' - }, - }, - ], -} -``` - -### Event Handler Functions - -The configuration's event handlers work by calling event handler functions. While each event handler function does a different job, all event handler functions receive the _same_ three parameters: - -1. The machine's current `data` draft -2. The payload sent by the event that has caused the function to run -3. The most recent result returned by a `result` function - -> Note: The `payload` and `result` parameters must be typed manually inline. - -```ts -eventHandlerFn(data, payload: { id: string }, result: Shape) {} -``` - -Results may return any value. - -```ts -pageById(data, payload: { id: string }) { - return data.document.pages[payload.id] -} -``` - -Conditions must return `true` or `false`. - -```ts -pageIsCurrentPage(data, payload, result: Page) { - return data.currentPageId === result.id -} -``` - -Actions may mutate the `data` draft. - -```ts -setCurrentPageId(data, payload, result: Page) { - data.currentPageId = result.id -} -``` - -In a state's event handlers, event handler functions are referred to by name. - -```ts -on: { - SOME_EVENT: { - get: "pageById" - unless: "pageIsCurrentPage", - do: "setCurrentPageId" - } -} -``` - -Asyncs are asynchronous functions. They work like results, but resolve data instead. - -```ts -async getCurrentUser(data) { - return fetch(`https://tldraw/api/users/${data.currentUserId}`) -} -``` - -These are used in asynchronous event handlers: - -```ts -loadingUser: { - async: { - await: "getCurrentUser", - onResolve: { to: "user" }, - onReject: { to: "error" }, - } -} -``` - -### State Updates - -The state will update each time it: - -1. receives an event... -2. that causes it to run an event handler... -3. that passes its conditions... -4. and that contains either an action or a transition - -Such updates are batched: while a single event may cause several event handlers to run, the state will update only once provided that at least one of the event handlers caused an action or transition to occur. - -When a state updates, it will cause any subscribed components to update via hooks. - -### Subscribing to State - -To use the state's data reactively, we use the `useSelector` hook. - -```tsx -import state, { useSelector } from 'state' - -function SomeComponent() { - const pointingId = useSelector((s) => s.data.pointingId) - - return
The pointing id is {pointingId}
-} -``` - -Each time the state updates, the hook will check whether the data returned by the selector function matches its previous data. If the answer is false (ie if the data is new) the hook will update and the new data will become its previous data. - -The hook may also accept a second parameter, a comparison function. If the selector function returns anything other than a primitive, we will often use a comparison function to correctly find changes. - -```tsx -import state, { useSelector } from 'state' -import { deepCompareArrays } from 'utils' - -function SomeComponent() { - const selectedIds = useSelector( - (s) => tld.getSelectedShapes(s.data).map((shape) => shape.id), - deepCompareArrays - ) - - return
The selected ids are {selectedIds.toString()}
-} -``` - -### Events - -Events are sent from the user interface to the state. - -```ts -import state from 'state' - -state.send('SELECTED_DRAW_TOOL') -``` - -Events may also include payloads of data. - -```ts -state.send('ALIGNED', { type: AlignType.Right }) -``` - -The payload will become the second parameter of any event handler function that runs as a result of the event. - -Note that with very few exceptions, we send events to the state regardless of whether the state can handle the event. Whether the event should have an effect—and what that effect should be—these questions are left entirely to the state machine. - -> Note: You can send an event to the state from anywhere in the app: even from components that are not subscribed to the state. See the components/style-panel files for examples. - -### Commands and History - -The app uses a command pattern to keep track of what has happened in the app, and to support an undo and redo stack. Each command includes a `do` method and an `undo` method. When the command is created, it will run its `do` method. If it is "undone", it will run its `undo` method. If the command is "redone", it will run its `do` method again. - -```ts -export default function nudgeCommand(data: Data, delta: number[]): void { - const initialShapes = tld.getSelectedShapeSnapshot(data, () => null) - - history.execute( - data, - new Command({ - name: 'nudge_shapes', - category: 'canvas', - do(data) { - tld.mutateShapes( - data, - initialShapes.map((shape) => shape.id), - (shape, utils) => { - utils.setProperty(shape, 'point', vec.add(shape.point, delta)) - } - ) - }, - undo(data) { - tld.mutateShapes( - data, - initialShapes.map((shape) => shape.id), - (shape, utils) => { - utils.setProperty(shape, 'point', vec.sub(shape.point, delta)) - } - ) - }, - }) - ) -} -``` - -Undos are not done programatically. It's the responsibility of a command to ensure that any mutations made in its `do` method are correctly reversed in its `undo` method. - -> Note: All mutations to a shape must be done through a shape's utils (the structure returned by `getShapeUtils`). Currently, many commands do this directly: however we're currently working on a more robust API for this, with built-in support for side effects, such as shown with `mutateShapes` above. - -### Sessions - -Not every change to the app's state needs to be put into the undo / redo stack. Sessions are a way of managing the data associated with certain states that lie _between_ commands, such as when a user is dragging a shape to a new position. - -Sessions are managed by the SessionManager (`state/session`). It guarantees that only one session is active at a time and allows other parts of the app's state to access information about the current session. - -A session's life cycle is accessed via four methods, `begin`, `update`, `cancel` and `complete`. Different sessions will implement these methods in different ways. - -A session begins when constructed. - -```ts -session.begin( - new Sessions.TranslateSession( - data, - tld.screenToWorld(inputs.pointer.origin, data) - ) -) -``` - -Next, the session receives updates. Note that we're passing in the `data` draft from an action. The session will make any necessary changes to the draft. - -```ts -session.update( - data, - tld.screenToWorld(payload.point, data), - payload.shiftKey, - payload.altKey -) -``` - -> Note: To get proper typing in `session.update`, you must provide the generic type of the session you're updating. - -When a session completes, the session calls a method. This way, a user is able to travel back through the undo stack, visit only discrete commands (like deleting a shape) and those commands that marked the end of a session. - -```ts -session.complete(data) -``` - -A session may also be cancelled. - -```ts -session.cancel(data) -``` - -When cancelled, it is the responsibility of the session to restore the state to exactly how it was when the session began, reversing any changes that were made to the state during the session. - -For this reason, many sessions begin by taking a snapshot of the current draft. - -> Because the draft is a JavaScript Proxy, you must deep clone any parts of the draft that you want to include in a snapshot. (Direct references will fail as the underlying Proxy will have expired.) While the memory size of a snapshot is not usually a concern, this deep-cloning process is thread-blocking, so try to snapshot only the parts of the `data` draft that you need. +2. Open the local site at `https://localhost:3000`. diff --git a/__tests__/README.md b/__tests__/README.md deleted file mode 100644 index ca00db08d..000000000 --- a/__tests__/README.md +++ /dev/null @@ -1,239 +0,0 @@ -# Testing Guide - -Writing tests for tldraw? Thank you! This guide will get you started. - -- [Getting Started](#getting-started) -- [How to Test](#how-to-test) -- [What to Test](#what-to-test) -- [I Found a Bug!](#i-found-a-bug) -- [TestUtils](#test-utils) -- [Conclusion and Tips](#conclusion-and-tips) - -## Getting Started - -This project uses Jest for its unit tests. - -- To run the test suite, run `yarn test` in your terminal. -- To start the test watcher, run `yarn test:watch`. -- To update the test snapshots, run `yarn test:update`. - -Tests live inside of the `__tests__` folder. - -To create a new test, create a file named `myTest.test.ts` inside of the `__tests__` folder. - -## How to Test - -In tldraw, we write our tests against application's _state_. - -Remember that in tldraw, user interactions send _events_ to the app's _state_, where they produce a change (or not) depending on the state's configuration and current status. To test a feature, we "manually" send those same events to the state machine and then check whether the events produced the change we expected. - -To test a feature, we'll need to: - -- learn how the features works in tldraw -- identify the events involved -- identify the outcome of the events -- reproduce the events in our test -- test the outcome - -### Example - -Let's say we want to test the "create a page" feature of the app. - -We'd start by creating a new file named `create-page.test.ts`. Here's some boilerplace to get us started. - -```ts -// __tests__/create-page.test.ts - -import TestState from '../test-utils' -const tt = new TestState() - -it('creates a new page', () => {}) -``` - -In the code above, we import our `TestState` class, create a new instance for this test file, then have a unit test that will assert something about our app's behavior. - -In the app's UI, we can find a button labelled "create page". - -```tsx -// page-panel.tsx - - state.send('CREATED_PAGE')} /> -``` - -Because we're only testing the state machine, we don't have to worry about how the `DropdownMenuButton` component works, or whether `onSelect` is implemented correctly. Instead, our only concern is the call to `state.send`, where we "send" the `CREATED_PAGE` event to the app's central state machine. - -Back in our test, we can send that the `CREATED_PAGE` event ourselves and check whether it's produced the correct outcome. - -```ts -// __tests__/create-page.test.ts - -import TestState from '../test-utils' -const tt = new TestState() - -it('creates a new page', () => { - const pageCountBefore = Object.keys(tt.state.data.document.pages).length - - tt.state.send('CREATED_PAGE') - - const pageCountAfter = Object.keys(tt.state.data.document.pages).length - - expect(pageCountAfter).toEqual(pageCountBefore + 1) -}) -``` - -If we run our tests (with `yarn test`) or if we're already in watch mode (`yarn test:watch`) then our tests should update. If it worked, hooray! Now try to make it fail and see what that looks like, too. - -## What to Test - -While a test like "create a page" is pretty self-explanatory, most features are at least a little complex. - -To _fully_ test a feature, we would need to: - -- test the entire outcome -- testing every circumstance under which the outcome could be different - -Let's take another look at the `CREATED_PAGE` event. - -If we search for the event in the state machine itself, we can find where and how event is being handled. - -```ts -// state/state.ts - -ready: { - on: { - // ... - CREATED_PAGE: { - unless: ['isReadOnly', 'isInSession'], - do: 'createPage', - } - } -} -``` - -Here's where we can see what exactly we need to test. The event can tell us a few things: - -- It should only run when the "ready" state is active -- It never run when the app is in read only mode -- It should never run when the app is in a session (like drawing or rotating) - -These are all things that we could test. For example: - -```ts -// __tests__/create-page.test.ts - -import TestState from '../test-utils' -const tt = new TestState() - -it('does not create a new page in read only mode', () => { - tt.state.send('TOGGLED_READ_ONLY') - - expect(tt.state.data.isReadOnly).toBe(true) - - const pageCountBefore = Object.keys(tt.state.data.document.pages).length - - tt.state.send('CREATED_PAGE') - - const pageCountAfter = Object.keys(tt.state.data.document.pages).length - - expect(pageCountAfter).toEqual(pageCountBefore) -}) -``` - -> Note that we're using a different event, `TOGGLED_READ_ONLY`, in order to get the state into the correct condition to make our test. When using events like this, it's a good idea to assert that the state is how you expect it to be before you make your "real" test. Here that means testing that the state's `data.isReadOnly` boolean is `true` before we test the `CREATED_PAGE` event. - -We can also look at the `createPage` action. - -```ts -// state/state.ts - -createPage(data) { - commands.createPage(data, true) -}, -``` - -If we follow this call, we'll find the `createPage` command (`state/commands/create-page.ts`). This command is more complex, but it gives us more to test: - -- did we correctly iterate the numbers in the new page's name? -- did we get the correct child index for the new page? -- did we save the current page to local storage? -- did we save the new page to local storage? -- did we add the new page to the document? -- did we add the new page state to the document? -- did we go to the new page? -- when we undo the command, will we remove the new page / page state? -- when we redo the command, will we put the new page / page state back? - -To _fully_ test a feature, we'll need to write tests that cover all of these. - -### Todo Tests - -...but while full test coverage is a goal, it's not always within reach. If you're not able to test everything about a feature, it's a good idea to write "placeholders" for the tests that need to be written. - -```ts -describe('when creating a new page...', () => { - it('sets the correct child index for the new page', () => { - // TODO - }) - - it('sets the correct name for the new page', () => { - // TODO - }) - - it('saves the document to local storage', () => { - // TODO - }) -}) -``` - -### Snapshots - -An even better way to improve coverage when dealing with complex tests is to write "snapshot" tests. - -```ts -describe('when creating a new page...', () => { - it('updates the document', () => { - tt.state.send('CREATED_PAGE') - expect(tt.state.data).toMatchSnapshot() - }) -}) -``` - -While snapshot tests don't assert specific things about a feature's implementation, they will at least help flag changes in other parts of the app that might break the feature. For example, if we accidentally made the app start in read only mode, then the snapshot outcome of `CREATED_PAGE` would be different—and the test would fail. - -## I Found a Bug! - -As you write your tests, chances are you'll find some part of the application that just doesn't work the way it should. If it's your own code, then go ahead and make your fix. If the bug is in code that someone else has written, and if the fix seems complicated, then consider reaching out to the author on [Discord](https://discord.gg/a3H98DGSXS) or on the Github issue for help. - -## TestUtils - -While you can test every feature in tldraw by sending events to the state, the `TestUtils` class is designed to make certain things easier. By convention, I'll refer to an instance of the `TestUtils` class as `tt`. - -```ts -import TestState from '../test-utils' -const tt = new TestState() -``` - -The `TestUtils` instance wraps an instance of the app's state machine (`tt.state`). It also exposes the state's data as `tt.data`, as well as the state's helper methods (`tt.send`, `tt.isIn`, etc.) - -- `tt.resetDocumentState` will clear the document and reset the app state. -- `tt.createShape` will create a new shape on the page. -- `tt.clickShape` will click a the indicated shape - -Check the `test-utils.ts` file for the rest of the API. Feel free to add your own methods if you have a reason for doing so. - -## Conclusion and Tips - -To wrap up, thanks again for writing tests for tldraw. Quality in creative software is extremely important: nothing's worse than losing work to a bug, but even lesser terrors—getting kicked out of creative flow by unexpected behavior, or having to accomodate an accidental quirk—can make an app unusable. - -To sum up what we've covered: - -- Do a bit of digging into a feature's events and their outcome(s) -- Test the app's state machine (view `TestUtils`), not the React view -- Use the `TestUtils` class for complex events like clicking and dragging -- Write "todo" tests for the things you can't get to -- Ask original authors if you find a complex bug -- Ask for help on [Discord](https://discord.gg/a3H98DGSXS) - -Thanks! - --Steve (@steveruizok) diff --git a/__tests__/__mocks__/data.json b/__tests__/__mocks__/data.json deleted file mode 100644 index decf560c6..000000000 --- a/__tests__/__mocks__/data.json +++ /dev/null @@ -1,326 +0,0 @@ -{ - "isReadOnly": false, - "settings": { - "fontSize": 13, - "isDarkMode": false, - "isCodeOpen": false, - "isDebugMode": false, - "isDebugOpen": false, - "isStyleOpen": false, - "isToolLocked": false, - "isPenLocked": false, - "nudgeDistanceLarge": 10, - "nudgeDistanceSmall": 1 - }, - "currentStyle": { - "size": "Medium", - "color": "Black", - "dash": "Draw", - "isFilled": false - }, - "activeTool": "select", - "editingId": null, - "boundsRotation": 0, - "currentPageId": "page1", - "currentParentId": "page1", - "currentCodeFileId": "file0", - "codeControls": {}, - "document": { - "id": "TESTING", - "name": "My Document", - "pages": { - "page1": { - "id": "page1", - "type": "page", - "name": "Page 1", - "childIndex": 0, - "shapes": { - "e43559cb-6f41-4ae4-9c49-158ed1ad2f72": { - "id": "e43559cb-6f41-4ae4-9c49-158ed1ad2f72", - "type": "rectangle", - "name": "Rectangle", - "parentId": "page1", - "childIndex": 3, - "point": [171.47, 288.63], - "size": [176.22, 192.26], - "radius": 2, - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "13448777-d8f5-46cd-8a70-a4259211902e": { - "id": "13448777-d8f5-46cd-8a70-a4259211902e", - "type": "rectangle", - "name": "Rectangle", - "parentId": "page1", - "childIndex": 4, - "point": [511.7, 404.19], - "size": [181.08999999999992, 150.40999999999997], - "radius": 2, - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "75010635-8dfb-48ea-9250-719e50e58f02": { - "id": "75010635-8dfb-48ea-9250-719e50e58f02", - "type": "rectangle", - "name": "Rectangle", - "parentId": "page1", - "childIndex": 5, - "point": [384.09, 378.45], - "size": [95.20999999999992, 91.1799999999999], - "radius": 2, - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "c892d665-3311-4e25-a0bf-c4632d777f7e": { - "id": "c892d665-3311-4e25-a0bf-c4632d777f7e", - "type": "ellipse", - "name": "Ellipse", - "parentId": "page1", - "childIndex": 6, - "point": [162.45, 679.23], - "radiusX": 102.99999999999997, - "radiusY": 102.99999999999994, - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "51641de1-9787-41b8-afcc-2c85fd1b24c7": { - "id": "51641de1-9787-41b8-afcc-2c85fd1b24c7", - "type": "ellipse", - "name": "Ellipse", - "parentId": "page1", - "childIndex": 7, - "point": [517.18, 783.54], - "radiusX": 102.99999999999997, - "radiusY": 102.99999999999994, - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "e08c415e-3db3-4d3b-878e-28ce693ec1b0": { - "id": "e08c415e-3db3-4d3b-878e-28ce693ec1b0", - "type": "ellipse", - "name": "Ellipse", - "parentId": "page1", - "childIndex": 8, - "point": [398.99, 810.79], - "radiusX": 45.484999999999985, - "radiusY": 45.48499999999996, - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "fee77127-e779-4576-882b-b1bf7c7e132f": { - "id": "fee77127-e779-4576-882b-b1bf7c7e132f", - "type": "arrow", - "name": "Arrow", - "parentId": "page1", - "childIndex": 9, - "point": [252.85, 1057.5], - "rotation": 0, - "bend": 0, - "handles": { - "start": { - "id": "start", - "index": 0, - "point": [0, 0] - }, - "end": { - "id": "end", - "index": 1, - "point": [0.09000000000000341, 208] - }, - "bend": { - "id": "bend", - "index": 2, - "point": [0.045000000000001705, 104] - } - }, - "decorations": { - "start": null, - "middle": null, - "end": "Arrow" - }, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "2d842ace-ebc5-4e83-acdf-de29352e5e62": { - "id": "2d842ace-ebc5-4e83-acdf-de29352e5e62", - "type": "arrow", - "name": "Arrow", - "parentId": "page1", - "childIndex": 10, - "point": [616.9, 1124.3], - "rotation": 0, - "bend": 0, - "handles": { - "start": { - "id": "start", - "index": 0, - "point": [0, 0] - }, - "end": { - "id": "end", - "index": 1, - "point": [2.4500000000000455, 185.20000000000005] - }, - "bend": { - "id": "bend", - "index": 2, - "point": [1.2250000000000227, 92.60000000000002] - } - }, - "decorations": { - "start": null, - "middle": null, - "end": "Arrow" - }, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "b8e4e2c5-c662-4587-bf80-b9820ad8ad7f": { - "id": "b8e4e2c5-c662-4587-bf80-b9820ad8ad7f", - "type": "arrow", - "name": "Arrow", - "parentId": "page1", - "childIndex": 11, - "point": [425.18, 1143.2], - "rotation": 0, - "bend": 0, - "handles": { - "start": { - "id": "start", - "index": 0, - "point": [0, 0] - }, - "end": { - "id": "end", - "index": 1, - "point": [1.8500000000000227, 95.70000000000005] - }, - "bend": { - "id": "bend", - "index": 2, - "point": [0.9250000000000114, 47.85000000000002] - } - }, - "decorations": { - "start": null, - "middle": null, - "end": "Arrow" - }, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "38e9e750-16c2-4476-93ab-21aeb5f8858f": { - "id": "38e9e750-16c2-4476-93ab-21aeb5f8858f", - "type": "text", - "name": "Text", - "parentId": "page1", - "childIndex": 12, - "point": [207.16, 1422.4], - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - }, - "text": "Hello", - "scale": 1 - }, - "5ba998df-c036-447a-9b88-d96c71394f52": { - "id": "5ba998df-c036-447a-9b88-d96c71394f52", - "type": "text", - "name": "Text", - "parentId": "page1", - "childIndex": 13, - "point": [389.57, 1496.5], - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - }, - "text": "Hello", - "scale": 1 - }, - "3c688979-b190-4270-915b-7d8dd22a2bb7": { - "id": "3c688979-b190-4270-915b-7d8dd22a2bb7", - "type": "text", - "name": "Text", - "parentId": "page1", - "childIndex": 14, - "point": [564.06, 1558.1], - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - }, - "text": "Hello", - "scale": 1 - } - } - } - }, - "code": { - "file0": { - "id": "file0", - "name": "index.ts", - "code": "\nconst draw = new Draw({\n points: [\n ...Utils.getPointsBetween([0, 0], [20, 50]),\n ...Utils.getPointsBetween([20, 50], [100, 20], 3),\n ...Utils.getPointsBetween([100, 20], [100, 100], 10),\n [100, 100],\n ],\n})\n\nconst rectangle = new Rectangle({\n point: [200, 0],\n style: {\n color: ColorStyle.Blue,\n },\n})\n\nconst ellipse = new Ellipse({\n point: [400, 0],\n})\n\nconst arrow = new Arrow({\n start: [600, 0],\n end: [700, 100],\n})\n\nconst radius = 1000\nconst count = 100\nconst center = [350, 50]\n\nfor (let i = 0; i < count; i++) {\n const point = Vec.rotWith(\n Vec.add(center, [radius, 0]),\n center,\n (Math.PI * 2 * i) / count\n )\n\n const dot = new Dot({\n point,\n })\n}\n " - } - } - }, - "pageStates": { - "page1": { - "id": "page1", - "camera": { - "point": [0, -145], - "zoom": 1 - }, - "selectedIds": {} - } - } -} diff --git a/__tests__/__mocks__/document.json b/__tests__/__mocks__/document.json deleted file mode 100644 index 2c8a7b213..000000000 --- a/__tests__/__mocks__/document.json +++ /dev/null @@ -1,298 +0,0 @@ -{ - "document": { - "id": "TESTING", - "name": "My Document", - "pages": { - "page1": { - "id": "page1", - "type": "page", - "name": "Page 1", - "childIndex": 0, - "shapes": { - "e43559cb-6f41-4ae4-9c49-158ed1ad2f72": { - "id": "e43559cb-6f41-4ae4-9c49-158ed1ad2f72", - "type": "rectangle", - "name": "Rectangle", - "parentId": "page1", - "childIndex": 3, - "point": [100, 100], - "size": [100, 100], - "radius": 2, - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "13448777-d8f5-46cd-8a70-a4259211902e": { - "id": "13448777-d8f5-46cd-8a70-a4259211902e", - "type": "rectangle", - "name": "Rectangle", - "parentId": "page1", - "childIndex": 4, - "point": [500, 400], - "size": [200, 200], - "radius": 2, - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "75010635-8dfb-48ea-9250-719e50e58f02": { - "id": "75010635-8dfb-48ea-9250-719e50e58f02", - "type": "rectangle", - "name": "Rectangle", - "parentId": "page1", - "childIndex": 5, - "point": [384.09, 378.45], - "size": [95.20999999999992, 91.1799999999999], - "radius": 2, - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "c892d665-3311-4e25-a0bf-c4632d777f7e": { - "id": "c892d665-3311-4e25-a0bf-c4632d777f7e", - "type": "ellipse", - "name": "Ellipse", - "parentId": "page1", - "childIndex": 6, - "point": [162.45, 679.23], - "radiusX": 102.99999999999997, - "radiusY": 102.99999999999994, - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "51641de1-9787-41b8-afcc-2c85fd1b24c7": { - "id": "51641de1-9787-41b8-afcc-2c85fd1b24c7", - "type": "ellipse", - "name": "Ellipse", - "parentId": "page1", - "childIndex": 7, - "point": [517.18, 783.54], - "radiusX": 102.99999999999997, - "radiusY": 102.99999999999994, - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "e08c415e-3db3-4d3b-878e-28ce693ec1b0": { - "id": "e08c415e-3db3-4d3b-878e-28ce693ec1b0", - "type": "ellipse", - "name": "Ellipse", - "parentId": "page1", - "childIndex": 8, - "point": [398.99, 810.79], - "radiusX": 45.484999999999985, - "radiusY": 45.48499999999996, - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "fee77127-e779-4576-882b-b1bf7c7e132f": { - "id": "fee77127-e779-4576-882b-b1bf7c7e132f", - "type": "arrow", - "name": "Arrow", - "parentId": "page1", - "childIndex": 9, - "point": [252.85, 1057.5], - "rotation": 0, - "bend": 0, - "handles": { - "start": { - "id": "start", - "index": 0, - "point": [0, 0] - }, - "end": { - "id": "end", - "index": 1, - "point": [0.09000000000000341, 208] - }, - "bend": { - "id": "bend", - "index": 2, - "point": [0.045000000000001705, 104] - } - }, - "decorations": { - "start": null, - "middle": null, - "end": "Arrow" - }, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "2d842ace-ebc5-4e83-acdf-de29352e5e62": { - "id": "2d842ace-ebc5-4e83-acdf-de29352e5e62", - "type": "arrow", - "name": "Arrow", - "parentId": "page1", - "childIndex": 10, - "point": [616.9, 1124.3], - "rotation": 0, - "bend": 0, - "handles": { - "start": { - "id": "start", - "index": 0, - "point": [0, 0] - }, - "end": { - "id": "end", - "index": 1, - "point": [2.4500000000000455, 185.20000000000005] - }, - "bend": { - "id": "bend", - "index": 2, - "point": [1.2250000000000227, 92.60000000000002] - } - }, - "decorations": { - "start": null, - "middle": null, - "end": "Arrow" - }, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "b8e4e2c5-c662-4587-bf80-b9820ad8ad7f": { - "id": "b8e4e2c5-c662-4587-bf80-b9820ad8ad7f", - "type": "arrow", - "name": "Arrow", - "parentId": "page1", - "childIndex": 11, - "point": [425.18, 1143.2], - "rotation": 0, - "bend": 0, - "handles": { - "start": { - "id": "start", - "index": 0, - "point": [0, 0] - }, - "end": { - "id": "end", - "index": 1, - "point": [1.8500000000000227, 95.70000000000005] - }, - "bend": { - "id": "bend", - "index": 2, - "point": [0.9250000000000114, 47.85000000000002] - } - }, - "decorations": { - "start": null, - "middle": null, - "end": "Arrow" - }, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - } - }, - "38e9e750-16c2-4476-93ab-21aeb5f8858f": { - "id": "38e9e750-16c2-4476-93ab-21aeb5f8858f", - "type": "text", - "name": "Text", - "parentId": "page1", - "childIndex": 12, - "point": [207.16, 1422.4], - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - }, - "text": "Hello", - "scale": 1 - }, - "5ba998df-c036-447a-9b88-d96c71394f52": { - "id": "5ba998df-c036-447a-9b88-d96c71394f52", - "type": "text", - "name": "Text", - "parentId": "page1", - "childIndex": 13, - "point": [389.57, 1496.5], - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - }, - "text": "Hello", - "scale": 1 - }, - "3c688979-b190-4270-915b-7d8dd22a2bb7": { - "id": "3c688979-b190-4270-915b-7d8dd22a2bb7", - "type": "text", - "name": "Text", - "parentId": "page1", - "childIndex": 14, - "point": [564.06, 1558.1], - "rotation": 0, - "style": { - "color": "Black", - "size": "Medium", - "isFilled": false, - "dash": "Draw" - }, - "text": "Hello", - "scale": 1 - } - } - } - }, - "code": { - "file0": { - "id": "file0", - "name": "index.ts", - "code": "\nconst draw = new Draw({\n points: [\n ...Utils.getPointsBetween([0, 0], [20, 50]),\n ...Utils.getPointsBetween([20, 50], [100, 20], 3),\n ...Utils.getPointsBetween([100, 20], [100, 100], 10),\n [100, 100],\n ],\n})\n\nconst rectangle = new Rectangle({\n point: [200, 0],\n style: {\n color: ColorStyle.Blue,\n },\n})\n\nconst ellipse = new Ellipse({\n point: [400, 0],\n})\n\nconst arrow = new Arrow({\n start: [600, 0],\n end: [700, 100],\n})\n\nconst radius = 1000\nconst count = 100\nconst center = [350, 50]\n\nfor (let i = 0; i < count; i++) {\n const point = Vec.rotWith(\n Vec.add(center, [radius, 0]),\n center,\n (Math.PI * 2 * i) / count\n )\n\n const dot = new Dot({\n point,\n })\n}\n " - } - } - }, - "pageState": { - "id": "page1", - "camera": { - "point": [0, -145], - "zoom": 1 - }, - "selectedIds": {} - } -} diff --git a/__tests__/__snapshots__/code.test.ts.snap b/__tests__/__snapshots__/code.test.ts.snap deleted file mode 100644 index 0f851d5c8..000000000 --- a/__tests__/__snapshots__/code.test.ts.snap +++ /dev/null @@ -1,280 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`selection creates a code control: generated code controls from code 1`] = ` -Object { - "test-number-control": Object { - "id": "test-number-control", - "label": "x", - "step": 1, - "type": "number", - "value": 0, - }, -} -`; - -exports[`selection generates a draw shape: generated draw from code 1`] = ` -Array [ - Object { - "childIndex": 1, - "id": "test-draw", - "isGenerated": true, - "name": "Test draw", - "parentId": "page1", - "point": Array [ - 0, - 0, - ], - "points": Array [ - Array [ - 100, - 100, - ], - Array [ - 200, - 200, - ], - Array [ - 300, - 300, - ], - ], - "rotation": 0, - "style": Object { - "color": "Red", - "dash": "Dotted", - "isFilled": false, - "size": "Medium", - }, - "type": "draw", - }, -] -`; - -exports[`selection generates a rectangle shape: generated rectangle from code 1`] = ` -Array [ - Object { - "childIndex": 1, - "id": "test-rectangle", - "isGenerated": true, - "name": "Test Rectangle", - "parentId": "page1", - "point": Array [ - 100, - 100, - ], - "radius": 2, - "rotation": 0, - "size": Array [ - 200, - 200, - ], - "style": Object { - "color": "Red", - "dash": "Dotted", - "isFilled": false, - "size": "Medium", - }, - "type": "rectangle", - }, -] -`; - -exports[`selection generates a text shape: generated draw from code 1`] = ` -Array [ - Object { - "childIndex": 1, - "id": "test-text", - "isGenerated": true, - "name": "Test text", - "parentId": "page1", - "point": Array [ - 100, - 100, - ], - "rotation": 0, - "scale": 1, - "style": Object { - "color": "Red", - "dash": "Dotted", - "isFilled": false, - "size": "Large", - }, - "text": "Hello world!", - "type": "text", - }, -] -`; - -exports[`selection generates an arrow shape: generated draw from code 1`] = ` -Array [ - Object { - "bend": 0, - "childIndex": 1, - "decorations": Object { - "end": "Arrow", - "middle": null, - "start": null, - }, - "handles": Object { - "bend": Object { - "id": "bend", - "index": 2, - "point": Array [ - 50, - 50, - ], - }, - "end": Object { - "id": "end", - "index": 1, - "point": Array [ - 100, - 100, - ], - }, - "start": Object { - "id": "start", - "index": 0, - "point": Array [ - 0, - 0, - ], - }, - }, - "id": "test-draw", - "isGenerated": true, - "name": "Test draw", - "parentId": "page1", - "point": Array [ - 0, - 0, - ], - "points": Array [ - Array [ - 100, - 100, - ], - Array [ - 200, - 200, - ], - Array [ - 300, - 300, - ], - ], - "rotation": 0, - "style": Object { - "color": "Red", - "dash": "Dotted", - "isFilled": false, - "size": "Medium", - }, - "type": "arrow", - }, -] -`; - -exports[`selection generates an ellipse shape: generated ellipse from code 1`] = ` -Array [ - Object { - "childIndex": 1, - "id": "test-ellipse", - "isGenerated": true, - "name": "Test ellipse", - "parentId": "page1", - "point": Array [ - 100, - 100, - ], - "radiusX": 100, - "radiusY": 200, - "rotation": 0, - "style": Object { - "color": "Red", - "dash": "Dotted", - "isFilled": false, - "size": "Medium", - }, - "type": "ellipse", - }, -] -`; - -exports[`selection generates shapes: generated rectangle from code 1`] = ` -Array [ - Object { - "childIndex": 1, - "id": "test-rectangle", - "isGenerated": true, - "name": "Test Rectangle", - "parentId": "page1", - "point": Array [ - 100, - 100, - ], - "radius": 2, - "rotation": 0, - "size": Array [ - 200, - 200, - ], - "style": Object { - "color": "Red", - "dash": "Dotted", - "isFilled": false, - "size": "Medium", - }, - "type": "rectangle", - }, -] -`; - -exports[`selection updates a code control: data in state after changing control 1`] = ` -Object { - "test-number-control": Object { - "id": "test-number-control", - "label": "x", - "step": 1, - "type": "number", - "value": 100, - }, - "test-vector-control": Object { - "id": "test-vector-control", - "isNormalized": false, - "label": "size", - "type": "vector", - "value": Array [ - 0, - 0, - ], - }, -} -`; - -exports[`selection updates a code control: rectangle in state after changing code control 1`] = ` -Object { - "childIndex": 1, - "id": "test-rectangle", - "isGenerated": true, - "name": "Test Rectangle", - "parentId": "page1", - "point": Array [ - 0, - 100, - ], - "radius": 2, - "rotation": 0, - "size": Array [ - 0, - 0, - ], - "style": Object { - "color": "Red", - "dash": "Dotted", - "isFilled": false, - "size": "Medium", - }, - "type": "rectangle", -} -`; diff --git a/__tests__/__snapshots__/dashes.test.ts.snap b/__tests__/__snapshots__/dashes.test.ts.snap deleted file mode 100644 index 409a3a653..000000000 --- a/__tests__/__snapshots__/dashes.test.ts.snap +++ /dev/null @@ -1,57 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`ellipse dash props renders dashed props on a circle correctly: large dashed circle dash props 1`] = ` -Object { - "strokeDasharray": "16 17.333333333333332", - "strokeDashoffset": "8", -} -`; - -exports[`ellipse dash props renders dashed props on a circle correctly: large dashed ellipse dash props 1`] = ` -Object { - "strokeDasharray": "16 17.333333333333332", - "strokeDashoffset": "8", -} -`; - -exports[`ellipse dash props renders dashed props on a circle correctly: small dashed circle dash props 1`] = ` -Object { - "strokeDasharray": "8 8.666666666666666", - "strokeDashoffset": "4", -} -`; - -exports[`ellipse dash props renders dashed props on a circle correctly: small dashed ellipse dash props 1`] = ` -Object { - "strokeDasharray": "8 8.666666666666666", - "strokeDashoffset": "4", -} -`; - -exports[`ellipse dash props renders dotted props on a circle correctly: large dotted circle dash props 1`] = ` -Object { - "strokeDasharray": "0.08 16.586666666666666", - "strokeDashoffset": "0", -} -`; - -exports[`ellipse dash props renders dotted props on a circle correctly: large dotted ellipse dash props 1`] = ` -Object { - "strokeDasharray": "0.08 16.586666666666666", - "strokeDashoffset": "0", -} -`; - -exports[`ellipse dash props renders dotted props on a circle correctly: small dotted circle dash props 1`] = ` -Object { - "strokeDasharray": "0.04 8.293333333333333", - "strokeDashoffset": "0", -} -`; - -exports[`ellipse dash props renders dotted props on a circle correctly: small dotted ellipse dash props 1`] = ` -Object { - "strokeDasharray": "0.04 8.293333333333333", - "strokeDashoffset": "0", -} -`; diff --git a/__tests__/__snapshots__/project.test.ts.snap b/__tests__/__snapshots__/project.test.ts.snap deleted file mode 100644 index 9c0ee0649..000000000 --- a/__tests__/__snapshots__/project.test.ts.snap +++ /dev/null @@ -1,809 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`project loads file from json: data after mount from file 1`] = ` -Object { - "code": Object { - "file0": Object { - "code": " -const draw = new Draw({ - points: [ - ...Utils.getPointsBetween([0, 0], [20, 50]), - ...Utils.getPointsBetween([20, 50], [100, 20], 3), - ...Utils.getPointsBetween([100, 20], [100, 100], 10), - [100, 100], - ], -}) - -const rectangle = new Rectangle({ - point: [200, 0], - style: { - color: ColorStyle.Blue, - }, -}) - -const ellipse = new Ellipse({ - point: [400, 0], -}) - -const arrow = new Arrow({ - start: [600, 0], - end: [700, 100], -}) - -const radius = 1000 -const count = 100 -const center = [350, 50] - -for (let i = 0; i < count; i++) { - const point = Vec.rotWith( - Vec.add(center, [radius, 0]), - center, - (Math.PI * 2 * i) / count - ) - - const dot = new Dot({ - point, - }) -} - ", - "id": "file0", - "name": "index.ts", - }, - }, - "id": "TESTING", - "name": "My Document", - "pages": Object { - "page1": Object { - "childIndex": 0, - "id": "page1", - "name": "Page 1", - "shapes": Object { - "13448777-d8f5-46cd-8a70-a4259211902e": Object { - "childIndex": 4, - "id": "13448777-d8f5-46cd-8a70-a4259211902e", - "name": "Rectangle", - "parentId": "page1", - "point": Array [ - 500, - 400, - ], - "radius": 2, - "rotation": 0, - "size": Array [ - 200, - 200, - ], - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "rectangle", - }, - "2d842ace-ebc5-4e83-acdf-de29352e5e62": Object { - "bend": 0, - "childIndex": 10, - "decorations": Object { - "end": "Arrow", - "middle": null, - "start": null, - }, - "handles": Object { - "bend": Object { - "id": "bend", - "index": 2, - "point": Array [ - 1.2250000000000227, - 92.60000000000002, - ], - }, - "end": Object { - "id": "end", - "index": 1, - "point": Array [ - 2.4500000000000455, - 185.20000000000005, - ], - }, - "start": Object { - "id": "start", - "index": 0, - "point": Array [ - 0, - 0, - ], - }, - }, - "id": "2d842ace-ebc5-4e83-acdf-de29352e5e62", - "name": "Arrow", - "parentId": "page1", - "point": Array [ - 616.9, - 1124.3, - ], - "rotation": 0, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "arrow", - }, - "38e9e750-16c2-4476-93ab-21aeb5f8858f": Object { - "childIndex": 12, - "id": "38e9e750-16c2-4476-93ab-21aeb5f8858f", - "name": "Text", - "parentId": "page1", - "point": Array [ - 207.16, - 1422.4, - ], - "rotation": 0, - "scale": 1, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "text": "Hello", - "type": "text", - }, - "3c688979-b190-4270-915b-7d8dd22a2bb7": Object { - "childIndex": 14, - "id": "3c688979-b190-4270-915b-7d8dd22a2bb7", - "name": "Text", - "parentId": "page1", - "point": Array [ - 564.06, - 1558.1, - ], - "rotation": 0, - "scale": 1, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "text": "Hello", - "type": "text", - }, - "51641de1-9787-41b8-afcc-2c85fd1b24c7": Object { - "childIndex": 7, - "id": "51641de1-9787-41b8-afcc-2c85fd1b24c7", - "name": "Ellipse", - "parentId": "page1", - "point": Array [ - 517.18, - 783.54, - ], - "radiusX": 102.99999999999997, - "radiusY": 102.99999999999994, - "rotation": 0, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "ellipse", - }, - "5ba998df-c036-447a-9b88-d96c71394f52": Object { - "childIndex": 13, - "id": "5ba998df-c036-447a-9b88-d96c71394f52", - "name": "Text", - "parentId": "page1", - "point": Array [ - 389.57, - 1496.5, - ], - "rotation": 0, - "scale": 1, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "text": "Hello", - "type": "text", - }, - "75010635-8dfb-48ea-9250-719e50e58f02": Object { - "childIndex": 5, - "id": "75010635-8dfb-48ea-9250-719e50e58f02", - "name": "Rectangle", - "parentId": "page1", - "point": Array [ - 384.09, - 378.45, - ], - "radius": 2, - "rotation": 0, - "size": Array [ - 95.20999999999992, - 91.1799999999999, - ], - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "rectangle", - }, - "b8e4e2c5-c662-4587-bf80-b9820ad8ad7f": Object { - "bend": 0, - "childIndex": 11, - "decorations": Object { - "end": "Arrow", - "middle": null, - "start": null, - }, - "handles": Object { - "bend": Object { - "id": "bend", - "index": 2, - "point": Array [ - 0.9250000000000114, - 47.85000000000002, - ], - }, - "end": Object { - "id": "end", - "index": 1, - "point": Array [ - 1.8500000000000227, - 95.70000000000005, - ], - }, - "start": Object { - "id": "start", - "index": 0, - "point": Array [ - 0, - 0, - ], - }, - }, - "id": "b8e4e2c5-c662-4587-bf80-b9820ad8ad7f", - "name": "Arrow", - "parentId": "page1", - "point": Array [ - 425.18, - 1143.2, - ], - "rotation": 0, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "arrow", - }, - "c892d665-3311-4e25-a0bf-c4632d777f7e": Object { - "childIndex": 6, - "id": "c892d665-3311-4e25-a0bf-c4632d777f7e", - "name": "Ellipse", - "parentId": "page1", - "point": Array [ - 162.45, - 679.23, - ], - "radiusX": 102.99999999999997, - "radiusY": 102.99999999999994, - "rotation": 0, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "ellipse", - }, - "e08c415e-3db3-4d3b-878e-28ce693ec1b0": Object { - "childIndex": 8, - "id": "e08c415e-3db3-4d3b-878e-28ce693ec1b0", - "name": "Ellipse", - "parentId": "page1", - "point": Array [ - 398.99, - 810.79, - ], - "radiusX": 45.484999999999985, - "radiusY": 45.48499999999996, - "rotation": 0, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "ellipse", - }, - "e43559cb-6f41-4ae4-9c49-158ed1ad2f72": Object { - "childIndex": 3, - "id": "e43559cb-6f41-4ae4-9c49-158ed1ad2f72", - "name": "Rectangle", - "parentId": "page1", - "point": Array [ - 100, - 100, - ], - "radius": 2, - "rotation": 0, - "size": Array [ - 100, - 100, - ], - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "rectangle", - }, - "fee77127-e779-4576-882b-b1bf7c7e132f": Object { - "bend": 0, - "childIndex": 9, - "decorations": Object { - "end": "Arrow", - "middle": null, - "start": null, - }, - "handles": Object { - "bend": Object { - "id": "bend", - "index": 2, - "point": Array [ - 0.045000000000001705, - 104, - ], - }, - "end": Object { - "id": "end", - "index": 1, - "point": Array [ - 0.09000000000000341, - 208, - ], - }, - "start": Object { - "id": "start", - "index": 0, - "point": Array [ - 0, - 0, - ], - }, - }, - "id": "fee77127-e779-4576-882b-b1bf7c7e132f", - "name": "Arrow", - "parentId": "page1", - "point": Array [ - 252.85, - 1057.5, - ], - "rotation": 0, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "arrow", - }, - }, - "type": "page", - }, - }, -} -`; - -exports[`restoring project remounts the state after mutating the current state: data after re-mount from file 1`] = ` -Object { - "code": Object { - "file0": Object { - "code": " -const draw = new Draw({ - points: [ - ...Utils.getPointsBetween([0, 0], [20, 50]), - ...Utils.getPointsBetween([20, 50], [100, 20], 3), - ...Utils.getPointsBetween([100, 20], [100, 100], 10), - [100, 100], - ], -}) - -const rectangle = new Rectangle({ - point: [200, 0], - style: { - color: ColorStyle.Blue, - }, -}) - -const ellipse = new Ellipse({ - point: [400, 0], -}) - -const arrow = new Arrow({ - start: [600, 0], - end: [700, 100], -}) - -const radius = 1000 -const count = 100 -const center = [350, 50] - -for (let i = 0; i < count; i++) { - const point = Vec.rotWith( - Vec.add(center, [radius, 0]), - center, - (Math.PI * 2 * i) / count - ) - - const dot = new Dot({ - point, - }) -} - ", - "id": "file0", - "name": "index.ts", - }, - }, - "id": "TESTING", - "name": "My Document", - "pages": Object { - "page1": Object { - "childIndex": 0, - "id": "page1", - "name": "Page 1", - "shapes": Object { - "13448777-d8f5-46cd-8a70-a4259211902e": Object { - "childIndex": 4, - "id": "13448777-d8f5-46cd-8a70-a4259211902e", - "name": "Rectangle", - "parentId": "page1", - "point": Array [ - 500, - 400, - ], - "radius": 2, - "rotation": 0, - "size": Array [ - 200, - 200, - ], - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "rectangle", - }, - "2d842ace-ebc5-4e83-acdf-de29352e5e62": Object { - "bend": 0, - "childIndex": 10, - "decorations": Object { - "end": "Arrow", - "middle": null, - "start": null, - }, - "handles": Object { - "bend": Object { - "id": "bend", - "index": 2, - "point": Array [ - 1.2250000000000227, - 92.60000000000002, - ], - }, - "end": Object { - "id": "end", - "index": 1, - "point": Array [ - 2.4500000000000455, - 185.20000000000005, - ], - }, - "start": Object { - "id": "start", - "index": 0, - "point": Array [ - 0, - 0, - ], - }, - }, - "id": "2d842ace-ebc5-4e83-acdf-de29352e5e62", - "name": "Arrow", - "parentId": "page1", - "point": Array [ - 616.9, - 1124.3, - ], - "rotation": 0, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "arrow", - }, - "38e9e750-16c2-4476-93ab-21aeb5f8858f": Object { - "childIndex": 12, - "id": "38e9e750-16c2-4476-93ab-21aeb5f8858f", - "name": "Text", - "parentId": "page1", - "point": Array [ - 207.16, - 1422.4, - ], - "rotation": 0, - "scale": 1, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "text": "Hello", - "type": "text", - }, - "3c688979-b190-4270-915b-7d8dd22a2bb7": Object { - "childIndex": 14, - "id": "3c688979-b190-4270-915b-7d8dd22a2bb7", - "name": "Text", - "parentId": "page1", - "point": Array [ - 564.06, - 1558.1, - ], - "rotation": 0, - "scale": 1, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "text": "Hello", - "type": "text", - }, - "51641de1-9787-41b8-afcc-2c85fd1b24c7": Object { - "childIndex": 7, - "id": "51641de1-9787-41b8-afcc-2c85fd1b24c7", - "name": "Ellipse", - "parentId": "page1", - "point": Array [ - 517.18, - 783.54, - ], - "radiusX": 102.99999999999997, - "radiusY": 102.99999999999994, - "rotation": 0, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "ellipse", - }, - "5ba998df-c036-447a-9b88-d96c71394f52": Object { - "childIndex": 13, - "id": "5ba998df-c036-447a-9b88-d96c71394f52", - "name": "Text", - "parentId": "page1", - "point": Array [ - 389.57, - 1496.5, - ], - "rotation": 0, - "scale": 1, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "text": "Hello", - "type": "text", - }, - "75010635-8dfb-48ea-9250-719e50e58f02": Object { - "childIndex": 5, - "id": "75010635-8dfb-48ea-9250-719e50e58f02", - "name": "Rectangle", - "parentId": "page1", - "point": Array [ - 384.09, - 378.45, - ], - "radius": 2, - "rotation": 0, - "size": Array [ - 95.20999999999992, - 91.1799999999999, - ], - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "rectangle", - }, - "b8e4e2c5-c662-4587-bf80-b9820ad8ad7f": Object { - "bend": 0, - "childIndex": 11, - "decorations": Object { - "end": "Arrow", - "middle": null, - "start": null, - }, - "handles": Object { - "bend": Object { - "id": "bend", - "index": 2, - "point": Array [ - 0.9250000000000114, - 47.85000000000002, - ], - }, - "end": Object { - "id": "end", - "index": 1, - "point": Array [ - 1.8500000000000227, - 95.70000000000005, - ], - }, - "start": Object { - "id": "start", - "index": 0, - "point": Array [ - 0, - 0, - ], - }, - }, - "id": "b8e4e2c5-c662-4587-bf80-b9820ad8ad7f", - "name": "Arrow", - "parentId": "page1", - "point": Array [ - 425.18, - 1143.2, - ], - "rotation": 0, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "arrow", - }, - "c892d665-3311-4e25-a0bf-c4632d777f7e": Object { - "childIndex": 6, - "id": "c892d665-3311-4e25-a0bf-c4632d777f7e", - "name": "Ellipse", - "parentId": "page1", - "point": Array [ - 162.45, - 679.23, - ], - "radiusX": 102.99999999999997, - "radiusY": 102.99999999999994, - "rotation": 0, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "ellipse", - }, - "e08c415e-3db3-4d3b-878e-28ce693ec1b0": Object { - "childIndex": 8, - "id": "e08c415e-3db3-4d3b-878e-28ce693ec1b0", - "name": "Ellipse", - "parentId": "page1", - "point": Array [ - 398.99, - 810.79, - ], - "radiusX": 45.484999999999985, - "radiusY": 45.48499999999996, - "rotation": 0, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "ellipse", - }, - "e43559cb-6f41-4ae4-9c49-158ed1ad2f72": Object { - "childIndex": 3, - "id": "e43559cb-6f41-4ae4-9c49-158ed1ad2f72", - "name": "Rectangle", - "parentId": "page1", - "point": Array [ - 100, - 100, - ], - "radius": 2, - "rotation": 0, - "size": Array [ - 100, - 100, - ], - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "rectangle", - }, - "fee77127-e779-4576-882b-b1bf7c7e132f": Object { - "bend": 0, - "childIndex": 9, - "decorations": Object { - "end": "Arrow", - "middle": null, - "start": null, - }, - "handles": Object { - "bend": Object { - "id": "bend", - "index": 2, - "point": Array [ - 0.045000000000001705, - 104, - ], - }, - "end": Object { - "id": "end", - "index": 1, - "point": Array [ - 0.09000000000000341, - 208, - ], - }, - "start": Object { - "id": "start", - "index": 0, - "point": Array [ - 0, - 0, - ], - }, - }, - "id": "fee77127-e779-4576-882b-b1bf7c7e132f", - "name": "Arrow", - "parentId": "page1", - "point": Array [ - 252.85, - 1057.5, - ], - "rotation": 0, - "style": Object { - "color": "Black", - "dash": "Draw", - "isFilled": false, - "size": "Medium", - }, - "type": "arrow", - }, - }, - "type": "page", - }, - }, -} -`; diff --git a/__tests__/bounds.test.ts b/__tests__/bounds.test.ts deleted file mode 100644 index fee0821c3..000000000 --- a/__tests__/bounds.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { getShapeUtils } from 'state/shape-utils' -import { getCommonBounds } from 'utils' -import TestState, { arrowId, rectangleId } from './test-utils' - -describe('selection', () => { - const tt = new TestState() - - it('measures correct bounds for selected item', () => { - // Note: Each item should test its own bounds in its ./shapes/[shape].tsx file - - const shape = tt.getShape(rectangleId) - - tt.deselectAll().clickShape(rectangleId) - - expect(tt.state.values.selectedBounds).toStrictEqual( - getShapeUtils(shape).getBounds(shape) - ) - }) - - it('measures correct bounds for rotated selected item', () => { - const shape = tt.getShape(rectangleId) - - getShapeUtils(shape).rotateBy(shape, Math.PI * 2 * Math.random()) - - tt.deselectAll().clickShape(rectangleId) - - expect(tt.state.values.selectedBounds).toStrictEqual( - getShapeUtils(shape).getBounds(shape) - ) - - getShapeUtils(shape).rotateBy(shape, -Math.PI * 2 * Math.random()) - - expect(tt.state.values.selectedBounds).toStrictEqual( - getShapeUtils(shape).getBounds(shape) - ) - }) - - it('measures correct bounds for selected items', () => { - const shape1 = tt.getShape(rectangleId) - const shape2 = tt.getShape(arrowId) - - tt.deselectAll() - .clickShape(shape1.id) - .clickShape(shape2.id, { shiftKey: true }) - - expect(tt.state.values.selectedBounds).toStrictEqual( - getCommonBounds( - getShapeUtils(shape1).getRotatedBounds(shape1), - getShapeUtils(shape2).getRotatedBounds(shape2) - ) - ) - }) - - it('measures correct bounds for rotated selected items', () => { - const shape1 = tt.getShape(rectangleId) - const shape2 = tt.getShape(arrowId) - - getShapeUtils(shape1).rotateBy(shape1, Math.PI * 2 * Math.random()) - getShapeUtils(shape2).rotateBy(shape2, Math.PI * 2 * Math.random()) - - tt.deselectAll() - .clickShape(shape1.id) - .clickShape(shape2.id, { shiftKey: true }) - - expect(tt.state.values.selectedBounds).toStrictEqual( - getCommonBounds( - getShapeUtils(shape1).getRotatedBounds(shape1), - getShapeUtils(shape2).getRotatedBounds(shape2) - ) - ) - }) -}) diff --git a/__tests__/children.test.ts b/__tests__/children.test.ts deleted file mode 100644 index 98f3e5dc9..000000000 --- a/__tests__/children.test.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { MoveType, ShapeType } from 'types' -import TestState from './test-utils' - -describe('shapes with children', () => { - const tt = new TestState() - - tt.resetDocumentState() - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 0], - size: [100, 100], - childIndex: 1, - }, - 'delete-me-bottom' - ) - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 0], - size: [100, 100], - childIndex: 2, - }, - '1' - ) - .createShape( - { - type: ShapeType.Rectangle, - point: [300, 0], - size: [100, 100], - childIndex: 3, - }, - '2' - ) - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 300], - size: [100, 100], - childIndex: 4, - }, - 'delete-me-middle' - ) - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 300], - size: [100, 100], - childIndex: 5, - }, - '3' - ) - .createShape( - { - type: ShapeType.Rectangle, - point: [300, 300], - size: [100, 100], - childIndex: 6, - }, - '4' - ) - - // Delete shapes at the start and in the middle of the list - - tt.clickShape('delete-me-bottom') - .send('DELETED') - .clickShape('delete-me-middle') - .send('DELETED') - - it('has shapes in order', () => { - expect( - Object.values(tt.data.document.pages[tt.data.currentParentId].shapes) - .sort((a, b) => a.childIndex - b.childIndex) - .map((shape) => shape.childIndex) - ).toStrictEqual([2, 3, 5, 6]) - }) - - it('moves a shape to back', () => { - tt.clickShape('3').send('MOVED', { - type: MoveType.ToBack, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['3', '1', '2', '4']) - }) - - it('moves two adjacent siblings to back', () => { - tt.clickShape('4').clickShape('2', { shiftKey: true }).send('MOVED', { - type: MoveType.ToBack, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['2', '4', '3', '1']) - }) - - it('moves two non-adjacent siblings to back', () => { - tt.clickShape('4').clickShape('1', { shiftKey: true }).send('MOVED', { - type: MoveType.ToBack, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['4', '1', '2', '3']) - }) - - it('moves a shape backward', () => { - tt.clickShape('3').send('MOVED', { - type: MoveType.Backward, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['4', '1', '3', '2']) - }) - - it('moves a shape at first index backward', () => { - tt.clickShape('4').send('MOVED', { - type: MoveType.Backward, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['4', '1', '3', '2']) - }) - - it('moves two adjacent siblings backward', () => { - tt.clickShape('3').clickShape('2', { shiftKey: true }).send('MOVED', { - type: MoveType.Backward, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['4', '3', '2', '1']) - }) - - it('moves two non-adjacent siblings backward', () => { - tt.clickShape('3') - .clickShape('1', { shiftKey: true }) - .send('MOVED', { type: MoveType.Backward }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['3', '4', '1', '2']) - }) - - it('moves two adjacent siblings backward at zero index', () => { - tt.clickShape('3').clickShape('4', { shiftKey: true }).send('MOVED', { - type: MoveType.Backward, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['3', '4', '1', '2']) - }) - - it('moves a shape forward', () => { - tt.clickShape('4').send('MOVED', { - type: MoveType.Forward, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['3', '1', '4', '2']) - }) - - it('moves a shape forward at the top index', () => { - tt.clickShape('2').send('MOVED', { - type: MoveType.Forward, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['3', '1', '4', '2']) - }) - - it('moves two adjacent siblings forward', () => { - tt.deselectAll() - .clickShape('4') - .clickShape('1', { shiftKey: true }) - .send('MOVED', { - type: MoveType.Forward, - }) - - expect(tt.idsAreSelected(['1', '4'])).toBe(true) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['3', '2', '1', '4']) - }) - - it('moves two non-adjacent siblings forward', () => { - tt.deselectAll() - .clickShape('3') - .clickShape('1', { shiftKey: true }) - .send('MOVED', { - type: MoveType.Forward, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['2', '3', '4', '1']) - }) - - it('moves two adjacent siblings forward at top index', () => { - tt.deselectAll() - .clickShape('3') - .clickShape('1', { shiftKey: true }) - .send('MOVED', { - type: MoveType.Forward, - }) - expect(tt.getSortedPageShapeIds()).toStrictEqual(['2', '4', '3', '1']) - }) - - it('moves a shape to front', () => { - tt.deselectAll().clickShape('2').send('MOVED', { - type: MoveType.ToFront, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['4', '3', '1', '2']) - }) - - it('moves two adjacent siblings to front', () => { - tt.deselectAll() - .clickShape('3') - .clickShape('1', { shiftKey: true }) - .send('MOVED', { - type: MoveType.ToFront, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['4', '2', '3', '1']) - }) - - it('moves two non-adjacent siblings to front', () => { - tt.deselectAll() - .clickShape('4') - .clickShape('3', { shiftKey: true }) - .send('MOVED', { - type: MoveType.ToFront, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['2', '1', '4', '3']) - }) - - it('moves siblings already at front to front', () => { - tt.deselectAll() - .clickShape('4') - .clickShape('3', { shiftKey: true }) - .send('MOVED', { - type: MoveType.ToFront, - }) - - expect(tt.getSortedPageShapeIds()).toStrictEqual(['2', '1', '4', '3']) - }) -}) diff --git a/__tests__/code.test.ts b/__tests__/code.test.ts deleted file mode 100644 index e37926766..000000000 --- a/__tests__/code.test.ts +++ /dev/null @@ -1,284 +0,0 @@ -import { generateFromCode } from 'state/code/generate' -import * as json from './__mocks__/document.json' -import TestState from './test-utils' - -jest.useRealTimers() - -const tt = new TestState() -tt.resetDocumentState() - .send('LOADED_FROM_FILE', { json: JSON.stringify(json) }) - .send('CLEARED_PAGE') - .save() - -describe('selection', () => { - it('opens and closes the code panel', () => { - expect(tt.data.settings.isCodeOpen).toBe(false) - tt.send('TOGGLED_CODE_PANEL_OPEN') - expect(tt.data.settings.isCodeOpen).toBe(true) - tt.send('TOGGLED_CODE_PANEL_OPEN') - expect(tt.data.settings.isCodeOpen).toBe(false) - }) - - it('saves changes to code', () => { - expect(tt.getSortedPageShapeIds().length).toBe(0) - - const code = `// hello world!` - - tt.send('SAVED_CODE', { code }) - - expect(tt.data.document.code[tt.data.currentCodeFileId].code).toBe(code) - }) - - it('generates shapes', async () => { - const code = ` - const rectangle = new Rectangle({ - id: "test-rectangle", - name: 'Test Rectangle', - point: [100, 100], - size: [200, 200], - style: { - size: SizeStyle.Medium, - color: ColorStyle.Red, - dash: DashStyle.Dotted, - }, - }) - ` - - const { controls, shapes } = await generateFromCode(tt.data, code) - - tt.send('GENERATED_FROM_CODE', { controls, shapes }) - - expect(tt.getShapes()).toMatchSnapshot('generated rectangle from code') - }) - - it('creates a code control', async () => { - const code = ` - new NumberControl({ - id: "test-number-control", - label: "x" - }) - ` - - const { controls, shapes } = await generateFromCode(tt.data, code) - - tt.send('GENERATED_FROM_CODE', { controls, shapes }) - - expect(tt.data.codeControls).toMatchSnapshot( - 'generated code controls from code' - ) - }) - - it('updates a code control', async () => { - const code = ` - new NumberControl({ - id: "test-number-control", - label: "x" - }) - - new VectorControl({ - id: "test-vector-control", - label: "size" - }) - - const rectangle = new Rectangle({ - id: "test-rectangle", - name: 'Test Rectangle', - point: [controls.x, 100], - size: controls.size, - style: { - size: SizeStyle.Medium, - color: ColorStyle.Red, - dash: DashStyle.Dotted, - }, - }) - ` - - const { controls, shapes } = await generateFromCode(tt.data, code) - - tt.send('GENERATED_FROM_CODE', { controls, shapes }) - - tt.send('CHANGED_CODE_CONTROL', { 'test-number-control': 100 }) - - expect(tt.data.codeControls).toMatchSnapshot( - 'data in state after changing control' - ) - - expect(tt.getShape('test-rectangle')).toMatchSnapshot( - 'rectangle in state after changing code control' - ) - }) - - /* -------------------- Readonly -------------------- */ - - it('does not saves changes to code when readonly', () => { - tt.send('CLEARED_PAGE') - - expect(tt.getShapes().length).toBe(0) - - const code = `// hello world!` - - tt.send('SAVED_CODE', { code }) - .send('TOGGLED_READ_ONLY') - .send('SAVED_CODE', { code: '' }) - - expect(tt.data.document.code[tt.data.currentCodeFileId].code).toBe(code) - - tt.send('TOGGLED_READ_ONLY').send('SAVED_CODE', { code: '' }) - - expect(tt.data.document.code[tt.data.currentCodeFileId].code).toBe('') - }) - - /* --------------------- Methods -------------------- */ - - it('moves shape to front', async () => { - null - }) - - it('moves shape forward', async () => { - null - }) - - it('moves shape backward', async () => { - null - }) - - it('moves shape to back', async () => { - null - }) - - it('rotates a shape', async () => { - null - }) - - it('rotates a shape by a delta', async () => { - null - }) - - it('translates a shape', async () => { - null - }) - - it('translates a shape by a delta', async () => { - null - }) - - /* --------------------- Shapes --------------------- */ - - it('generates a rectangle shape', async () => { - tt.send('CLEARED_PAGE') - const code = ` - const rectangle = new Rectangle({ - id: "test-rectangle", - name: 'Test Rectangle', - point: [100, 100], - size: [200, 200], - style: { - size: SizeStyle.Medium, - color: ColorStyle.Red, - dash: DashStyle.Dotted, - }, - }) - ` - - const { controls, shapes } = await generateFromCode(tt.data, code) - - tt.send('GENERATED_FROM_CODE', { controls, shapes }) - - expect(tt.getShapes()).toMatchSnapshot('generated rectangle from code') - }) - - it('changes a rectangle size', async () => { - null - }) - - it('generates an ellipse shape', async () => { - tt.send('CLEARED_PAGE') - const code = ` - const ellipse = new Ellipse({ - id: 'test-ellipse', - name: 'Test ellipse', - point: [100, 100], - radiusX: 100, - radiusY: 200, - style: { - size: SizeStyle.Medium, - color: ColorStyle.Red, - dash: DashStyle.Dotted, - }, - }) - ` - - const { controls, shapes } = await generateFromCode(tt.data, code) - - tt.send('GENERATED_FROM_CODE', { controls, shapes }) - - expect(tt.getShapes()).toMatchSnapshot('generated ellipse from code') - }) - - it('generates a draw shape', async () => { - tt.send('CLEARED_PAGE') - const code = ` - const ellipse = new Draw({ - id: 'test-draw', - name: 'Test draw', - points: [[100, 100], [200,200], [300,300]], - style: { - size: SizeStyle.Medium, - color: ColorStyle.Red, - dash: DashStyle.Dotted, - }, - }) - ` - - const { controls, shapes } = await generateFromCode(tt.data, code) - - tt.send('GENERATED_FROM_CODE', { controls, shapes }) - - expect(tt.getShapes()).toMatchSnapshot('generated draw from code') - }) - - it('generates an arrow shape', async () => { - tt.send('CLEARED_PAGE') - const code = ` - const draw = new Arrow({ - id: 'test-draw', - name: 'Test draw', - points: [[100, 100], [200,200], [300,300]], - style: { - size: SizeStyle.Medium, - color: ColorStyle.Red, - dash: DashStyle.Dotted, - }, - }) - ` - - const { controls, shapes } = await generateFromCode(tt.data, code) - - tt.send('GENERATED_FROM_CODE', { controls, shapes }) - - expect(tt.getShapes()).toMatchSnapshot('generated draw from code') - }) - - it('generates a text shape', async () => { - tt.send('CLEARED_PAGE') - const code = ` - const text = new Text({ - id: 'test-text', - name: 'Test text', - point: [100, 100], - text: 'Hello world!', - style: { - size: SizeStyle.Large, - color: ColorStyle.Red, - dash: DashStyle.Dotted, - }, - }) - ` - - const { controls, shapes } = await generateFromCode(tt.data, code) - - tt.send('GENERATED_FROM_CODE', { controls, shapes }) - - expect(tt.getShapes()).toMatchSnapshot('generated draw from code') - }) -}) diff --git a/__tests__/commands/__snapshots__/transform.test.ts.snap b/__tests__/commands/__snapshots__/transform.test.ts.snap deleted file mode 100644 index cd0c460ac..000000000 --- a/__tests__/commands/__snapshots__/transform.test.ts.snap +++ /dev/null @@ -1,852 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`transform command snapshot tests shift-transforms corners 1`] = ` -Object { - "height": 593.73, - "maxX": 700, - "maxY": 600, - "minX": -12.476, - "minY": 6.27, - "width": 712.476, -} -`; - -exports[`transform command snapshot tests shift-transforms corners 2`] = ` -Object { - "rect1": Object { - "point": Array [ - -12.476, - 6.27, - ], - "size": Array [ - 118.75, - 118.75, - ], - }, - "rect2": Object { - "point": Array [ - 462.51, - 362.51, - ], - "size": Array [ - 237.49, - 237.49, - ], - }, -} -`; - -exports[`transform command snapshot tests shift-transforms corners 3`] = ` -Object { - "height": 531.6320000000001, - "maxX": 737.9599999999999, - "maxY": 600, - "minX": 100, - "minY": 68.368, - "width": 637.9599999999999, -} -`; - -exports[`transform command snapshot tests shift-transforms corners 4`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 68.368, - ], - "size": Array [ - 106.33, - 106.33, - ], - }, - "rect2": Object { - "point": Array [ - 525.31, - 387.35, - ], - "size": Array [ - 212.65, - 212.65, - ], - }, -} -`; - -exports[`transform command snapshot tests shift-transforms corners 5`] = ` -Object { - "height": 533.62, - "maxX": 740.3499999999999, - "maxY": 633.62, - "minX": 100, - "minY": 100, - "width": 640.3499999999999, -} -`; - -exports[`transform command snapshot tests shift-transforms corners 6`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 100, - ], - "size": Array [ - 106.72, - 106.72, - ], - }, - "rect2": Object { - "point": Array [ - 526.9, - 420.17, - ], - "size": Array [ - 213.45, - 213.45, - ], - }, -} -`; - -exports[`transform command snapshot tests shift-transforms corners 7`] = ` -Object { - "height": 490.52, - "maxX": 700, - "maxY": 590.52, - "minX": 111.38, - "minY": 100, - "width": 588.62, -} -`; - -exports[`transform command snapshot tests shift-transforms corners 8`] = ` -Object { - "rect1": Object { - "point": Array [ - 111.38, - 100, - ], - "size": Array [ - 98.104, - 98.104, - ], - }, - "rect2": Object { - "point": Array [ - 503.79, - 394.31, - ], - "size": Array [ - 196.21, - 196.21, - ], - }, -} -`; - -exports[`transform command snapshot tests shift-transforms edges 1`] = ` -Object { - "height": 593.73, - "maxX": 756.24, - "maxY": 600, - "minX": 43.762, - "minY": 6.27, - "width": 712.4780000000001, -} -`; - -exports[`transform command snapshot tests shift-transforms edges 2`] = ` -Object { - "rect1": Object { - "point": Array [ - 43.762, - 6.27, - ], - "size": Array [ - 118.75, - 118.75, - ], - }, - "rect2": Object { - "point": Array [ - 518.75, - 362.51, - ], - "size": Array [ - 237.49, - 237.49, - ], - }, -} -`; - -exports[`transform command snapshot tests shift-transforms edges 3`] = ` -Object { - "height": 531.6260000000001, - "maxX": 737.9599999999999, - "maxY": 615.8100000000001, - "minX": 100, - "minY": 84.184, - "width": 637.9599999999999, -} -`; - -exports[`transform command snapshot tests shift-transforms edges 4`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 84.184, - ], - "size": Array [ - 106.33, - 106.33, - ], - }, - "rect2": Object { - "point": Array [ - 525.31, - 403.16, - ], - "size": Array [ - 212.65, - 212.65, - ], - }, -} -`; - -exports[`transform command snapshot tests shift-transforms edges 5`] = ` -Object { - "height": 411.35, - "maxX": 646.81, - "maxY": 511.35, - "minX": 153.19, - "minY": 100, - "width": 493.61999999999995, -} -`; - -exports[`transform command snapshot tests shift-transforms edges 6`] = ` -Object { - "rect1": Object { - "point": Array [ - 153.19, - 100, - ], - "size": Array [ - 82.269, - 82.269, - ], - }, - "rect2": Object { - "point": Array [ - 482.27, - 346.81, - ], - "size": Array [ - 164.54, - 164.54, - ], - }, -} -`; - -exports[`transform command snapshot tests shift-transforms edges 7`] = ` -Object { - "height": 490.52, - "maxX": 700, - "maxY": 595.26, - "minX": 111.38, - "minY": 104.74, - "width": 588.62, -} -`; - -exports[`transform command snapshot tests shift-transforms edges 8`] = ` -Object { - "rect1": Object { - "point": Array [ - 111.38, - 104.74, - ], - "size": Array [ - 98.104, - 98.104, - ], - }, - "rect2": Object { - "point": Array [ - 503.79, - 399.05, - ], - "size": Array [ - 196.21, - 196.21, - ], - }, -} -`; - -exports[`transform command snapshot tests transforms corners 1`] = ` -Object { - "height": 593.73, - "maxX": 700, - "maxY": 600, - "minX": 27.892, - "minY": 6.27, - "width": 672.108, -} -`; - -exports[`transform command snapshot tests transforms corners 2`] = ` -Object { - "rect1": Object { - "point": Array [ - 27.892, - 6.27, - ], - "size": Array [ - 112.02, - 118.75, - ], - }, - "rect2": Object { - "point": Array [ - 475.96, - 362.51, - ], - "size": Array [ - 224.04, - 237.49, - ], - }, -} -`; - -exports[`transform command snapshot tests transforms corners 3`] = ` -Object { - "height": 490.17, - "maxX": 737.9599999999999, - "maxY": 600, - "minX": 100, - "minY": 109.83, - "width": 637.9599999999999, -} -`; - -exports[`transform command snapshot tests transforms corners 4`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 109.83, - ], - "size": Array [ - 106.33, - 98.034, - ], - }, - "rect2": Object { - "point": Array [ - 525.31, - 403.93, - ], - "size": Array [ - 212.65, - 196.07, - ], - }, -} -`; - -exports[`transform command snapshot tests transforms corners 5`] = ` -Object { - "height": 411.35, - "maxX": 740.3499999999999, - "maxY": 511.35, - "minX": 100, - "minY": 100, - "width": 640.3499999999999, -} -`; - -exports[`transform command snapshot tests transforms corners 6`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 100, - ], - "size": Array [ - 106.72, - 82.269, - ], - }, - "rect2": Object { - "point": Array [ - 526.9, - 346.81, - ], - "size": Array [ - 213.45, - 164.54, - ], - }, -} -`; - -exports[`transform command snapshot tests transforms corners 7`] = ` -Object { - "height": 437.4, - "maxX": 700, - "maxY": 537.4, - "minX": 111.38, - "minY": 100, - "width": 588.62, -} -`; - -exports[`transform command snapshot tests transforms corners 8`] = ` -Object { - "rect1": Object { - "point": Array [ - 111.38, - 100, - ], - "size": Array [ - 98.104, - 87.479, - ], - }, - "rect2": Object { - "point": Array [ - 503.79, - 362.44, - ], - "size": Array [ - 196.21, - 174.96, - ], - }, -} -`; - -exports[`transform command snapshot tests transforms edges 1`] = ` -Object { - "height": 593.73, - "maxX": 700, - "maxY": 600, - "minX": 100, - "minY": 6.27, - "width": 600, -} -`; - -exports[`transform command snapshot tests transforms edges 2`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 6.27, - ], - "size": Array [ - 100, - 118.75, - ], - }, - "rect2": Object { - "point": Array [ - 500, - 362.51, - ], - "size": Array [ - 200, - 237.49, - ], - }, -} -`; - -exports[`transform command snapshot tests transforms edges 3`] = ` -Object { - "height": 500, - "maxX": 737.9599999999999, - "maxY": 600, - "minX": 100, - "minY": 100, - "width": 637.9599999999999, -} -`; - -exports[`transform command snapshot tests transforms edges 4`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 100, - ], - "size": Array [ - 106.33, - 100, - ], - }, - "rect2": Object { - "point": Array [ - 525.31, - 400, - ], - "size": Array [ - 212.65, - 200, - ], - }, -} -`; - -exports[`transform command snapshot tests transforms edges 5`] = ` -Object { - "height": 411.35, - "maxX": 700, - "maxY": 511.35, - "minX": 100, - "minY": 100, - "width": 600, -} -`; - -exports[`transform command snapshot tests transforms edges 6`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 100, - ], - "size": Array [ - 100, - 82.269, - ], - }, - "rect2": Object { - "point": Array [ - 500, - 346.81, - ], - "size": Array [ - 200, - 164.54, - ], - }, -} -`; - -exports[`transform command snapshot tests transforms edges 7`] = ` -Object { - "height": 500, - "maxX": 700, - "maxY": 600, - "minX": 111.38, - "minY": 100, - "width": 588.62, -} -`; - -exports[`transform command snapshot tests transforms edges 8`] = ` -Object { - "rect1": Object { - "point": Array [ - 111.38, - 100, - ], - "size": Array [ - 98.104, - 100, - ], - }, - "rect2": Object { - "point": Array [ - 503.79, - 400, - ], - "size": Array [ - 196.21, - 200, - ], - }, -} -`; - -exports[`transform command transforms from the bottom edge 1`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 100, - ], - "size": Array [ - 100, - 120, - ], - }, - "rect2": Object { - "point": Array [ - 500, - 460, - ], - "size": Array [ - 200, - 240, - ], - }, -} -`; - -exports[`transform command transforms from the bottom-left corner 1`] = ` -Object { - "rect1": Object { - "point": Array [ - 200, - 100, - ], - "size": Array [ - 83.333, - 120, - ], - }, - "rect2": Object { - "point": Array [ - 533.33, - 460, - ], - "size": Array [ - 166.67, - 240, - ], - }, -} -`; - -exports[`transform command transforms from the bottom-right corner 1`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 100, - ], - "size": Array [ - 116.67, - 120, - ], - }, - "rect2": Object { - "point": Array [ - 566.67, - 460, - ], - "size": Array [ - 233.33, - 240, - ], - }, -} -`; - -exports[`transform command transforms from the left edge 1`] = ` -Object { - "rect1": Object { - "point": Array [ - 200, - 100, - ], - "size": Array [ - 83.333, - 100, - ], - }, - "rect2": Object { - "point": Array [ - 533.33, - 400, - ], - "size": Array [ - 166.67, - 200, - ], - }, -} -`; - -exports[`transform command transforms from the right edge 1`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 100, - ], - "size": Array [ - 116.67, - 100, - ], - }, - "rect2": Object { - "point": Array [ - 566.67, - 400, - ], - "size": Array [ - 233.33, - 200, - ], - }, -} -`; - -exports[`transform command transforms from the top edge 1`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 200, - ], - "size": Array [ - 100, - 80, - ], - }, - "rect2": Object { - "point": Array [ - 500, - 440, - ], - "size": Array [ - 200, - 160, - ], - }, -} -`; - -exports[`transform command transforms from the top-left corner 1`] = ` -Object { - "rect1": Object { - "point": Array [ - 200, - 200, - ], - "size": Array [ - 83.333, - 80, - ], - }, - "rect2": Object { - "point": Array [ - 533.33, - 440, - ], - "size": Array [ - 166.67, - 160, - ], - }, -} -`; - -exports[`transform command transforms from the top-right corner 1`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 200, - ], - "size": Array [ - 116.67, - 80, - ], - }, - "rect2": Object { - "point": Array [ - 566.67, - 440, - ], - "size": Array [ - 233.33, - 160, - ], - }, -} -`; - -exports[`transform command when transforming from the bottom-right corner does command 1`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 100, - ], - "size": Array [ - 116.67, - 120, - ], - }, - "rect2": Object { - "point": Array [ - 566.67, - 460, - ], - "size": Array [ - 233.33, - 240, - ], - }, -} -`; - -exports[`transform command when transforming from the bottom-right corner re-does command 1`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 100, - ], - "size": Array [ - 116.67, - 120, - ], - }, - "rect2": Object { - "point": Array [ - 566.67, - 460, - ], - "size": Array [ - 233.33, - 240, - ], - }, -} -`; - -exports[`transform command when transforming from the bottom-right corner un-does command 1`] = ` -Object { - "rect1": Object { - "point": Array [ - 100, - 100, - ], - "size": Array [ - 100, - 100, - ], - }, - "rect2": Object { - "point": Array [ - 500, - 400, - ], - "size": Array [ - 200, - 200, - ], - }, -} -`; diff --git a/__tests__/commands/align.test.ts b/__tests__/commands/align.test.ts deleted file mode 100644 index cc2de7824..000000000 --- a/__tests__/commands/align.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import TestState from '../test-utils' - -describe('align command', () => { - const tt = new TestState() - tt.resetDocumentState() - - describe('when one item is selected', () => { - it('does command', () => { - // TODO - null - }) - - it('un-does command', () => { - // TODO - null - }) - - it('re-does command', () => { - // TODO - null - }) - }) - - describe('when multiple items are selected', () => { - it('does command', () => { - // TODO - null - }) - - it('un-does command', () => { - // TODO - null - }) - - it('re-does command', () => { - // TODO - null - }) - }) -}) diff --git a/__tests__/commands/change-page.test.ts b/__tests__/commands/change-page.test.ts deleted file mode 100644 index 266dddca8..000000000 --- a/__tests__/commands/change-page.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import TestState from '../test-utils' - -describe('change page command', () => { - const tt = new TestState() - tt.resetDocumentState() - - it('does command', () => { - // TODO - null - }) - - it('un-does command', () => { - // TODO - null - }) - - it('re-does command', () => { - // TODO - null - }) -}) diff --git a/__tests__/commands/create-page.test.ts b/__tests__/commands/create-page.test.ts deleted file mode 100644 index abdf36b65..000000000 --- a/__tests__/commands/create-page.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import TestState from '../test-utils' - -describe('create page command', () => { - const tt = new TestState() - tt.resetDocumentState().save() - - describe('creates a page', () => { - it('does command', () => { - expect(Object.keys(tt.data.document.pages).length).toBe(1) - - tt.send('CREATED_PAGE') - - expect(Object.keys(tt.data.document.pages).length).toBe(2) - }) - - it('changes to the new page', () => { - tt.restore().send('CREATED_PAGE') - - const pageId = Object.keys(tt.data.document.pages)[1] - - expect(tt.data.currentPageId).toBe(pageId) - }) - - it('un-does command', () => { - tt.restore().send('CREATED_PAGE').undo() - expect(Object.keys(tt.data.document.pages).length).toBe(1) - const pageId = Object.keys(tt.data.document.pages)[0] - expect(tt.data.currentPageId).toBe(pageId) - }) - - it('re-does command', () => { - tt.restore().send('CREATED_PAGE').undo().redo() - expect(Object.keys(tt.data.document.pages).length).toBe(2) - const pageId = Object.keys(tt.data.document.pages)[1] - expect(tt.data.currentPageId).toBe(pageId) - }) - }) -}) diff --git a/__tests__/commands/delete-page.test.ts b/__tests__/commands/delete-page.test.ts deleted file mode 100644 index 0c32877ba..000000000 --- a/__tests__/commands/delete-page.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import TestState from '../test-utils' - -describe('delete page command', () => { - const tt = new TestState() - tt.resetDocumentState().save() - - it('does command', () => { - tt.reset().restore().send('CREATED_PAGE') - expect(Object.keys(tt.data.document.pages).length).toBe(2) - - const pageId = Object.keys(tt.data.document.pages)[1] - tt.send('DELETED_PAGE', { id: pageId }) - - expect(Object.keys(tt.data.document.pages).length).toBe(1) - - const firstPageId = Object.keys(tt.data.document.pages)[0] - expect(tt.data.currentPageId).toBe(firstPageId) - }) - - it('un-does command', () => { - tt.reset().restore().send('CREATED_PAGE') - expect(Object.keys(tt.data.document.pages).length).toBe(2) - - const pageId = Object.keys(tt.data.document.pages)[1] - tt.send('DELETED_PAGE', { id: pageId }).undo() - - expect(Object.keys(tt.data.document.pages).length).toBe(2) - - expect(tt.data.currentPageId).toBe(pageId) - }) - - it('re-does command', () => { - tt.reset().restore().send('CREATED_PAGE') - expect(Object.keys(tt.data.document.pages).length).toBe(2) - - const pageId = Object.keys(tt.data.document.pages)[1] - tt.send('DELETED_PAGE', { id: pageId }).undo().redo() - - expect(Object.keys(tt.data.document.pages).length).toBe(1) - - const firstPageId = Object.keys(tt.data.document.pages)[0] - expect(tt.data.currentPageId).toBe(firstPageId) - }) - - describe('when first page is selected', () => { - it('does command', () => { - // TODO - null - }) - - it('un-does command', () => { - // TODO - null - }) - - it('re-does command', () => { - // TODO - null - }) - }) - - describe('when project only has one page', () => { - it('does command', () => { - // TODO - null - }) - - it('un-does command', () => { - // TODO - null - }) - - it('re-does command', () => { - // TODO - null - }) - }) -}) diff --git a/__tests__/commands/delete-selected.ts b/__tests__/commands/delete-selected.ts deleted file mode 100644 index 7df2eacc8..000000000 --- a/__tests__/commands/delete-selected.ts +++ /dev/null @@ -1,40 +0,0 @@ -import TestState from '../test-utils' - -describe('delete-selected command', () => { - const tt = new TestState() - tt.resetDocumentState() - - describe('when one item is selected', () => { - it('does command', () => { - // TODO - null - }) - - it('un-does command', () => { - // TODO - null - }) - - it('re-does command', () => { - // TODO - null - }) - }) - - describe('when multiple items are selected', () => { - it('does command', () => { - // TODO - null - }) - - it('un-does command', () => { - // TODO - null - }) - - it('re-does command', () => { - // TODO - null - }) - }) -}) diff --git a/__tests__/commands/delete.test.ts b/__tests__/commands/delete.test.ts deleted file mode 100644 index 2ce7fd65b..000000000 --- a/__tests__/commands/delete.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { ShapeType } from 'types' -import TestState, { rectangleId, arrowId } from '../test-utils' - -describe('delete command', () => { - const tt = new TestState() - - describe('deleting single shapes', () => { - it('deletes a shape and undoes the delete', () => { - tt.deselectAll().clickShape(rectangleId).pressDelete() - - expect(tt.idsAreSelected([])).toBe(true) - - expect(tt.getShape(rectangleId)).toBe(undefined) - - tt.undo() - - expect(tt.getShape(rectangleId)).toBeTruthy() - expect(tt.idsAreSelected([rectangleId])).toBe(true) - - tt.redo() - - expect(tt.getShape(rectangleId)).toBe(undefined) - }) - }) - - describe('deleting and restoring grouped shapes', () => { - it('creates a group', () => { - tt.reset() - .deselectAll() - .clickShape(rectangleId) - .clickShape(arrowId, { shiftKey: true }) - .send('GROUPED') - - const group = tt.getOnlySelectedShape() - - // Should select the group - expect(tt.assertShapeProps(group, { type: ShapeType.Group })).toBe(true) - - const arrow = tt.getShape(arrowId) - - // The arrow should be have the group as its parent - expect(tt.assertShapeProps(arrow, { parentId: group.id })).toBe(true) - }) - - it('selects the new group', () => { - const groupId = tt.getShape(arrowId).parentId - - expect(tt.idsAreSelected([groupId])).toBe(true) - }) - - it('assigns a new parent', () => { - const groupId = tt.getShape(arrowId).parentId - - expect(groupId === tt.data.currentPageId).toBe(false) - }) - - // Rectangle has the same new parent? - it('assigns new parent to all selected shapes', () => { - const groupId = tt.getShape(arrowId).parentId - - expect(tt.hasParent(arrowId, groupId)).toBe(true) - }) - }) - - describe('selecting within the group', () => { - it('selects the group when pointing a shape', () => { - const groupId = tt.getShape(arrowId).parentId - - tt.deselectAll().clickShape(rectangleId) - - expect(tt.idsAreSelected([groupId])).toBe(true) - }) - - it('keeps selection when pointing group shape', () => { - const groupId = tt.getShape(arrowId).parentId - - tt.deselectAll().clickShape(groupId) - - expect(tt.idsAreSelected([groupId])).toBe(true) - }) - - it('selects a grouped shape by double-pointing', () => { - tt.deselectAll().doubleClickShape(rectangleId) - - expect(tt.idsAreSelected([rectangleId])).toBe(true) - }) - - it('selects a sibling on point after double-pointing into a grouped shape children', () => { - tt.deselectAll().doubleClickShape(rectangleId).clickShape(arrowId) - - expect(tt.idsAreSelected([arrowId])).toBe(true) - }) - - it('rises up a selection level when escape is pressed', () => { - const groupId = tt.getShape(arrowId).parentId - - tt.deselectAll().doubleClickShape(rectangleId).send('CANCELLED') - - tt.clickShape(rectangleId) - - expect(tt.idsAreSelected([groupId])).toBe(true) - }) - - // it('deletes and restores one shape', () => { - // // Delete the rectangle first - // state.send('UNDO') - - // expect(tld.getShape(tt.data, rectangleId)).toBeTruthy() - // expect(tt.idsAreSelected([rectangleId])).toBe(true) - - // state.send('REDO') - - // expect(tld.getShape(tt.data, rectangleId)).toBe(undefined) - - // state.send('UNDO') - - // expect(tld.getShape(tt.data, rectangleId)).toBeTruthy() - // expect(tt.idsAreSelected([rectangleId])).toBe(true) - }) -}) diff --git a/__tests__/commands/distribute.test.ts b/__tests__/commands/distribute.test.ts deleted file mode 100644 index dd0a86868..000000000 --- a/__tests__/commands/distribute.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import TestState from '../test-utils' - -describe('distribute command', () => { - const tt = new TestState() - tt.resetDocumentState() - - describe('when one item is selected', () => { - it('does not change anything', () => { - // TODO - null - }) - }) - - describe('when two items are selected', () => { - it('does not change anything', () => { - // TODO - null - }) - }) - - describe('when three or more items are selected', () => { - it('does command', () => { - // TODO - null - }) - - it('un-does command', () => { - // TODO - null - }) - - it('re-does command', () => { - // TODO - null - }) - }) -}) diff --git a/__tests__/commands/draw.test.ts b/__tests__/commands/draw.test.ts deleted file mode 100644 index 545b5ac9d..000000000 --- a/__tests__/commands/draw.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import TestState from '../test-utils' - -describe('draw command', () => { - const tt = new TestState() - tt.resetDocumentState() - - it('does command', () => { - // TODO - null - }) - - it('un-does command', () => { - // TODO - null - }) - - it('re-does command', () => { - // TODO - null - }) -}) diff --git a/__tests__/commands/duplicate-page.test.ts b/__tests__/commands/duplicate-page.test.ts deleted file mode 100644 index 255b26f23..000000000 --- a/__tests__/commands/duplicate-page.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { ShapeType } from 'types' -import TestState from '../test-utils' - -describe('duplicate page command', () => { - const tt = new TestState() - tt.resetDocumentState() - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 0], - size: [100, 100], - childIndex: 1, - }, - 'rect1' - ) - .save() - - describe('duplicates a page', () => { - it('does, undoes, and redoes command', () => { - tt.reset().restore() - - expect(Object.keys(tt.data.document.pages).length).toBe(1) - const pageId = Object.keys(tt.data.document.pages)[0] - expect(tt.getShape('rect1').parentId).toBe(pageId) - - tt.send('DUPLICATED_PAGE', { id: pageId }) - - expect(Object.keys(tt.data.document.pages).length).toBe(2) - - const newPageId = Object.keys(tt.data.document.pages)[1] - - expect(tt.data.currentPageId).toBe(newPageId) - - expect(tt.getShape('rect1').parentId).toBe(newPageId) - - tt.undo() - - expect(Object.keys(tt.data.document.pages).length).toBe(1) - expect(tt.data.currentPageId).toBe(Object.keys(tt.data.document.pages)[0]) - - expect(tt.getShape('rect1').parentId).toBe(pageId) - - tt.redo() - - expect(Object.keys(tt.data.document.pages).length).toBe(2) - expect(tt.data.currentPageId).toBe(Object.keys(tt.data.document.pages)[1]) - - expect(tt.getShape('rect1').parentId).toBe(newPageId) - }) - }) - - describe('duplicates a page other than the current page', () => { - tt.restore() - .reset() - .send('CREATED_PAGE') - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 0], - size: [100, 100], - childIndex: 1, - }, - 'rect2' - ) - .send('CHANGED_PAGE', { id: 'page1' }) - - const firstPageId = Object.keys(tt.data.document.pages)[0] - - // We should be back on the first page - expect(tt.data.currentPageId).toBe(firstPageId) - - // But we should have two pages - expect(Object.keys(tt.data.document.pages).length).toBe(2) - - const secondPageId = Object.keys(tt.data.document.pages)[1] - - // Now we duplicate the second page - tt.send('DUPLICATED_PAGE', { id: secondPageId }) - - // We should now have three pages - expect(Object.keys(tt.data.document.pages).length).toBe(3) - - // The third page should also have a shape named rect2 - const thirdPageId = Object.keys(tt.data.document.pages)[2] - - // We should have changed pages to the third page - expect(tt.data.currentPageId).toBe(thirdPageId) - - // And it should be the parent of the third page - expect(tt.getShape('rect2').parentId).toBe(thirdPageId) - - tt.undo() - - // We should still be on the first page, but we should - // have only two pages; the third page should be deleted - expect(Object.keys(tt.data.document.pages).length).toBe(2) - expect(tt.data.document.pages[thirdPageId]).toBe(undefined) - expect(tt.data.currentPageId).toBe(firstPageId) - - tt.redo() - - // We should be back on the third page - expect(Object.keys(tt.data.document.pages).length).toBe(3) - expect(tt.data.document.pages[thirdPageId]).toBeTruthy() - expect(tt.data.currentPageId).toBe(Object.keys(tt.data.document.pages)[2]) - - expect(tt.getShape('rect2').parentId).toBe(thirdPageId) - }) -}) diff --git a/__tests__/commands/duplicate.test.ts b/__tests__/commands/duplicate.test.ts deleted file mode 100644 index 48057b7f9..000000000 --- a/__tests__/commands/duplicate.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { ShapeType } from 'types' -import TestState from '../test-utils' - -describe('duplicate command', () => { - const tt = new TestState() - tt.resetDocumentState() - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 0], - size: [100, 100], - }, - 'rectangleShape' - ) - .createShape( - { - type: ShapeType.Ellipse, - point: [150, 150], - radiusX: 50, - radiusY: 50, - }, - 'ellipseShape' - ) - .save() - - describe('when one item is selected', () => { - it('does, undoes and redoes command', () => { - tt.restore() - - const shapesBeforeDuplication = tt.getSortedPageShapeIds() - - tt.clickShape('rectangleShape').send('DUPLICATED') - - const shapesAfterDuplication = tt.getSortedPageShapeIds() - - const duplicatedShapeId = tt.selectedIds[0] - const duplicatedShape = tt.getShape(duplicatedShapeId) - - expect(shapesAfterDuplication.length).toEqual( - shapesBeforeDuplication.length + 1 - ) - expect( - tt.assertShapeProps(duplicatedShape, { - type: ShapeType.Rectangle, - size: [100, 100], - }) - ) - - tt.undo() - - const shapesAfterUndo = tt.getSortedPageShapeIds() - - expect(shapesAfterUndo.length).toEqual(shapesBeforeDuplication.length) - expect(tt.getShape(duplicatedShapeId)).toBe(undefined) - expect(tt.idsAreSelected(['rectangleShape'])).toBe(true) - - tt.redo() - - expect(tt.getShape(duplicatedShapeId)).toBeTruthy() - expect(tt.idsAreSelected([duplicatedShapeId])).toBe(true) - }) - }) - - describe('when multiple items are selected', () => { - it('does, undoes and redoes command', () => { - tt.restore() - - const shapesBeforeDuplication = tt.getSortedPageShapeIds() - - tt.clickShape('rectangleShape') - .clickShape('ellipseShape', { shiftKey: true }) - .send('DUPLICATED') - - const shapesAfterDuplication = tt.getSortedPageShapeIds() - - const duplicatedShapesIds = tt.selectedIds - const [duplicatedRectangle, duplicatedEllipse] = duplicatedShapesIds.map( - (shapeId) => tt.getShape(shapeId) - ) - - expect(shapesAfterDuplication.length).toEqual( - shapesBeforeDuplication.length * 2 - ) - expect( - tt.assertShapeProps(duplicatedRectangle, { - type: ShapeType.Rectangle, - size: [100, 100], - }) - ) - expect( - tt.assertShapeProps(duplicatedEllipse, { - type: ShapeType.Ellipse, - radiusX: 50, - radiusY: 50, - }) - ) - - tt.undo() - - const shapesAfterUndo = tt.getSortedPageShapeIds() - - expect(shapesAfterUndo.length).toEqual(shapesBeforeDuplication.length) - duplicatedShapesIds.forEach((shapeId) => { - expect(tt.getShape(shapeId)).toBe(undefined) - }) - expect(tt.idsAreSelected(['rectangleShape', 'ellipseShape'])).toBe(true) - - tt.redo() - - duplicatedShapesIds.forEach((shapeId) => { - expect(tt.getShape(shapeId)).toBeTruthy() - }) - expect(tt.idsAreSelected(duplicatedShapesIds)).toBe(true) - }) - }) -}) diff --git a/__tests__/commands/edit.test.ts b/__tests__/commands/edit.test.ts deleted file mode 100644 index 5d9d714a8..000000000 --- a/__tests__/commands/edit.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import TestState from '../test-utils' - -describe('edit command', () => { - const tt = new TestState() - tt.resetDocumentState() - - it('does command', () => { - // TODO - null - }) - - it('un-does command', () => { - // TODO - null - }) - - it('re-does command', () => { - // TODO - null - }) -}) diff --git a/__tests__/commands/generate.test.ts b/__tests__/commands/generate.test.ts deleted file mode 100644 index 74e37e2a3..000000000 --- a/__tests__/commands/generate.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import TestState from '../test-utils' - -describe('generate command', () => { - const tt = new TestState() - tt.resetDocumentState() - - it('does command', () => { - // TODO - null - }) - - it('un-does command', () => { - // TODO - null - }) - - it('re-does command', () => { - // TODO - null - }) -}) diff --git a/__tests__/commands/group.test.ts b/__tests__/commands/group.test.ts deleted file mode 100644 index dc9a1239a..000000000 --- a/__tests__/commands/group.test.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { ShapeType } from 'types' -import TestState from '../test-utils' - -describe('group command', () => { - const tt = new TestState() - tt.resetDocumentState() - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 0], - size: [100, 100], - childIndex: 1, - isLocked: false, - isHidden: false, - isAspectRatioLocked: false, - }, - 'rect1' - ) - .createShape( - { - type: ShapeType.Rectangle, - point: [400, 0], - size: [100, 100], - childIndex: 2, - isHidden: false, - isLocked: false, - isAspectRatioLocked: false, - }, - 'rect2' - ) - .save() - - // it('deletes the group if it has only one child', () => { - // tt.restore() - // .clickShape('rect1') - // .clickShape('rect2', { shiftKey: true }) - // .send('GROUPED') - - // const groupId = tt.getShape('rect1').parentId - - // expect(groupId === tt.data.currentPageId).toBe(false) - - // tt.doubleClickShape('rect1') - - // tt.send('DELETED') - - // expect(tt.getShape(groupId)).toBe(undefined) - // expect(tt.getShape('rect2')).toBeTruthy() - // }) - - it('deletes the group if all children are deleted', () => { - tt.restore() - .clickShape('rect1') - .clickShape('rect2', { shiftKey: true }) - .send('GROUPED') - - const groupId = tt.getShape('rect1').parentId - - expect(groupId === tt.data.currentPageId).toBe(false) - - tt.doubleClickShape('rect1').clickShape('rect2', { shiftKey: true }) - - tt.send('DELETED') - - expect(tt.getShape(groupId)).toBe(undefined) - }) - - it('creates a group', () => { - tt.restore() - .clickShape('rect1') - .clickShape('rect2', { shiftKey: true }) - .send('GROUPED') - - const groupId = tt.getShape('rect1').parentId - - expect(groupId === tt.data.currentPageId).toBe(false) - }) - - it('selects the group on single click', () => { - tt.restore() - .clickShape('rect1') - .clickShape('rect2', { shiftKey: true }) - .send('GROUPED') - .clickShape('rect1') - - const groupId = tt.getShape('rect1').parentId - - expect(tt.selectedIds).toEqual([groupId]) - }) - - it('selects the item on double click', () => { - tt.restore() - .clickShape('rect1') - .clickShape('rect2', { shiftKey: true }) - .send('GROUPED') - .doubleClickShape('rect1') - - const groupId = tt.getShape('rect1').parentId - - expect(tt.data.currentParentId).toBe(groupId) - - expect(tt.selectedIds).toEqual(['rect1']) - }) - - it('resets currentPageId when clicking the canvas', () => { - tt.restore() - .clickShape('rect1') - .clickShape('rect2', { shiftKey: true }) - .send('GROUPED') - .doubleClickShape('rect1') - .clickCanvas() - .clickShape('rect1') - - const groupId = tt.getShape('rect1').parentId - - expect(tt.data.currentParentId).toBe(tt.data.currentPageId) - - expect(tt.selectedIds).toEqual([groupId]) - }) - - it('creates a group and undoes and redoes', () => { - tt.restore() - .clickShape('rect1') - .clickShape('rect2', { shiftKey: true }) - .send('GROUPED') - - const groupId = tt.getShape('rect1').parentId - - expect(groupId === tt.data.currentPageId).toBe(false) - - tt.undo() - - expect(tt.getShape('rect1').parentId === tt.data.currentPageId).toBe(true) - expect(tt.getShape(groupId)).toBe(undefined) - - tt.redo() - - expect(tt.getShape('rect1').parentId === tt.data.currentPageId).toBe(false) - expect(tt.getShape(groupId)).toBeTruthy() - }) - - it('groups shapes with different parents', () => { - // TODO - null - }) - - it('does not group a parent group shape and its child', () => { - // TODO - null - }) -}) diff --git a/__tests__/commands/move-to-page.test.ts b/__tests__/commands/move-to-page.test.ts deleted file mode 100644 index f098128bb..000000000 --- a/__tests__/commands/move-to-page.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import TestState from '../test-utils' - -describe('move-to-page command', () => { - const tt = new TestState() - tt.resetDocumentState() - - describe('when one item is selected', () => { - it('does not change anything', () => { - // TODO - null - }) - }) - - describe('when multiple items are selected', () => { - it('does command', () => { - // TODO - null - }) - - it('un-does command', () => { - // TODO - null - }) - - it('re-does command', () => { - // TODO - null - }) - }) - - it('reparents children of groups to page', () => { - // TODO - null - }) - - it('correctly preserves moved groups', () => { - // TODO - null - }) -}) diff --git a/__tests__/commands/rename-page.test.ts b/__tests__/commands/rename-page.test.ts deleted file mode 100644 index 1f70cab01..000000000 --- a/__tests__/commands/rename-page.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import TestState from '../test-utils' - -describe('rename page command', () => { - const tt = new TestState() - tt.resetDocumentState().save() - - describe('renames a page', () => { - it('does, undoes, and redoes command', () => { - tt.restore().reset().send('CREATED_PAGE') - - const pageId = Object.keys(tt.data.document.pages)[1] - - expect(tt.data.document.pages[pageId].name).toBe('Page 2') - - tt.send('RENAMED_PAGE', { id: pageId, name: 'My First Page' }) - - expect(tt.data.document.pages[pageId].name).toBe('My First Page') - - tt.undo() - - expect(tt.data.document.pages[pageId].name).toBe('Page 2') - - tt.redo() - - expect(tt.data.document.pages[pageId].name).toBe('My First Page') - }) - }) - - describe('renames a page other than the current page', () => { - tt.restore() - .reset() - .send('CREATED_PAGE') - .send('CHANGED_PAGE', { id: 'page1' }) - - expect(Object.keys(tt.data.document.pages).length).toBe(2) - - expect(tt.data.currentPageId).toBe('page1') - - const secondPageId = Object.keys(tt.data.document.pages)[1] - - expect(tt.data.document.pages[secondPageId].name).toBe('Page 2') - - tt.send('RENAMED_PAGE', { id: secondPageId, name: 'My Second Page' }) - - expect(tt.data.document.pages[secondPageId].name).toBe('My Second Page') - - tt.undo() - - expect(tt.data.document.pages[secondPageId].name).toBe('Page 2') - - tt.redo() - - expect(tt.data.document.pages[secondPageId].name).toBe('My Second Page') - }) -}) diff --git a/__tests__/commands/toggle.test.ts b/__tests__/commands/toggle.test.ts deleted file mode 100644 index a19dc7ce2..000000000 --- a/__tests__/commands/toggle.test.ts +++ /dev/null @@ -1,237 +0,0 @@ -import { ShapeType } from 'types' -import TestState from '../test-utils' - -describe('toggle command', () => { - const tt = new TestState() - tt.resetDocumentState() - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 0], - size: [100, 100], - childIndex: 1, - isLocked: false, - isHidden: false, - isAspectRatioLocked: false, - }, - 'rect1' - ) - .createShape( - { - type: ShapeType.Rectangle, - point: [400, 0], - size: [100, 100], - childIndex: 2, - isHidden: false, - isLocked: false, - isAspectRatioLocked: false, - }, - 'rect2' - ) - .createShape( - { - type: ShapeType.Rectangle, - point: [800, 0], - size: [100, 100], - childIndex: 3, - isHidden: true, - isLocked: true, - isAspectRatioLocked: true, - }, - 'rect3' - ) - .createShape( - { - type: ShapeType.Rectangle, - point: [1000, 0], - size: [100, 100], - childIndex: 4, - isHidden: true, - isLocked: true, - isAspectRatioLocked: true, - }, - 'rect4' - ) - .save() - - describe('toggles properties on single shape', () => { - it('does command', () => { - tt.restore().clickShape('rect1') - - tt.send('TOGGLED_SHAPE_LOCK') - - expect(tt.getShape('rect1').isLocked).toBe(true) - - tt.send('TOGGLED_SHAPE_LOCK') - - expect(tt.getShape('rect1').isLocked).toBe(false) - }) - - it('undoes and redoes command', () => { - // Restore the saved data state, with the initial selection - tt.restore().clickShape('rect1') - - tt.send('TOGGLED_SHAPE_LOCK') - - tt.send('UNDO') - - expect(tt.getShape('rect1').isLocked).toBe(false) - - tt.send('REDO') - - expect(tt.getShape('rect1').isLocked).toBe(true) - }) - }) - - describe('toggles properties on shapes with matching properties, starting from false', () => { - it('does command', () => { - // Restore the saved data state, with the initial selection - tt.restore().clickShape('rect1').clickShape('rect2', { shiftKey: true }) - - tt.send('TOGGLED_SHAPE_LOCK') - - expect(tt.getShape('rect1').isLocked).toBe(true) - expect(tt.getShape('rect2').isLocked).toBe(true) - - tt.send('TOGGLED_SHAPE_LOCK') - - expect(tt.getShape('rect1').isLocked).toBe(false) - expect(tt.getShape('rect2').isLocked).toBe(false) - - tt.send('TOGGLED_SHAPE_LOCK') - - expect(tt.getShape('rect1').isLocked).toBe(true) - expect(tt.getShape('rect2').isLocked).toBe(true) - }) - - it('undoes and redoes command', () => { - // Restore the saved data state, with the initial selection - tt.restore().clickShape('rect1').clickShape('rect2', { shiftKey: true }) - - tt.send('TOGGLED_SHAPE_LOCK').undo() - - expect(tt.getShape('rect1').isLocked).toBe(false) - expect(tt.getShape('rect2').isLocked).toBe(false) - - tt.redo() - - expect(tt.getShape('rect1').isLocked).toBe(true) - expect(tt.getShape('rect2').isLocked).toBe(true) - }) - }) - - describe('toggles properties on shapes with matching properties, starting from true', () => { - it('does command', () => { - // Restore the saved data state, with the initial selection - tt.restore().clickShape('rect3').clickShape('rect4', { shiftKey: true }) - - tt.send('TOGGLED_SHAPE_LOCK') - - expect(tt.getShape('rect3').isLocked).toBe(false) - expect(tt.getShape('rect4').isLocked).toBe(false) - - tt.send('TOGGLED_SHAPE_LOCK') - - expect(tt.getShape('rect3').isLocked).toBe(true) - expect(tt.getShape('rect4').isLocked).toBe(true) - }) - - it('undoes and redoes command', () => { - // Restore the saved data state, with the initial selection - tt.restore().clickShape('rect3').clickShape('rect4', { shiftKey: true }) - - tt.send('TOGGLED_SHAPE_LOCK').undo() - - expect(tt.getShape('rect3').isLocked).toBe(true) - expect(tt.getShape('rect4').isLocked).toBe(true) - - tt.redo() - - expect(tt.getShape('rect3').isLocked).toBe(false) - expect(tt.getShape('rect4').isLocked).toBe(false) - }) - }) - - describe('toggles properties on shapes with different properties', () => { - it('does command', () => { - // Restore the saved data state, with the initial selection - tt.restore() - .clickShape('rect1') - .clickShape('rect2', { shiftKey: true }) - .clickShape('rect3', { shiftKey: true }) - - tt.send('TOGGLED_SHAPE_LOCK') - - expect(tt.getShape('rect1').isLocked).toBe(true) - expect(tt.getShape('rect2').isLocked).toBe(true) - expect(tt.getShape('rect3').isLocked).toBe(true) - - tt.send('TOGGLED_SHAPE_LOCK') - - expect(tt.getShape('rect1').isLocked).toBe(false) - expect(tt.getShape('rect2').isLocked).toBe(false) - expect(tt.getShape('rect3').isLocked).toBe(false) - }) - - it('undoes and redoes command', () => { - tt.restore() - .clickShape('rect1') - .clickShape('rect2', { shiftKey: true }) - .clickShape('rect3', { shiftKey: true }) - - tt.send('TOGGLED_SHAPE_LOCK').undo() - - expect(tt.getShape('rect1').isLocked).toBe(false) - expect(tt.getShape('rect2').isLocked).toBe(false) - expect(tt.getShape('rect3').isLocked).toBe(true) - - tt.redo() - - expect(tt.getShape('rect1').isLocked).toBe(true) - expect(tt.getShape('rect2').isLocked).toBe(true) - expect(tt.getShape('rect3').isLocked).toBe(true) - }) - }) - - describe('catch all for other toggle props', () => { - const eventPropertyPairs = { - TOGGLED_SHAPE_LOCK: 'isLocked', - TOGGLED_SHAPE_HIDE: 'isHidden', - TOGGLED_SHAPE_ASPECT_LOCK: 'isAspectRatioLocked', - } - - it('toggles all event property pairs', () => { - Object.entries(eventPropertyPairs).forEach(([eventName, propName]) => { - // Restore the saved data state, with the initial selection - tt.restore() - .clickShape('rect1') - .clickShape('rect2', { shiftKey: true }) - .clickShape('rect3', { shiftKey: true }) - - tt.send(eventName) - - expect(tt.getShape('rect1')[propName]).toBe(true) - expect(tt.getShape('rect2')[propName]).toBe(true) - expect(tt.getShape('rect3')[propName]).toBe(true) - - tt.undo() - - expect(tt.getShape('rect1')[propName]).toBe(false) - expect(tt.getShape('rect2')[propName]).toBe(false) - expect(tt.getShape('rect3')[propName]).toBe(true) - - tt.redo() - - expect(tt.getShape('rect1')[propName]).toBe(true) - expect(tt.getShape('rect2')[propName]).toBe(true) - expect(tt.getShape('rect3')[propName]).toBe(true) - - tt.send(eventName) - - expect(tt.getShape('rect1')[propName]).toBe(false) - expect(tt.getShape('rect2')[propName]).toBe(false) - expect(tt.getShape('rect3')[propName]).toBe(false) - }) - }) - }) -}) diff --git a/__tests__/commands/transform.test.ts b/__tests__/commands/transform.test.ts deleted file mode 100644 index b8e859647..000000000 --- a/__tests__/commands/transform.test.ts +++ /dev/null @@ -1,347 +0,0 @@ -import { Corner, Edge, RectangleShape, ShapeType } from 'types' -import { rng } from 'utils' -import TestState from '../test-utils' - -describe('transform command', () => { - const tt = new TestState() - tt.resetDocumentState() - .createShape( - { - type: ShapeType.Rectangle, - point: [100, 100], - size: [100, 100], - childIndex: 1, - }, - 'rect1' - ) - .createShape( - { - type: ShapeType.Rectangle, - point: [500, 400], - size: [200, 200], - childIndex: 2, - }, - 'rect2' - ) - .clickShape('rect1') - .clickShape('rect2', { shiftKey: true }) - .save() - - function getSnapInfo() { - return { - rect1: { - point: tt.getShape('rect1').point, - size: tt.getShape('rect1').size, - }, - rect2: { - point: tt.getShape('rect2').point, - size: tt.getShape('rect2').size, - }, - } - } - - it('sets up initial bounds', () => { - expect(tt.selectedIds).toEqual(['rect1', 'rect2']) - - expect(tt.state.values.selectedBounds).toMatchObject({ - minX: 100, - minY: 100, - maxX: 700, - maxY: 600, - width: 600, - height: 500, - }) - }) - - describe('when transforming from the bottom-right corner', () => { - it('does command', () => { - // Restore the saved data state, with the initial selection - tt.restore() - - // Move the bounds handle - tt.startClickingBoundsHandle(Corner.BottomRight) - .movePointerBy([100, 100]) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchObject({ - minX: 100, - minY: 100, - maxX: 800, - maxY: 700, - width: 700, - height: 600, - }) - - expect(getSnapInfo()).toMatchSnapshot() - }) - - it('un-does command', () => { - // Repeat the same actions, but add an undo at the end - tt.restore() - .startClickingBoundsHandle(Corner.BottomRight) - .movePointerBy([100, 100]) - .stopClickingBounds() - .undo() - - // Expect the bounds to be the initial bounds - expect(tt.state.values.selectedBounds).toMatchObject({ - minX: 100, - minY: 100, - maxX: 700, - maxY: 600, - width: 600, - height: 500, - }) - - expect(getSnapInfo()).toMatchSnapshot() - }) - - it('re-does command', () => { - // Repeat the same actions but add an undo and a redo at the end - tt.restore() - .startClickingBoundsHandle(Corner.BottomRight) - .movePointerBy([100, 100]) - .stopClickingBounds() - .undo() - .redo() - - // Expect the bounds to be the transformed bounds - expect(tt.state.values.selectedBounds).toMatchObject({ - minX: 100, - minY: 100, - maxX: 800, - maxY: 700, - width: 700, - height: 600, - }) - - expect(getSnapInfo()).toMatchSnapshot() - }) - }) - - // From here on, let's assume that the undo and redos work as expected, - // so let's only test the command's execution. - - it('transforms from the top edge', () => { - tt.restore() - .startClickingBoundsHandle(Edge.Top) - .movePointerBy([100, 100]) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchObject({ - minX: 100, - minY: 200, - maxX: 700, - maxY: 600, - width: 600, - height: 400, - }) - - expect(getSnapInfo()).toMatchSnapshot() - }) - - it('transforms from the right edge', () => { - tt.restore() - .startClickingBoundsHandle(Edge.Right) - .movePointerBy([100, 100]) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchObject({ - minX: 100, - minY: 100, - maxX: 800, - maxY: 600, - width: 700, - height: 500, - }) - - expect(getSnapInfo()).toMatchSnapshot() - }) - - it('transforms from the bottom edge', () => { - tt.restore() - .startClickingBoundsHandle(Edge.Bottom) - .movePointerBy([100, 100]) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchObject({ - minX: 100, - minY: 100, - maxX: 700, - maxY: 700, - width: 600, - height: 600, - }) - - expect(getSnapInfo()).toMatchSnapshot() - }) - - it('transforms from the left edge', () => { - tt.restore() - .startClickingBoundsHandle(Edge.Left) - .movePointerBy([100, 100]) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchObject({ - minX: 200, - minY: 100, - maxX: 700, - maxY: 600, - width: 500, - height: 500, - }) - - expect(getSnapInfo()).toMatchSnapshot() - }) - - it('transforms from the top-left corner', () => { - tt.restore() - .startClickingBoundsHandle(Corner.TopLeft) - .movePointerBy([100, 100]) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchObject({ - minX: 200, - minY: 200, - maxX: 700, - maxY: 600, - width: 500, - height: 400, - }) - - expect(getSnapInfo()).toMatchSnapshot() - }) - - it('transforms from the top-right corner', () => { - tt.restore() - .startClickingBoundsHandle(Corner.TopRight) - .movePointerBy([100, 100]) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchObject({ - minX: 100, - minY: 200, - maxX: 800, - maxY: 600, - width: 700, - height: 400, - }) - - expect(getSnapInfo()).toMatchSnapshot() - }) - - it('transforms from the bottom-right corner', () => { - tt.restore() - .startClickingBoundsHandle(Corner.BottomRight) - .movePointerBy([100, 100]) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchObject({ - minX: 100, - minY: 100, - maxX: 800, - maxY: 700, - width: 700, - height: 600, - }) - - expect(getSnapInfo()).toMatchSnapshot() - }) - - it('transforms from the bottom-left corner', () => { - tt.restore() - .startClickingBoundsHandle(Corner.BottomLeft) - .movePointerBy([100, 100]) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchObject({ - minX: 200, - minY: 100, - maxX: 700, - maxY: 700, - width: 500, - height: 600, - }) - - expect(getSnapInfo()).toMatchSnapshot() - }) - - describe('snapshot tests', () => { - it('transforms corners', () => { - const getRandom = rng('transform-tests-random-number-generator') - - for (const corner of Object.values(Corner)) { - tt.restore() - .startClickingBoundsHandle(corner) - .movePointerBy([getRandom() * 200, getRandom() * 200]) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchSnapshot() - - expect(getSnapInfo()).toMatchSnapshot() - } - }) - - it('transforms edges', () => { - const getRandom = rng('transform-tests-random-number-generator') - - for (const edge of Object.values(Edge)) { - tt.restore() - .startClickingBoundsHandle(edge) - .movePointerBy([getRandom() * 200, getRandom() * 200]) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchSnapshot() - - expect(getSnapInfo()).toMatchSnapshot() - } - }) - - it('shift-transforms corners', () => { - const getRandom = rng('transform-tests-random-number-generator') - - for (const corner of Object.values(Corner)) { - tt.restore() - .startClickingBoundsHandle(corner) - .movePointerBy([getRandom() * 200, getRandom() * 200], { - shiftKey: true, - }) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchSnapshot() - - expect(getSnapInfo()).toMatchSnapshot() - } - }) - - it('shift-transforms edges', () => { - const getRandom = rng('transform-tests-random-number-generator') - - for (const edge of Object.values(Edge)) { - tt.restore() - .startClickingBoundsHandle(edge) - .movePointerBy([getRandom() * 200, getRandom() * 200], { - shiftKey: true, - }) - .stopClickingBounds() - - // Ensure the bounds have been transformed - expect(tt.state.values.selectedBounds).toMatchSnapshot() - - expect(getSnapInfo()).toMatchSnapshot() - } - }) - }) -}) diff --git a/__tests__/commands/translate.test.ts b/__tests__/commands/translate.test.ts deleted file mode 100644 index d9ea22c8a..000000000 --- a/__tests__/commands/translate.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import TestState from '../test-utils' - -describe('translate command', () => { - const tt = new TestState() - tt.resetDocumentState() - - it('translates a single selected shape', () => { - // TODO - null - }) - - it('translates multiple selected shape', () => { - // TODO - null - }) - - it('translates while axis-locked', () => { - // TODO - null - }) - - it('translates after leaving axis-locked state', () => { - // TODO - null - }) - - it('creates clones while translating', () => { - // TODO - null - }) - - it('removes clones after leaving cloning state', () => { - // TODO - null - }) -}) diff --git a/__tests__/coop.test.ts b/__tests__/coop.test.ts deleted file mode 100644 index 0702ea18c..000000000 --- a/__tests__/coop.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import state from 'state' -import coopState from 'state/coop/coop-state' -import * as json from './__mocks__/document.json' - -state.reset() -state - .send('MOUNTED') - .send('MOUNTED_SHAPES') - .send('LOADED_FROM_FILE', { json: JSON.stringify(json) }) -state.send('CLEARED_PAGE') - -coopState.reset() - -describe('coop', () => { - it('joins a room', () => { - // TODO - null - }) - - it('leaves a room', () => { - // TODO - null - }) - - it('rejoins a room', () => { - // TODO - null - }) - - it('handles another user joining room', () => { - // TODO - null - }) - - it('handles another user leaving room', () => { - // TODO - null - }) - - it('sends mouse movements', () => { - // TODO - null - }) - - it('receives mouse movements', () => { - // TODO - null - }) -}) diff --git a/__tests__/create.test.ts b/__tests__/create.test.ts deleted file mode 100644 index 152585a77..000000000 --- a/__tests__/create.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import state from 'state' -import * as json from './__mocks__/document.json' - -state.reset() -state - .send('MOUNTED') - .send('MOUNTED_SHAPES') - .send('LOADED_FROM_FILE', { json: JSON.stringify(json) }) -state.send('CLEARED_PAGE') - -describe('arrow shape', () => { - it('creates a shape', () => { - // TODO - null - }) - - it('cancels shape while creating', () => { - // TODO - null - }) - - it('removes shape on undo and restores it on redo', () => { - // TODO - null - }) - - it('does not create shape when readonly', () => { - // TODO - null - }) -}) diff --git a/__tests__/dashes.test.ts b/__tests__/dashes.test.ts deleted file mode 100644 index a6e923e00..000000000 --- a/__tests__/dashes.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { DashStyle } from 'types' -import { getPerfectDashProps } from 'utils' - -describe('ellipse dash props', () => { - it('renders dashed props on a circle correctly', () => { - expect(getPerfectDashProps(100, 4, DashStyle.Dashed)).toMatchSnapshot( - 'small dashed circle dash props' - ) - expect(getPerfectDashProps(100, 4, DashStyle.Dashed)).toMatchSnapshot( - 'small dashed ellipse dash props' - ) - expect(getPerfectDashProps(200, 8, DashStyle.Dashed)).toMatchSnapshot( - 'large dashed circle dash props' - ) - expect(getPerfectDashProps(200, 8, DashStyle.Dashed)).toMatchSnapshot( - 'large dashed ellipse dash props' - ) - }) - - it('renders dotted props on a circle correctly', () => { - expect(getPerfectDashProps(100, 4, DashStyle.Dotted)).toMatchSnapshot( - 'small dotted circle dash props' - ) - expect(getPerfectDashProps(100, 4, DashStyle.Dotted)).toMatchSnapshot( - 'small dotted ellipse dash props' - ) - expect(getPerfectDashProps(200, 8, DashStyle.Dotted)).toMatchSnapshot( - 'large dotted circle dash props' - ) - expect(getPerfectDashProps(200, 8, DashStyle.Dotted)).toMatchSnapshot( - 'large dotted ellipse dash props' - ) - }) -}) diff --git a/__tests__/locked.test.ts b/__tests__/locked.test.ts deleted file mode 100644 index b0f089e09..000000000 --- a/__tests__/locked.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import TestState from './test-utils' - -describe('lock command', () => { - const tt = new TestState() - tt.resetDocumentState() - - it('toggles a locked shape', () => { - // TODO - null - }) - - it('selects a locked shape', () => { - // TODO - null - }) - - it('does not translate a locked shape', () => { - // TODO - null - }) - - it('does not translate a locked shape in a group', () => { - // TODO - null - }) - - it('does not rotate a locked shape', () => { - // TODO - null - }) - - it('does not rotate a locked shape in a group', () => { - // TODO - null - }) - - it('dpes not transform a locked single shape', () => { - // TODO - null - }) - - it('does not transform a locked shape in a multiple selection', () => { - // TODO - null - }) - - it('does not transform a locked shape in a group', () => { - // TODO - null - }) - - it('does not change the style of a locked shape', () => { - // TODO - null - }) - - it('does not change the handles of a locked shape', () => { - // TODO - null - }) -}) diff --git a/__tests__/project.test.ts b/__tests__/project.test.ts deleted file mode 100644 index a027ec6c2..000000000 --- a/__tests__/project.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import state from 'state' -import * as json from './__mocks__/document.json' - -describe('project', () => { - state.reset() - state.enableLog(true) - - it('mounts the state', () => { - state.send('MOUNTED').send('MOUNTED_SHAPES') - - expect(state.isIn('ready')).toBe(true) - }) - - it('loads file from json', () => { - state.send('LOADED_FROM_FILE', { json: JSON.stringify(json) }) - - expect(state.isIn('ready')).toBe(true) - expect(state.data.document).toMatchSnapshot('data after mount from file') - }) -}) - -describe('restoring project', () => { - state.reset() - state.enableLog(true) - - it('remounts the state after mutating the current state', () => { - state - .send('MOUNTED') - .send('MOUNTED_SHAPES') - .send('LOADED_FROM_FILE', { json: JSON.stringify(json) }) - .send('CLEARED_PAGE') - - expect( - state.data.document.pages[state.data.currentPageId].shapes - ).toStrictEqual({}) - - state - .send('MOUNTED') - .send('MOUNTED_SHAPES') - .send('LOADED_FROM_FILE', { json: JSON.stringify(json) }) - - expect(state.data.document).toMatchSnapshot('data after re-mount from file') - }) -}) diff --git a/__tests__/selection.test.ts b/__tests__/selection.test.ts deleted file mode 100644 index 960bace48..000000000 --- a/__tests__/selection.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import TestState, { rectangleId, arrowId } from './test-utils' - -describe('selection', () => { - const tt = new TestState() - - it('selects a shape', () => { - tt.deselectAll().clickShape(rectangleId) - - expect(tt.idsAreSelected([rectangleId])).toBe(true) - }) - - it('selects and deselects a shape', () => { - tt.deselectAll().clickShape(rectangleId).clickCanvas() - - expect(tt.idsAreSelected([])).toBe(true) - }) - - it('selects multiple shapes', () => { - tt.deselectAll() - .clickShape(rectangleId) - .clickShape(arrowId, { shiftKey: true }) - - expect(tt.idsAreSelected([rectangleId, arrowId])).toBe(true) - }) - - it('shift-selects to deselect shapes', () => { - tt.deselectAll() - .clickShape(rectangleId) - .clickShape(arrowId, { shiftKey: true }) - .clickShape(rectangleId, { shiftKey: true }) - - expect(tt.idsAreSelected([arrowId])).toBe(true) - }) - - it('single-selects shape in selection on click', () => { - tt.deselectAll() - .clickShape(rectangleId) - .clickShape(arrowId, { shiftKey: true }) - .clickShape(arrowId) - - expect(tt.idsAreSelected([arrowId])).toBe(true) - }) - - it('single-selects shape in selection on pointerup only', () => { - tt.deselectAll() - .clickShape(rectangleId) - .clickShape(arrowId, { shiftKey: true }) - - expect(tt.idsAreSelected([rectangleId, arrowId])).toBe(true) - - tt.startClick(arrowId) - - expect(tt.idsAreSelected([rectangleId, arrowId])).toBe(true) - - tt.stopClick(arrowId) - - expect(tt.idsAreSelected([arrowId])).toBe(true) - }) - - it('selects shapes if shift key is lifted before pointerup', () => { - tt.deselectAll() - .clickShape(rectangleId) - .clickShape(arrowId, { shiftKey: true }) - .startClick(rectangleId, { shiftKey: true }) - .stopClick(rectangleId) - - expect(tt.idsAreSelected([rectangleId])).toBe(true) - }) - - it('does not select on meta-click', () => { - tt.deselectAll().clickShape(rectangleId, { ctrlKey: true }) - - expect(tt.idsAreSelected([])).toBe(true) - }) - - it('does not select on meta-shift-click', () => { - tt.deselectAll().clickShape(rectangleId, { ctrlKey: true, shiftKey: true }) - - expect(tt.idsAreSelected([])).toBe(true) - }) -}) diff --git a/__tests__/shapes/arrow.test.ts b/__tests__/shapes/arrow.test.ts deleted file mode 100644 index 82b1fee0d..000000000 --- a/__tests__/shapes/arrow.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { ArrowShape, ShapeType } from 'types' -import TestState from '../test-utils' - -describe('arrow shape', () => { - const tt = new TestState() - tt.resetDocumentState().save() - - describe('creating arrows', () => { - it('creates shape', () => { - tt.reset().restore().send('SELECTED_ARROW_TOOL') - - expect(tt.state.isIn('arrow.creating')).toBe(true) - - tt.startClick('canvas').movePointerBy([100, 100]).stopClick('canvas') - - const id = tt.getSortedPageShapeIds()[0] - - const shape = tt.getShape(id) - - tt.assertShapeType(id, ShapeType.Arrow) - - expect(shape.handles.start.point).toEqual([0, 0]) - expect(shape.handles.bend.point).toEqual([50.5, 50.5]) - expect(shape.handles.end.point).toEqual([101, 101]) - }) - - it('creates shapes when pointing a shape', () => { - tt.reset().restore().send('SELECTED_ARROW_TOOL').send('TOGGLED_TOOL_LOCK') - - tt.startClick('canvas').movePointerBy([100, 100]).stopClick('canvas') - tt.startClick('canvas').movePointerBy([-200, 100]).stopClick('canvas') - - expect(tt.getSortedPageShapeIds()).toHaveLength(2) - }) - - it('creates shapes when shape locked', () => { - tt.reset() - .restore() - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 0], - size: [100, 100], - childIndex: 1, - }, - 'rect1' - ) - .send('SELECTED_ARROW_TOOL') - - tt.startClick('rect1').movePointerBy([100, 100]).stopClick('canvas') - - expect(tt.getSortedPageShapeIds()).toHaveLength(2) - }) - - it('cancels shape while creating', () => { - // TODO - null - }) - }) - - it('moves shape', () => { - // TODO - null - }) - - it('rotates shape', () => { - // TODO - null - }) - - it('rotates shape in a group', () => { - // TODO - null - }) - - it('measures shape bounds', () => { - // TODO - null - }) - - it('measures shape rotated bounds', () => { - // TODO - null - }) - - it('transforms single shape', () => { - // TODO - null - }) - - it('transforms in a group', () => { - // TODO - null - }) - - /* -------------------- Specific -------------------- */ - - it('creates compass-aligned shape with shift key', () => { - // TODO - null - }) - - it('changes start handle', () => { - // TODO - null - }) - - it('changes end handle', () => { - // TODO - null - }) - - it('changes bend handle', () => { - // TODO - null - }) - - it('resets bend handle when double-pointed', () => { - // TODO - null - }) -}) diff --git a/__tests__/shapes/draw.test.ts b/__tests__/shapes/draw.test.ts deleted file mode 100644 index a261344fc..000000000 --- a/__tests__/shapes/draw.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { ShapeType } from 'types' -import TestState from '../test-utils' - -describe('draw shape', () => { - const tt = new TestState() - tt.resetDocumentState().save() - - describe('creating draws', () => { - it('creates shape', () => { - tt.reset().restore().send('SELECTED_DRAW_TOOL') - - expect(tt.state.isIn('draw.creating')).toBe(true) - - tt.startClick('canvas').movePointerBy([100, 100]).stopClick('canvas') - - const id = tt.getSortedPageShapeIds()[0] - - tt.assertShapeType(id, ShapeType.Draw) - }) - - it('creates shapes when pointing a shape', () => { - tt.reset().restore().send('SELECTED_DRAW_TOOL').send('TOGGLED_TOOL_LOCK') - - tt.startClick('canvas').movePointerBy([100, 100]).stopClick('canvas') - tt.startClick('canvas').movePointerBy([-200, 100]).stopClick('canvas') - - expect(tt.getSortedPageShapeIds()).toHaveLength(2) - }) - - it('creates shapes when shape locked', () => { - tt.reset() - .restore() - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 0], - size: [100, 100], - childIndex: 1, - }, - 'rect1' - ) - .send('SELECTED_DRAW_TOOL') - - tt.startClick('rect1').movePointerBy([100, 100]).stopClick('canvas') - - expect(tt.getSortedPageShapeIds()).toHaveLength(2) - }) - - it('cancels shape while creating', () => { - // TODO - null - }) - }) - - it('moves shape', () => { - // TODO - null - }) - - it('rotates shape', () => { - // TODO - null - }) - - it('rotates shape in a group', () => { - // TODO - null - }) - - it('measures shape bounds', () => { - // TODO - null - }) - - it('measures shape rotated bounds', () => { - // TODO - null - }) - - it('transforms single shape', () => { - // TODO - null - }) - - it('transforms in a group', () => { - // TODO - null - }) - - /* -------------------- Specific -------------------- */ - - it('closes the shape when the start and end points are near enough', () => { - // TODO - null - }) - - it('remains closed after resizing up', () => { - // TODO - null - }) -}) diff --git a/__tests__/shapes/ellipse.test.ts b/__tests__/shapes/ellipse.test.ts deleted file mode 100644 index 9f4f2cd13..000000000 --- a/__tests__/shapes/ellipse.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { ShapeType } from 'types' -import TestState from '../test-utils' - -describe('ellipse shape', () => { - const tt = new TestState() - tt.resetDocumentState().save() - - describe('creating ellipses', () => { - it('creates shape', () => { - tt.reset().restore().send('SELECTED_ELLIPSE_TOOL') - - expect(tt.state.isIn('ellipse.creating')).toBe(true) - - tt.startClick('canvas').movePointerBy([100, 100]).stopClick('canvas') - - const id = tt.getSortedPageShapeIds()[0] - - tt.assertShapeType(id, ShapeType.Ellipse) - }) - - it('creates shapes when pointing a shape', () => { - tt.reset() - .restore() - .send('SELECTED_ELLIPSE_TOOL') - .send('TOGGLED_TOOL_LOCK') - - tt.startClick('canvas').movePointerBy([100, 100]).stopClick('canvas') - tt.startClick('canvas').movePointerBy([-200, 100]).stopClick('canvas') - - expect(tt.getSortedPageShapeIds()).toHaveLength(2) - }) - - it('creates shapes when shape locked', () => { - tt.reset() - .restore() - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 0], - size: [100, 100], - childIndex: 1, - }, - 'rect1' - ) - .send('SELECTED_ELLIPSE_TOOL') - - tt.startClick('rect1').movePointerBy([100, 100]).stopClick('canvas') - - expect(tt.getSortedPageShapeIds()).toHaveLength(2) - }) - - it('cancels shape while creating', () => { - // TODO - null - }) - }) - - it('moves shape', () => { - // TODO - null - }) - - it('rotates shape', () => { - // TODO - null - }) - - it('rotates shape in a group', () => { - // TODO - null - }) - - it('measures shape bounds', () => { - // TODO - null - }) - - it('measures shape rotated bounds', () => { - // TODO - null - }) - - it('transforms single shape', () => { - // TODO - null - }) - - it('transforms in a group', () => { - // TODO - null - }) - - /* -------------------- Specific -------------------- */ - - it('creates aspect-ratio-locked shape with shift key', () => { - // TODO - null - }) - - it('resizes aspect-ratio-locked shape with shift key', () => { - // TODO - null - }) -}) diff --git a/__tests__/shapes/rectangle.test.ts b/__tests__/shapes/rectangle.test.ts deleted file mode 100644 index ee331ca28..000000000 --- a/__tests__/shapes/rectangle.test.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { ShapeType } from 'types' -import TestState from '../test-utils' - -describe('rectangle shape', () => { - const tt = new TestState() - tt.resetDocumentState().save() - - describe('creating rectangles', () => { - it('creates shape', () => { - tt.reset().restore().send('SELECTED_RECTANGLE_TOOL') - - expect(tt.state.isIn('rectangle.creating')).toBe(true) - - tt.startClick('canvas').movePointerBy([100, 100]).stopClick('canvas') - - const id = tt.getSortedPageShapeIds()[0] - - tt.assertShapeType(id, ShapeType.Rectangle) - }) - - it('creates shapes when pointing a shape', () => { - tt.reset() - .restore() - .send('SELECTED_RECTANGLE_TOOL') - .send('TOGGLED_TOOL_LOCK') - - tt.startClick('canvas').movePointerBy([100, 100]).stopClick('canvas') - tt.startClick('canvas').movePointerBy([-200, 100]).stopClick('canvas') - - expect(tt.getSortedPageShapeIds()).toHaveLength(2) - }) - - it('creates shapes when shape locked', () => { - tt.reset() - .restore() - .createShape( - { - type: ShapeType.Rectangle, - point: [0, 0], - size: [100, 100], - childIndex: 1, - }, - 'rect1' - ) - .send('SELECTED_RECTANGLE_TOOL') - - tt.startClick('rect1').movePointerBy([100, 100]).stopClick('canvas') - - expect(tt.getSortedPageShapeIds()).toHaveLength(2) - }) - - it('cancels shape while creating', () => { - // TODO - null - }) - }) - - it('moves shape', () => { - // TODO - null - }) - - it('rotates shape', () => { - // TODO - null - }) - - it('rotates shape in a group', () => { - // TODO - null - }) - - it('measures shape bounds', () => { - // TODO - null - }) - - it('measures shape rotated bounds', () => { - // TODO - null - }) - - it('transforms single shape', () => { - // TODO - null - }) - - it('transforms in a group', () => { - // TODO - null - }) - - /* -------------------- Specific -------------------- */ - - it('creates aspect-ratio-locked shape with shift key', () => { - // TODO - null - }) - - it('resizes aspect-ratio-locked shape with shift key', () => { - // TODO - null - }) -}) diff --git a/__tests__/shapes/text.test.ts b/__tests__/shapes/text.test.ts deleted file mode 100644 index f70bf3443..000000000 --- a/__tests__/shapes/text.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import TestState from '../test-utils' - -describe('arrow shape', () => { - const tt = new TestState() - tt.resetDocumentState() - - it('creates shape', () => { - tt.send('SELECTED_TEXT_TOOL') - - expect(tt.state.isIn('text.creating')).toBe(true) - - const id = tt.getSortedPageShapeIds()[0] - - tt.clickCanvas() - - expect(tt.state.isIn('editingShape')).toBe(true) - - tt.send('EDITED_SHAPE', { - id, - change: { text: 'Hello world' }, - }) - - tt.send('BLURRED_EDITING_SHAPE', { id: id }) - - expect(tt.state.isIn('selecting')).toBe(true) - }) - - it('cancels shape while creating', () => { - // TODO - null - }) - - it('moves shape', () => { - // TODO - null - }) - - it('rotates shape', () => { - // TODO - null - }) - - it('rotates shape in a group', () => { - // TODO - null - }) - - it('measures shape bounds', () => { - // TODO - null - }) - - it('measures shape rotated bounds', () => { - // TODO - null - }) - - it('transforms single shape', () => { - // TODO - null - }) - - it('transforms in a group', () => { - // TODO - null - }) - - /* -------------------- Specific -------------------- */ - - it('scales', () => { - // TODO - null - }) - - it('selects different text on tap while editing', () => { - // TODO - null - }) -}) diff --git a/__tests__/style.test.ts b/__tests__/style.test.ts deleted file mode 100644 index 65969e081..000000000 --- a/__tests__/style.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import state from 'state' -import * as json from './__mocks__/document.json' - -state.reset() -state - .send('MOUNTED') - .send('MOUNTED_SHAPES') - .send('LOADED_FROM_FILE', { json: JSON.stringify(json) }) -state.send('CLEARED_PAGE') - -describe('shape styles', () => { - it('sets the color style of a shape', () => { - // TODO - null - }) - - it('sets the size style of a shape', () => { - // TODO - null - }) - - it('sets the dash style of a shape', () => { - // TODO - null - }) - - it('sets the isFilled style of a shape', () => { - // TODO - null - }) -}) diff --git a/__tests__/test-utils.ts b/__tests__/test-utils.ts deleted file mode 100644 index 2d99cbc50..000000000 --- a/__tests__/test-utils.ts +++ /dev/null @@ -1,836 +0,0 @@ -import _state from 'state' -import tld from 'utils/tld' -import inputs from 'state/inputs' -import { createShape, getShapeUtils } from 'state/shape-utils' -import { Corner, Data, Edge, Shape, ShapeType, ShapeUtility } from 'types' -import { deepClone, deepCompareArrays, uniqueId, vec } from 'utils' -import * as mockDocument from './__mocks__/document.json' - -type State = typeof _state - -export const rectangleId = 'e43559cb-6f41-4ae4-9c49-158ed1ad2f72' -export const arrowId = 'fee77127-e779-4576-882b-b1bf7c7e132f' - -interface PointerOptions { - id?: number - x?: number - y?: number - shiftKey?: boolean - altKey?: boolean - ctrlKey?: boolean -} - -class TestState { - _state: State - snapshot: Data - - constructor() { - this._state = _state - this.state.send('TOGGLED_TEST_MODE') - this.snapshot = deepClone(this.state.data) - this.reset() - } - - /** - * Get the underlying state-designer state. - * - * ### Example - * - *```ts - * tt.state - *``` - */ - get state(): State { - return this._state - } - - /** - * Get the state's current data. - * - * ### Example - * - *```ts - * tt.data - *``` - */ - get data(): Readonly { - return this.state.data - } - - /* -------- Reimplemenation of State Methods -------- */ - - /** - * Send a message to the state. - * - * ### Example - * - *```ts - * tt.send("MOVED_TO_FRONT") - *``` - */ - send(eventName: string, payload?: unknown): TestState { - this.state.send(eventName, payload) - return this - } - - /** - * Check whether a state node is active. If multiple names are provided, then the method will return true only if ALL of the provided state nodes are active. - * - * ### Example - * - *```ts - * tt.isIn("ready") // true - * tt.isIn("ready", "selecting") // true - * tt.isInAny("ready", "notReady") // false - *``` - */ - isIn(...ids: string[]): boolean { - return this.state.isIn(...ids) - } - - /** - * Check whether a state node is active. If multiple names are provided, then the method will return true if ANY of the provided state nodes are active. - * - * ### Example - * - *```ts - * tt.isIn("ready") // true - * tt.isIn("ready", "selecting") // true - * tt.isInAny("ready", "notReady") // true - *``` - */ - isInAny(...ids: string[]): boolean { - return this.state.isInAny(...ids) - } - - /** - * Check whether the state can handle a certain event (and optionally payload). The method will return true if the event is handled by one or more currently active state nodes and if the event will pass its conditions (if present) in at least one of those handlers. - * - * ### Example - * - *```ts - * example - *``` - */ - can(eventName: string, payload?: unknown): boolean { - return this.state.can(eventName, payload) - } - - /* -------------------- Specific -------------------- */ - - /** - * Save a snapshot of the state's current data. - * - * ### Example - * - *```ts - * tt.save() - * tt.restore() - *``` - */ - save(): TestState { - this.snapshot = deepClone(this.data) - return this - } - - /** - * Restore the state's saved data. - * - * ### Example - * - *```ts - * tt.save() - * tt.restore() - *``` - */ - restore(): TestState { - this.state.forceData(this.snapshot) - return this - } - - /** - * Reset the test state. - * - * ### Example - * - *```ts - * tt.reset() - *``` - */ - reset(): TestState { - this.state.reset() - this.state - .send('UNMOUNTED') - .send('MOUNTED', { roomId: 'TESTING' }) - .send('MOUNTED_SHAPES') - .send('LOADED_FROM_FILE', { json: JSON.stringify(mockDocument) }) - - return this - } - - /** - * Reset the document state. Will remove all shapes and extra pages. - * - * ### Example - * - *```ts - * tt.resetDocumentState() - *``` - */ - resetDocumentState(): TestState { - this.state.send('RESET_DOCUMENT_STATE').send('TOGGLED_TEST_MODE') - return this - } - - /** - * Create a new shape on the current page. Optionally provide an id. - * - * ### Example - * - *```ts - * tt.createShape({ type: ShapeType.Rectangle, point: [100, 100]}) - * tt.createShape({ type: ShapeType.Rectangle, point: [100, 100]}, "myId") - *``` - */ - createShape(props: Partial, id = uniqueId()): TestState { - const shape = createShape(props.type, props) - - getShapeUtils(shape) - .setProperty(shape, 'id', id) - .setProperty(shape, 'parentId', this.data.currentPageId) - - this.data.document.pages[this.data.currentPageId].shapes[shape.id] = shape - return this - } - - /** - * Click a shape. - * - * ### Example - * - *```ts - * tt.clickShape("myShapeId") - *``` - */ - clickShape(id: string, options: PointerOptions = {}): TestState { - const shape = tld.getShape(this.data, id) - const [x, y] = shape ? vec.add(shape.point, [1, 1]) : [0, 0] - - this.state - .send( - 'POINTED_SHAPE', - inputs.pointerDown(TestState.point({ x, y, ...options }), id) - ) - .send( - 'STOPPED_POINTING', - inputs.pointerUp(TestState.point({ x, y, ...options }), id) - ) - - return this - } - - /** - * Start a click (but do not stop it). - * - * ### Example - * - *```ts - * tt.startClick("myShapeId") - *``` - */ - startClick(id: string, options: PointerOptions = {}): TestState { - const shape = tld.getShape(this.data, id) - const [x, y] = shape ? vec.add(shape.point, [1, 1]) : [0, 0] - - if (id === 'canvas') { - this.state.send( - 'POINTED_CANVAS', - inputs.pointerDown(TestState.point({ x, y, ...options }), id) - ) - return this - } - - this.state.send( - 'POINTED_SHAPE', - inputs.pointerDown(TestState.point({ x, y, ...options }), id) - ) - - return this - } - - /** - * Stop a click (after starting it). - * - * ### Example - * - *```ts - * tt.stopClick("myShapeId") - *``` - */ - stopClick(id: string, options: PointerOptions = {}): TestState { - const shape = tld.getShape(this.data, id) - const [x, y] = shape ? vec.add(shape.point, [1, 1]) : [0, 0] - - this.state.send( - 'STOPPED_POINTING', - inputs.pointerUp(TestState.point({ x, y, ...options }), id) - ) - - return this - } - - /** - * Double click a shape. - * - * ### Example - * - *```ts - * tt.clickShape("myShapeId") - *``` - */ - doubleClickShape(id: string, options: PointerOptions = {}): TestState { - const shape = tld.getShape(this.data, id) - const [x, y] = shape ? vec.add(shape.point, [1, 1]) : [0, 0] - - this.state - .send( - 'DOUBLE_POINTED_SHAPE', - inputs.pointerDown(TestState.point({ x, y, ...options }), id) - ) - .send( - 'STOPPED_POINTING', - inputs.pointerUp(TestState.point({ x, y, ...options }), id) - ) - - return this - } - - /** - * Click the canvas. - * - * ### Example - * - *```ts - * tt.clickCanvas("myShapeId") - *``` - */ - clickCanvas(options: PointerOptions = {}): TestState { - this.state - .send( - 'POINTED_CANVAS', - inputs.pointerDown(TestState.point(options), 'canvas') - ) - .send( - 'STOPPED_POINTING', - inputs.pointerUp(TestState.point(options), 'canvas') - ) - - return this - } - - /** - * Click the background / body of the bounding box. - * - * ### Example - * - *```ts - * tt.clickBounds() - *``` - */ - clickBounds(options: PointerOptions = {}): TestState { - this.state - .send( - 'POINTED_BOUNDS', - inputs.pointerDown(TestState.point(options), 'bounds') - ) - .send( - 'STOPPED_POINTING', - inputs.pointerUp(TestState.point(options), 'bounds') - ) - - return this - } - - /** - * Start clicking bounds. - * - * ### Example - * - *```ts - * tt.startClickingBounds() - *``` - */ - startClickingBounds(options: PointerOptions = {}): TestState { - this.state.send( - 'POINTED_BOUNDS', - inputs.pointerDown(TestState.point(options), 'bounds') - ) - - return this - } - - /** - * Stop clicking the bounding box. - * - * ### Example - * - *```ts - * tt.stopClickingBounds() - *``` - */ - stopClickingBounds(options: PointerOptions = {}): TestState { - this.state.send( - 'STOPPED_POINTING', - inputs.pointerUp(TestState.point(options), 'bounds') - ) - - return this - } - - /** - * Start clicking a bounds handle. - * - * ### Example - * - *```ts - * tt.startClickingBoundsHandle(Edge.Top) - *``` - */ - startClickingBoundsHandle( - handle: Corner | Edge | 'center', - options: PointerOptions = {} - ): TestState { - this.state.send( - 'POINTED_BOUNDS_HANDLE', - inputs.pointerDown(TestState.point(options), handle) - ) - - return this - } - - /** - * Move the pointer to a new point, or to several points in order. - * - * ### Example - * - *```ts - * tt.movePointerTo([100, 100]) - * tt.movePointerTo([100, 100], { shiftKey: true }) - * tt.movePointerTo([[100, 100], [150, 150], [200, 200]]) - *``` - */ - movePointerTo( - to: number[] | number[][], - options: Omit = {} - ): TestState { - if (Array.isArray(to[0])) { - ;(to as number[][]).forEach(([x, y]) => { - this.state.send( - 'MOVED_POINTER', - inputs.pointerMove(TestState.point({ x, y, ...options })) - ) - }) - } else { - const [x, y] = to as number[] - this.state.send( - 'MOVED_POINTER', - inputs.pointerMove(TestState.point({ x, y, ...options })) - ) - } - - return this - } - - /** - * Move the pointer by a delta. - * - * ### Example - * - *```ts - * tt.movePointerBy([10,10]) - * tt.movePointerBy([10,10], { shiftKey: true }) - *``` - */ - movePointerBy( - by: number[] | number[][], - options: Omit = {} - ): TestState { - let pt = inputs.pointer?.point || [0, 0] - - if (Array.isArray(by[0])) { - ;(by as number[][]).forEach((delta) => { - pt = vec.add(pt, delta) - - this.state.send( - 'MOVED_POINTER', - inputs.pointerMove( - TestState.point({ x: pt[0], y: pt[1], ...options }) - ) - ) - }) - } else { - pt = vec.add(pt, by as number[]) - - this.state.send( - 'MOVED_POINTER', - inputs.pointerMove(TestState.point({ x: pt[0], y: pt[1], ...options })) - ) - } - - return this - } - - /** - * Move pointer over a shape. Will move the pointer to the top-left corner of the shape. - * - * ### - * ``` - * tt.movePointerOverShape('myShapeId', [100, 100]) - * ``` - */ - movePointerOverShape( - id: string, - options: Omit = {} - ): TestState { - const shape = tld.getShape(this.state.data, id) - const [x, y] = vec.add(shape.point, [1, 1]) - - this.state.send( - 'MOVED_OVER_SHAPE', - inputs.pointerEnter(TestState.point({ x, y, ...options }), id) - ) - - return this - } - - /** - * Move the pointer over a group. Will move the pointer to the top-left corner of the group. - * - * ### Example - * - *```ts - * tt.movePointerOverHandle('myGroupId') - * tt.movePointerOverHandle('myGroupId', { shiftKey: true }) - *``` - */ - movePointerOverGroup( - id: string, - options: Omit = {} - ): TestState { - const shape = tld.getShape(this.state.data, id) - const [x, y] = vec.add(shape.point, [1, 1]) - - this.state.send( - 'MOVED_OVER_GROUP', - inputs.pointerEnter(TestState.point({ x, y, ...options }), id) - ) - - return this - } - - /** - * Move the pointer over a handle. Will move the pointer to the top-left corner of the handle. - * - * ### Example - * - *```ts - * tt.movePointerOverHandle('bend') - * tt.movePointerOverHandle('bend', { shiftKey: true }) - *``` - */ - movePointerOverHandle( - id: string, - options: Omit = {} - ): TestState { - const shape = tld.getShape(this.state.data, id) - const handle = shape.handles?.[id] - const [x, y] = vec.add(handle.point, [1, 1]) - - this.state.send( - 'MOVED_OVER_HANDLE', - inputs.pointerEnter(TestState.point({ x, y, ...options }), id) - ) - - return this - } - - /** - * Select all shapes. - * - * ### Example - * - *```ts - * tt.deselectAll() - *``` - */ - selectAll(): TestState { - this.state.send('SELECTED_ALL') - return this - } - - /** - * Deselect all shapes. - * - * ### Example - * - *```ts - * tt.deselectAll() - *``` - */ - deselectAll(): TestState { - this.state.send('DESELECTED_ALL') - return this - } - - /** - * Delete the selected shapes. - * - * ### Example - * - *```ts - * tt.pressDelete() - *``` - */ - pressDelete(): TestState { - this.state.send('DELETED') - return this - } - - /** - * Undo. - * - * ### Example - * - *```ts - * tt.undo() - *``` - */ - undo(): TestState { - this.state.send('UNDO') - return this - } - - /** - * Redo. - * - * ### Example - * - *```ts - * tt.redo() - *``` - */ - redo(): TestState { - this.state.send('REDO') - return this - } - - /* ---------------- Getting Data Out ---------------- */ - - /** - * Get a shape by its id. Note: the shape must be in the current page. - * - * ### Example - * - *```ts - * tt.getShape("myShapeId") - *``` - */ - getShape(id: string): T { - return tld.getShape(this.data, id) as T - } - - /** - * Get the current selected ids. - * - * ### Example - * - *```ts - * example - *``` - */ - get selectedIds(): string[] { - return tld.getSelectedIds(this.data) - } - - /** - * Get shapes for the current page. - * - * ### Example - * - *```ts - * tt.getShapes() - *``` - */ - getShapes(): Shape[] { - return Object.values( - this.data.document.pages[this.data.currentPageId].shapes - ) - } - - /** - * Get ids of the page's children sorted by their child index. - * - * ### Example - * - *```ts - * tt.getSortedPageShapes() - *``` - */ - getSortedPageShapeIds(): string[] { - return this.getShapes() - .sort((a, b) => a.childIndex - b.childIndex) - .map((shape) => shape.id) - } - - /** - * Get the only selected shape. If more than one shape is selected, the test will fail. - * - * ### Example - * - *```ts - * tt.getOnlySelectedShape() - *``` - */ - getOnlySelectedShape(): Shape { - const selectedShapes = tld.getSelectedShapes(this.data) - return selectedShapes.length === 1 ? selectedShapes[0] : undefined - } - - /** - * Get whether the provided ids are the current selected ids. If the `strict` argument is `true`, then the result will be false if the state has selected ids in addition to those provided. - * - * ### Example - * - *```ts - * tt.idsAreSelected(state.data, ['rectangleId', 'ellipseId']) - * tt.idsAreSelected(state.data, ['rectangleId', 'ellipseId'], true) - *``` - */ - idsAreSelected(ids: string[], strict = true): boolean { - const selectedIds = tld.getSelectedIds(this.data) - return ( - (strict ? selectedIds.length === ids.length : true) && - ids.every((id) => selectedIds.includes(id)) - ) - } - - /** - * Get whether the shape with the provided id has the provided parent id. - * - * ### Example - * - *```ts - * tt.hasParent('childId', 'parentId') - *``` - */ - hasParent(childId: string, parentId: string): boolean { - return tld.getShape(this.data, childId).parentId === parentId - } - - /** - * Assert that a shape has the provided type. - * - * ### Example - * - *```ts - * tt.example - *``` - */ - assertShapeType(shapeId: string, type: ShapeType): boolean { - const shape = tld.getShape(this.data, shapeId) - if (shape.type !== type) { - throw new TypeError( - `expected shape ${shapeId} to be of type ${type}, found ${shape?.type} instead` - ) - } - return true - } - - /** - * Assert that the provided shape has the provided props. - * - * ### Example - * - *``` - * tt.assertShapeProps(myShape, { point: [0,0], style: { color: ColorStyle.Blue } } ) - *``` - */ - assertShapeProps( - shape: T, - props: { [K in keyof Partial]: T[K] } - ): boolean { - for (const key in props) { - let result: boolean - const value = props[key] - - if (Array.isArray(value)) { - result = deepCompareArrays(value, shape[key] as typeof value) - } else if (typeof value === 'object') { - const target = shape[key] as typeof value - result = - target && - Object.entries(value).every(([k, v]) => target[k] === props[key][v]) - } else { - result = shape[key] === value - } - - if (!result) { - throw new TypeError( - `expected shape ${shape.id} to have property ${key}: ${props[key]}, found ${key}: ${shape[key]} instead` - ) - } - } - - return true - } - - /** - * Get a shape and test it. - * - * ### Example - * - *```ts - * tt.testShape("myShapeId", (myShape, utils) => expect(utils(myShape).getBounds()).toMatchSnapshot() ) - *``` - */ - testShape( - id: string, - fn: (shape: T, shapeUtils: ShapeUtility) => boolean - ): boolean { - const shape = this.getShape(id) - return fn(shape, shape && getShapeUtils(shape)) - } - - /** - * Get a fake PointerEvent. - * - * ### Example - * - *```ts - * tt.point() - * tt.point({ x: 0, y: 0}) - * tt.point({ x: 0, y: 0, shiftKey: true } ) - *``` - */ - static point(options: PointerOptions = {} as PointerOptions): PointerEvent { - const { - id = 1, - x = 0, - y = 0, - shiftKey = false, - altKey = false, - ctrlKey = false, - } = options - - return { - shiftKey, - altKey, - ctrlKey, - pointerId: id, - clientX: x, - clientY: y, - } as any - } -} - -export default TestState diff --git a/__tests__/tools.test.ts b/__tests__/tools.test.ts deleted file mode 100644 index b86a64d21..000000000 --- a/__tests__/tools.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import TestState from './test-utils' - -const TOOLS = [ - 'draw', - 'rectangle', - 'ellipse', - 'arrow', - 'text', - 'line', - 'ray', - 'dot', -] - -describe('when selecting tools', () => { - const tt = new TestState() - - TOOLS.forEach((tool) => { - it(`selects ${tool} tool`, () => { - tt.reset().send(`SELECTED_${tool.toUpperCase()}_TOOL`) - - expect(tt.data.activeTool).toBe(tool) - expect(tt.state.isIn(tool)).toBe(true) - }) - - TOOLS.forEach((otherTool) => { - if (otherTool === tool) return - - it(`selects ${tool} tool from ${otherTool} tool`, () => { - tt.reset() - .send(`SELECTED_${tool.toUpperCase()}_TOOL`) - .send(`SELECTED_${otherTool.toUpperCase()}_TOOL`) - - expect(tt.data.activeTool).toBe(otherTool) - expect(tt.state.isIn(otherTool)).toBe(true) - }) - }) - }) -}) diff --git a/babel.config.js b/babel.config.js deleted file mode 100644 index bc6c51008..000000000 --- a/babel.config.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = { - presets: ['next/babel'], -} diff --git a/components/canvas/bounds/bounding-box.tsx b/components/canvas/bounds/bounding-box.tsx deleted file mode 100644 index 15c068e08..000000000 --- a/components/canvas/bounds/bounding-box.tsx +++ /dev/null @@ -1,78 +0,0 @@ -import * as React from 'react' -import { Edge, Corner } from 'types' -import { useSelector } from 'state' -import { getBoundsCenter, isMobile } from 'utils' -import tld from 'utils/tld' -import CenterHandle from './center-handle' -import CornerHandle from './corner-handle' -import EdgeHandle from './edge-handle' -import RotateHandle from './rotate-handle' - -export default function Bounds(): JSX.Element { - const isBrushing = useSelector((s) => s.isIn('brushSelecting')) - - const shouldDisplay = useSelector((s) => - s.isInAny('selecting', 'selectPinching') - ) - - const zoom = useSelector((s) => tld.getCurrentCamera(s.data).zoom) - - const bounds = useSelector((s) => s.values.selectedBounds) - - const rotation = useSelector((s) => s.values.selectedRotation) - - const isAllLocked = useSelector((s) => { - const page = tld.getPage(s.data) - return s.values.selectedIds.every((id) => page.shapes[id]?.isLocked) - }) - - const isSingleHandles = useSelector((s) => { - const page = tld.getPage(s.data) - return ( - s.values.selectedIds.length === 1 && - page.shapes[s.values.selectedIds[0]]?.handles !== undefined - ) - }) - - if (!bounds) return null - - if (!shouldDisplay) return null - - if (isSingleHandles) return null - - const size = (isMobile() ? 10 : 8) / zoom // Touch target size - const center = getBoundsCenter(bounds) - - return ( - - - {!isAllLocked && ( - <> - - - - - - - - - - - )} - - ) -} diff --git a/components/canvas/bounds/bounds-bg.tsx b/components/canvas/bounds/bounds-bg.tsx deleted file mode 100644 index 64b497370..000000000 --- a/components/canvas/bounds/bounds-bg.tsx +++ /dev/null @@ -1,77 +0,0 @@ -import { useRef } from 'react' -import state, { useSelector } from 'state' -import inputs from 'state/inputs' -import styled from 'styles' -import tld from 'utils/tld' - -function handlePointerDown(e: React.PointerEvent) { - if (!inputs.canAccept(e.pointerId)) return - e.stopPropagation() - e.currentTarget.setPointerCapture(e.pointerId) - const info = inputs.pointerDown(e, 'bounds') - - if (e.button === 0) { - state.send('POINTED_BOUNDS', info) - } else if (e.button === 2) { - state.send('RIGHT_POINTED', info) - } -} - -function handlePointerUp(e: React.PointerEvent) { - if (!inputs.canAccept(e.pointerId)) return - e.stopPropagation() - e.currentTarget.releasePointerCapture(e.pointerId) - state.send('STOPPED_POINTING', inputs.pointerUp(e, 'bounds')) -} - -export default function BoundsBg(): JSX.Element { - const rBounds = useRef(null) - - const bounds = useSelector((state) => state.values.selectedBounds) - - const shouldDisplay = useSelector((s) => - s.isInAny('selecting', 'selectPinching') - ) - - const rotation = useSelector((s) => s.values.selectedRotation) - - const isAllHandles = useSelector((s) => { - const selectedIds = s.values.selectedIds - - if (selectedIds.length === 1) { - const page = tld.getPage(s.data) - const selected = selectedIds[0] - - return ( - selectedIds.length === 1 && page.shapes[selected]?.handles !== undefined - ) - } - }) - - if (isAllHandles) return null - if (!bounds) return null - if (!shouldDisplay) return null - - const { width, height } = bounds - - return ( - - ) -} - -const StyledBoundsBg = styled('rect', { - fill: '$boundsBg', -}) diff --git a/components/canvas/bounds/center-handle.tsx b/components/canvas/bounds/center-handle.tsx deleted file mode 100644 index 2ab9fa110..000000000 --- a/components/canvas/bounds/center-handle.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import styled from 'styles' -import { Bounds } from 'types' - -export default function CenterHandle({ - bounds, - isLocked, -}: { - bounds: Bounds - isLocked: boolean -}): JSX.Element { - return ( - - ) -} - -const StyledBounds = styled('rect', { - fill: 'none', - stroke: '$bounds', - zStrokeWidth: 1.5, - - variants: { - isLocked: { - true: { - zStrokeWidth: 1.5, - zDash: 2, - }, - }, - }, -}) diff --git a/components/canvas/bounds/corner-handle.tsx b/components/canvas/bounds/corner-handle.tsx deleted file mode 100644 index b77fbe547..000000000 --- a/components/canvas/bounds/corner-handle.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import useBoundsEvents from 'hooks/useBoundsEvents' -import styled from 'styles' -import { Corner, Bounds } from 'types' - -export default function CornerHandle({ - size, - corner, - bounds, -}: { - size: number - bounds: Bounds - corner: Corner -}): JSX.Element { - const events = useBoundsEvents(corner) - - const isTop = corner === Corner.TopLeft || corner === Corner.TopRight - const isLeft = corner === Corner.TopLeft || corner === Corner.BottomLeft - - return ( - - - - - ) -} - -const StyledCorner = styled('rect', { - stroke: 'none', - fill: 'transparent', - variants: { - corner: { - [Corner.TopLeft]: { cursor: 'nwse-resize' }, - [Corner.TopRight]: { cursor: 'nesw-resize' }, - [Corner.BottomRight]: { cursor: 'nwse-resize' }, - [Corner.BottomLeft]: { cursor: 'nesw-resize' }, - }, - }, -}) - -const StyledCornerInner = styled('rect', { - stroke: '$bounds', - fill: '$canvas', - zStrokeWidth: 1.5, -}) diff --git a/components/canvas/bounds/edge-handle.tsx b/components/canvas/bounds/edge-handle.tsx deleted file mode 100644 index 583dd1ff3..000000000 --- a/components/canvas/bounds/edge-handle.tsx +++ /dev/null @@ -1,44 +0,0 @@ -import useBoundsEvents from 'hooks/useBoundsEvents' -import styled from 'styles' -import { Edge, Bounds } from 'types' - -export default function EdgeHandle({ - size, - bounds, - edge, -}: { - size: number - bounds: Bounds - edge: Edge -}): JSX.Element { - const events = useBoundsEvents(edge) - - const isHorizontal = edge === Edge.Top || edge === Edge.Bottom - const isFarEdge = edge === Edge.Right || edge === Edge.Bottom - - const { height, width } = bounds - - return ( - - ) -} - -const StyledEdge = styled('rect', { - stroke: 'none', - fill: 'none', - variants: { - edge: { - [Edge.Top]: { cursor: 'ns-resize' }, - [Edge.Right]: { cursor: 'ew-resize' }, - [Edge.Bottom]: { cursor: 'ns-resize' }, - [Edge.Left]: { cursor: 'ew-resize' }, - }, - }, -}) diff --git a/components/canvas/bounds/handles.tsx b/components/canvas/bounds/handles.tsx deleted file mode 100644 index ce810cfea..000000000 --- a/components/canvas/bounds/handles.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import useHandleEvents from 'hooks/useHandleEvents' -import { getShapeUtils } from 'state/shape-utils' -import { useRef } from 'react' -import { useSelector } from 'state' -import styled from 'styles' -import tld from 'utils/tld' -import vec from 'utils/vec' - -export default function Handles(): JSX.Element { - const shape = useSelector( - (s) => - s.values.selectedIds.length === 1 && - tld.getPage(s.data).shapes[s.values.selectedIds[0]] - ) - - const isSelecting = useSelector((s) => - s.isInAny('notPointing', 'pinching', 'translatingHandles') - ) - - if (!shape || !shape.handles || !isSelecting) return null - - const center = getShapeUtils(shape).getCenter(shape) - - return ( - - {Object.values(shape.handles).map((handle) => ( - - ))} - - ) -} - -function Handle({ id, point }: { id: string; point: number[] }) { - const rGroup = useRef(null) - const events = useHandleEvents(id, rGroup) - - return ( - - - - - ) -} - -const StyledGroup = styled('g', { - '&:hover': { - cursor: 'pointer', - }, - '&:active': { - cursor: 'none', - }, -}) - -const HandleCircleOuter = styled('circle', { - fill: 'transparent', - stroke: 'none', - opacity: 0.2, - pointerEvents: 'all', - cursor: 'pointer', - transform: 'scale(var(--scale))', - '&:hover': { - fill: '$selected', - '& > *': { - stroke: '$selected', - }, - }, - '&:active': { - fill: '$selected', - }, -}) diff --git a/components/canvas/bounds/rotate-handle.tsx b/components/canvas/bounds/rotate-handle.tsx deleted file mode 100644 index 5f86f1dfa..000000000 --- a/components/canvas/bounds/rotate-handle.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import useHandleEvents from 'hooks/useBoundsEvents' -import styled from 'styles' -import { Bounds } from 'types' - -export default function Rotate({ - bounds, - size, -}: { - bounds: Bounds - size: number -}): JSX.Element { - const events = useHandleEvents('rotate') - - return ( - - - - - ) -} - -const StyledRotateHandle = styled('circle', { - stroke: '$bounds', - fill: '$canvas', - zStrokeWidth: 1.5, - cursor: 'grab', -}) diff --git a/components/canvas/brush.tsx b/components/canvas/brush.tsx deleted file mode 100644 index 009e4a658..000000000 --- a/components/canvas/brush.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { useSelector } from 'state' -import styled from 'styles' - -export default function Brush(): JSX.Element { - const brush = useSelector(({ data }) => data.brush) - - if (!brush) return null - - return ( - - ) -} - -const BrushRect = styled('rect', { - fill: '$brushFill', - stroke: '$brushStroke', - zStrokeWidth: 1, -}) diff --git a/components/canvas/canvas.tsx b/components/canvas/canvas.tsx deleted file mode 100644 index 5f54df786..000000000 --- a/components/canvas/canvas.tsx +++ /dev/null @@ -1,99 +0,0 @@ -import * as Sentry from '@sentry/node' -import React, { useEffect, useRef } from 'react' - -import { ErrorBoundary } from 'react-error-boundary' -import state, { useSelector } from 'state' -import styled from 'styles' -import useCamera from 'hooks/useCamera' -import useCanvasEvents from 'hooks/useCanvasEvents' -import useZoomEvents from 'hooks/useZoomEvents' -import Bounds from './bounds/bounding-box' -import BoundsBg from './bounds/bounds-bg' -import Handles from './bounds/handles' -import ContextMenu from './context-menu/context-menu' -import Coop from './coop/coop' -import Brush from './brush' -import Defs from './defs' -import Page from './page' -import useSafariFocusOutFix from 'hooks/useSafariFocusOutFix' - -function resetError() { - null -} - -export default function Canvas(): JSX.Element { - const rCanvas = useRef(null) - const rGroup = useRef(null) - - useCamera(rGroup) - - useZoomEvents() - - useSafariFocusOutFix() - - const events = useCanvasEvents(rCanvas) - - const isSettingCamera = useSelector((s) => s.isIn('settingCamera')) - const isReady = useSelector((s) => s.isIn('ready')) - - useEffect(() => { - if (isSettingCamera) { - state.send('MOUNTED_SHAPES') - } - }, [isSettingCamera]) - - return ( - - - - - - - - - - - - - - - - ) -} - -const MainSVG = styled('svg', { - position: 'fixed', - overflow: 'hidden', - top: 0, - left: 0, - width: '100%', - height: '100%', - touchAction: 'none', - zIndex: 100, - pointerEvents: 'all', - backgroundColor: '$canvas', - borderTop: '1px solid $border', - borderBottom: '1px solid $border', - - '& *': { - userSelect: 'none', - }, -}) - -function ErrorFallback({ error, resetErrorBoundary }) { - React.useEffect(() => { - const copy = - 'Sorry, something went wrong. Press Ok to reset the document, or press cancel to continue and see if it resolves itself.' - - console.error(error) - - Sentry.captureException(error) - - if (window.confirm(copy)) { - state.send('RESET_DOCUMENT_STATE') - resetErrorBoundary() - } - }, []) - - return -} diff --git a/components/canvas/context-menu/context-menu.tsx b/components/canvas/context-menu/context-menu.tsx deleted file mode 100644 index 7fec2fcd5..000000000 --- a/components/canvas/context-menu/context-menu.tsx +++ /dev/null @@ -1,368 +0,0 @@ -import * as _ContextMenu from '@radix-ui/react-context-menu' -import styled from 'styles' -import { - IconWrapper, - breakpoints, - RowButton, - ContextMenuArrow, - ContextMenuDivider, - ContextMenuButton, - ContextMenuSubMenu, - ContextMenuIconButton, - ContextMenuRoot, - MenuContent, -} from 'components/shared' -import { commandKey, deepCompareArrays } from 'utils' -import state, { useSelector } from 'state' -import { - AlignType, - DistributeType, - MoveType, - ShapeType, - StretchType, -} from 'types' -import tld from 'utils/tld' -import React, { useRef } from 'react' -import { - ChevronRightIcon, - AlignBottomIcon, - AlignCenterHorizontallyIcon, - AlignCenterVerticallyIcon, - AlignLeftIcon, - AlignRightIcon, - AlignTopIcon, - SpaceEvenlyHorizontallyIcon, - SpaceEvenlyVerticallyIcon, - StretchHorizontallyIcon, - StretchVerticallyIcon, -} from '@radix-ui/react-icons' -import { Kbd } from 'components/shared' - -function alignTop() { - state.send('ALIGNED', { type: AlignType.Top }) -} - -function alignCenterVertical() { - state.send('ALIGNED', { type: AlignType.CenterVertical }) -} - -function alignBottom() { - state.send('ALIGNED', { type: AlignType.Bottom }) -} - -function stretchVertically() { - state.send('STRETCHED', { type: StretchType.Vertical }) -} - -function distributeVertically() { - state.send('DISTRIBUTED', { type: DistributeType.Vertical }) -} - -function alignLeft() { - state.send('ALIGNED', { type: AlignType.Left }) -} - -function alignCenterHorizontal() { - state.send('ALIGNED', { type: AlignType.CenterHorizontal }) -} - -function alignRight() { - state.send('ALIGNED', { type: AlignType.Right }) -} - -function stretchHorizontally() { - state.send('STRETCHED', { type: StretchType.Horizontal }) -} - -function distributeHorizontally() { - state.send('DISTRIBUTED', { type: DistributeType.Horizontal }) -} - -export default function ContextMenu({ - children, -}: { - children: React.ReactNode -}): JSX.Element { - const selectedShapeIds = useSelector( - (s) => s.values.selectedIds, - deepCompareArrays - ) - - const rContent = useRef(null) - - const hasGroupSelected = useSelector((s) => - selectedShapeIds.some( - (id) => tld.getShape(s.data, id)?.type === ShapeType.Group - ) - ) - - const hasTwoOrMore = selectedShapeIds.length > 1 - const hasThreeOrMore = selectedShapeIds.length > 2 - - return ( - - <_ContextMenu.Trigger>{children} - - {selectedShapeIds.length ? ( - <> - {/* state.send('COPIED')}> - Copy - - {commandKey()} - C - - - state.send('CUT')}> - Cut - - {commandKey()} - X - - - */} - state.send('DUPLICATED')}> - Duplicate - - {commandKey()} - D - - - - {hasGroupSelected || - (hasTwoOrMore && ( - <> - {hasGroupSelected && ( - state.send('UNGROUPED')}> - Ungroup - - {commandKey()} - - G - - - )} - {hasTwoOrMore && ( - state.send('GROUPED')}> - Group - - {commandKey()} - G - - - )} - - ))} - - - state.send('MOVED', { - type: MoveType.ToFront, - }) - } - > - To Front - - {commandKey()} - - ] - - - - - state.send('MOVED', { - type: MoveType.Forward, - }) - } - > - Forward - - {commandKey()} - ] - - - - state.send('MOVED', { - type: MoveType.Backward, - }) - } - > - Backward - - {commandKey()} - [ - - - - state.send('MOVED', { - type: MoveType.ToBack, - }) - } - > - To Back - - {commandKey()} - - [ - - - - {hasTwoOrMore && ( - - )} - - state.send('COPIED_TO_SVG')}> - Copy to SVG - - {commandKey()} - - C - - - - state.send('DELETED')}> - Delete - - - - - - ) : ( - <> - state.send('UNDO')}> - Undo - - {commandKey()} - Z - - - state.send('REDO')}> - Redo - - {commandKey()} - - Z - - - - )} - - - ) -} - -function AlignDistributeSubMenu({ - hasThreeOrMore, -}: { - hasTwoOrMore: boolean - hasThreeOrMore: boolean -}) { - return ( - - <_ContextMenu.TriggerItem as={RowButton} bp={breakpoints}> - Align / Distribute - - - - - - - - - - - - - - - - - - {hasThreeOrMore && ( - - - - )} - - - - - - - - - - - - - - {hasThreeOrMore && ( - - - - )} - - - - ) -} - -const StyledGrid = styled(MenuContent, { - display: 'grid', - variants: { - selectedStyle: { - threeOrMore: { - gridTemplateColumns: 'repeat(5, auto)', - }, - twoOrMore: { - gridTemplateColumns: 'repeat(4, auto)', - }, - }, - }, -}) - -function MoveToPageMenu() { - const documentPages = useSelector((s) => s.data.document.pages) - const currentPageId = useSelector((s) => s.data.currentPageId) - - if (!documentPages[currentPageId]) return null - - const sorted = Object.values(documentPages) - .sort((a, b) => a.childIndex - b.childIndex) - .filter((a) => a.id !== currentPageId) - - if (sorted.length === 0) return null - - return ( - - - Move To Page - - - - - - {sorted.map(({ id, name }) => ( - state.send('MOVED_TO_PAGE', { id })} - > - {name} - - ))} - - - - ) -} diff --git a/components/canvas/coop/coop.tsx b/components/canvas/coop/coop.tsx deleted file mode 100644 index 3d576889b..000000000 --- a/components/canvas/coop/coop.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import Cursor from './cursor' -import { useCoopSelector } from 'state/coop/coop-state' -import { useSelector } from 'state' - -export default function Presence(): JSX.Element { - const others = useCoopSelector((s) => s.data.others) - const currentPageId = useSelector((s) => s.data.currentPageId) - - if (!others) return null - - return ( - <> - {Object.values(others) - .filter(({ presence }) => presence?.pageId === currentPageId) - .map(({ connectionId, presence }) => { - return ( - - ) - })} - - ) -} diff --git a/components/canvas/coop/cursor.tsx b/components/canvas/coop/cursor.tsx deleted file mode 100644 index 191bbe65a..000000000 --- a/components/canvas/coop/cursor.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import React from 'react' -import styled from 'styles' -import { motion } from 'framer-motion' - -export default function Cursor({ - color = 'dodgerblue', - duration = 0, - bufferedXs = [], - bufferedYs = [], - times = [], -}: { - color: string - duration: number - bufferedXs: number[] - bufferedYs: number[] - times: number[] -}): JSX.Element { - return ( - - - - - - - ) -} - -const StyledCursor = styled(motion.g, { - position: 'absolute', - zIndex: 1000, - top: 0, - left: 0, -}) diff --git a/components/canvas/defs.tsx b/components/canvas/defs.tsx deleted file mode 100644 index b26154bed..000000000 --- a/components/canvas/defs.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import React from 'react' -import { useSelector } from 'state' -import tld from 'utils/tld' -import { DotCircle, Handle } from './misc' -import styled from 'styles' - -export default function Defs(): JSX.Element { - return ( - - - - - - - ) -} - -function ExpandDef() { - const zoom = useSelector((s) => tld.getCurrentCamera(s.data).zoom) - return ( - - - - ) -} - -function HoverDef() { - return ( - - - - ) -} - -const StyledShadow = styled('feDropShadow', { - floodColor: '$selected', -}) diff --git a/components/canvas/hovered-shape.tsx b/components/canvas/hovered-shape.tsx deleted file mode 100644 index 08969d8a3..000000000 --- a/components/canvas/hovered-shape.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import { memo } from 'react' -import tld from 'utils/tld' -import { getShapeUtils } from 'state/shape-utils' -import vec from 'utils/vec' -import styled from 'styles' -import { useSelector } from 'state' -import { getShapeStyle } from 'state/shape-styles' - -function HoveredShape({ id }: { id: string }) { - const transform = useSelector((s) => { - const shape = tld.getShape(s.data, id) - const center = getShapeUtils(shape).getCenter(shape) - const rotation = shape.rotation * (180 / Math.PI) - const parentPoint = tld.getShape(s.data, shape.parentId)?.point || [0, 0] - - return ` - translate(${vec.neg(parentPoint)}) - rotate(${rotation}, ${center}) - translate(${shape.point}) - ` - }) - - const strokeWidth = useSelector((s) => { - const shape = tld.getShape(s.data, id) - const style = getShapeStyle(shape.style, s.data.settings.isDarkMode) - return +style.strokeWidth - }) - - return ( - - ) -} - -const StyledHoverShape = styled('use', { - stroke: '$selected', - opacity: 0.1, -}) - -export default memo(HoveredShape) diff --git a/components/canvas/misc.tsx b/components/canvas/misc.tsx deleted file mode 100644 index 5c0b43591..000000000 --- a/components/canvas/misc.tsx +++ /dev/null @@ -1,19 +0,0 @@ -import styled from 'styles' - -export const DotCircle = styled('circle', { - transform: 'scale(var(--scale))', - fill: '$canvas', - stroke: '$text', - strokeWidth: '2', -}) - -export const Handle = styled('circle', { - transform: 'scale(var(--scale))', - fill: '$canvas', - stroke: '$selected', - strokeWidth: '2', -}) - -export const ThinLine = styled('line', { - zStrokeWidth: 1, -}) diff --git a/components/canvas/page.tsx b/components/canvas/page.tsx deleted file mode 100644 index 70dd6bbdc..000000000 --- a/components/canvas/page.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import { useSelector } from 'state' -import { ShapeTreeNode } from 'types' -import ShapeComponent from './shape' - -export default function Page(): JSX.Element { - const shapesToRender = useSelector((s) => s.values.shapesToRender) - - const allowHovers = useSelector((s) => - s.isInAny('selecting', 'text', 'editingShape') - ) - - return ( - <> - {shapesToRender.map((node) => ( - - ))} - - ) -} - -interface ShapeNodeProps { - node: ShapeTreeNode - allowHovers: boolean -} - -const ShapeNode = ({ - node: { - shape, - children, - isEditing, - isHovered, - isDarkMode, - isSelected, - isCurrentParent, - }, - allowHovers, -}: ShapeNodeProps) => { - return ( - <> - - {children.map((childNode) => ( - - ))} - - ) -} diff --git a/components/canvas/shape.tsx b/components/canvas/shape.tsx deleted file mode 100644 index b70845771..000000000 --- a/components/canvas/shape.tsx +++ /dev/null @@ -1,149 +0,0 @@ -import useShapeEvents from 'hooks/useShapeEvents' -import { Shape as _Shape, ShapeType, TextShape } from 'types' -import { getShapeUtils } from 'state/shape-utils' -import { shallowEqual } from 'utils' -import { memo, useRef } from 'react' -import styled from 'styles' - -interface ShapeProps { - shape: _Shape - isEditing: boolean - isHovered: boolean - isSelected: boolean - isDarkMode: boolean - isCurrentParent: boolean -} - -const Shape = memo( - ({ - shape, - isEditing, - isHovered, - isSelected, - isDarkMode, - isCurrentParent, - }: ShapeProps) => { - const rGroup = useRef(null) - const events = useShapeEvents(shape.id, isCurrentParent, rGroup) - const utils = getShapeUtils(shape) - - const center = utils.getCenter(shape) - const rotation = shape.rotation * (180 / Math.PI) - const transform = `rotate(${rotation}, ${center}) translate(${shape.point})` - - return ( - - {isEditing && shape.type === ShapeType.Text ? ( - - ) : ( - - )} - - ) - }, - shallowEqual -) - -export default Shape - -interface RenderedShapeProps { - shape: _Shape - isEditing: boolean - isHovered: boolean - isSelected: boolean - isDarkMode: boolean - isCurrentParent: boolean -} - -const RenderedShape = memo( - function RenderedShape({ - shape, - isEditing, - isHovered, - isSelected, - isDarkMode, - isCurrentParent, - }: RenderedShapeProps) { - return getShapeUtils(shape).render(shape, { - isEditing, - isHovered, - isSelected, - isDarkMode, - isCurrentParent, - }) - }, - (prev, next) => { - if ( - prev.isEditing !== next.isEditing || - prev.isHovered !== next.isHovered || - prev.isSelected !== next.isSelected || - prev.isDarkMode !== next.isDarkMode || - prev.isCurrentParent !== next.isCurrentParent - ) { - return false - } - - if (next.shape !== prev.shape) { - return !getShapeUtils(next.shape).shouldRender(next.shape, prev.shape) - } - - return true - } -) - -function EditingTextShape({ - shape, - isDarkMode, -}: { - shape: TextShape - isDarkMode: boolean -}) { - const ref = useRef(null) - - return getShapeUtils(shape).render(shape, { - ref, - isEditing: true, - isHovered: false, - isSelected: false, - isDarkMode, - isCurrentParent: false, - }) -} - -const ShapeGroup = styled('g', { - outline: 'none', - - '& > *[data-shy=true]': { - opacity: 0, - }, - - '&:hover': { - '& > *[data-shy=true]': { - opacity: 1, - }, - }, - - variants: { - isCurrentParent: { - true: { - '& > *[data-shy=true]': { - opacity: 1, - }, - }, - }, - }, -}) diff --git a/components/code-panel/code-docs.tsx b/components/code-panel/code-docs.tsx deleted file mode 100644 index ca148816c..000000000 --- a/components/code-panel/code-docs.tsx +++ /dev/null @@ -1,121 +0,0 @@ -import styled from 'styles' -import ReactMarkdown from 'react-markdown' -import docs from './docs-content' - -export default function CodeDocs({ - isHidden, -}: { - isHidden: boolean -}): JSX.Element { - return ( - - {docs.content} - - ) -} - -const StyledDocs = styled('div', { - position: 'absolute', - backgroundColor: '$panel', - top: 0, - left: 0, - width: '100%', - height: '100%', - padding: 16, - overflowY: 'scroll', - userSelect: 'none', - paddingBottom: 64, - fontFamily: '$body', - fontWeight: 500, - - variants: { - isHidden: { - true: { - visibility: 'hidden', - }, - false: { - visibility: 'visible', - }, - }, - }, - - '& p': { - fontSize: '$3', - lineHeight: '1.3', - }, - - '& ol, ul': { - fontSize: '$3', - lineHeight: '1.3', - marginTop: 16, - marginBottom: 16, - }, - - '& li': { - fontSize: '$3', - lineHeight: '1.5', - }, - - '& code': { - font: '$mono', - }, - - '& hr': { - margin: '32px 0', - borderColor: '$muted', - }, - - '& h2': { - margin: '40px 0px 24px 0', - }, - - '& h3': { - fontSize: 20, - margin: '48px 0px 32px 0px', - }, - - '& h3 > code': { - fontWeight: 600, - font: '$mono', - }, - - '& h4': { - margin: '32px 0px 0px 0px', - }, - - '& h4 > code': { - font: '$mono', - fontSize: 16, - userSelect: 'all', - }, - - '& h4 > code > i': { - fontSize: 14, - color: '$muted', - }, - - '& pre': { - border: '1px solid $brushStroke', - font: '$mono', - fontWeight: 420, - lineHeight: 1.5, - padding: 16, - borderRadius: 4, - userSelect: 'all', - margin: '24px 0', - }, - - '& p > code, blockquote > code': { - padding: '2px 4px', - borderRadius: 2, - color: '$text', - backgroundColor: '$codeHl', - }, - - '& blockquote': { - backgroundColor: '$overlay', - padding: 12, - margin: '20px 0', - borderRadius: 8, - }, -}) diff --git a/components/code-panel/code-editor.tsx b/components/code-panel/code-editor.tsx deleted file mode 100644 index 92d21ccf9..000000000 --- a/components/code-panel/code-editor.tsx +++ /dev/null @@ -1,248 +0,0 @@ -import Editor, { Monaco } from '@monaco-editor/react' -import { useTheme } from 'next-themes' -import libImport from './es5-lib' -import typesImport from './types-import' -import React, { useCallback, useEffect, useRef } from 'react' -import styled from 'styles' -import * as monaco from 'monaco-editor/esm/vs/editor/editor.api' -import { getFormattedCode } from 'utils/code' -import { metaKey } from 'utils' - -export type IMonaco = typeof monaco - -export type IMonacoEditor = monaco.editor.IStandaloneCodeEditor - -const modifierKeys = ['Escape', 'Meta', 'Control', 'Shift', 'Option', 'Alt'] - -interface Props { - value: string - error: { line: number; column: number } - fontSize: number - monacoRef?: React.MutableRefObject - editorRef?: React.MutableRefObject - readOnly?: boolean - onMount?: (value: string, editor: IMonacoEditor) => void - onUnmount?: (editor: IMonacoEditor) => void - onChange?: (value: string, editor: IMonacoEditor) => void - onSave?: (value: string, editor: IMonacoEditor) => void - onError?: (error: Error, line: number, col: number) => void - onKey?: () => void -} - -export default function CodeEditor({ - editorRef, - monacoRef, - fontSize, - value, - error, - readOnly, - onChange, - onSave, - onKey, -}: Props): JSX.Element { - const { theme } = useTheme() - - const rEditor = useRef(null) - const rMonaco = useRef(null) - - const handleBeforeMount = useCallback((monaco: Monaco) => { - if (monacoRef) { - monacoRef.current = monaco - } - - rMonaco.current = monaco - - // Set the compiler options. - - monaco.languages.typescript.typescriptDefaults.setCompilerOptions({ - allowJs: true, - checkJs: true, - strict: true, - noLib: true, - lib: ['es6'], - target: monaco.languages.typescript.ScriptTarget.ES2016, - allowNonTsExtensions: true, - }) - - // Sync the intellisense on load. - - monaco.languages.typescript.typescriptDefaults.setEagerModelSync(true) - - // Run both semantic and syntax validation. - - monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({ - noSemanticValidation: false, - noSyntaxValidation: false, - }) - - // Add custom types - - monaco.languages.typescript.typescriptDefaults.addExtraLib( - typesImport.content - ) - - // Add es5 library types - - monaco.languages.typescript.typescriptDefaults.addExtraLib( - libImport.content - ) - - // Use prettier as a formatter - - monaco.languages.registerDocumentFormattingEditProvider('typescript', { - async provideDocumentFormattingEdits(model) { - try { - const text = getFormattedCode(model.getValue()) - - return [ - { - range: model.getFullModelRange(), - text, - }, - ] - } catch (e) { - return [ - { - range: model.getFullModelRange(), - text: model.getValue(), - }, - ] - } - }, - }) - }, []) - - const handleMount = useCallback((editor: IMonacoEditor) => { - if (editorRef) { - editorRef.current = editor - } - rEditor.current = editor - - editor.updateOptions({ - fontSize, - fontFamily: "'Recursive Mono', monospace", - wordBasedSuggestions: false, - minimap: { enabled: false }, - lightbulb: { - enabled: false, - }, - readOnly, - }) - }, []) - - const handleChange = useCallback((code: string | undefined) => { - onChange(code, rEditor.current) - }, []) - - const handleKeydown = useCallback( - (e: React.KeyboardEvent) => { - e.stopPropagation() - - !modifierKeys.includes(e.key) && onKey?.() - - if ((e.key === 's' || e.key === 'Enter') && metaKey(e)) { - const editor = rEditor.current - - if (!editor) return - - editor - .getAction('editor.action.formatDocument') - .run() - .then(() => - onSave(rEditor.current?.getModel().getValue(), rEditor.current) - ) - - e.preventDefault() - } - if (e.key === 'p' && metaKey(e)) { - e.preventDefault() - } - - if (e.key === 'd' && metaKey(e)) { - e.preventDefault() - } - }, - [] - ) - - const handleKeyUp = useCallback( - (e: React.KeyboardEvent) => e.stopPropagation(), - [] - ) - - const rDecorations = useRef([]) - - useEffect(() => { - const monaco = rMonaco.current - if (!monaco) return - const editor = rEditor.current - if (!editor) return - - if (!error) { - rDecorations.current = editor.deltaDecorations(rDecorations.current, []) - return - } - - if (!error.line) return - - rDecorations.current = editor.deltaDecorations(rDecorations.current, [ - { - range: new monaco.Range( - Number(error.line) - 1, - 0, - Number(error.line) - 1, - 0 - ), - options: { - isWholeLine: true, - className: 'editorLineError', - }, - }, - ]) - }, [error]) - - useEffect(() => { - const monaco = rMonaco.current - if (!monaco) return - monaco.editor.setTheme(theme === 'dark' ? 'vs-dark' : 'light') - }, [theme]) - - useEffect(() => { - const editor = rEditor.current - if (!editor) return - - editor.updateOptions({ - fontSize, - }) - }, [fontSize]) - - return ( - - - - ) -} - -const EditorContainer = styled('div', { - height: '100%', - pointerEvents: 'all', - userSelect: 'all', - - '& > *': { - userSelect: 'all', - pointerEvents: 'all', - }, - - '.editorLineError': { - backgroundColor: '$lineError', - }, -}) diff --git a/components/code-panel/code-panel.tsx b/components/code-panel/code-panel.tsx deleted file mode 100644 index 2f10ff676..000000000 --- a/components/code-panel/code-panel.tsx +++ /dev/null @@ -1,235 +0,0 @@ -/* eslint-disable @typescript-eslint/ban-ts-comment */ -import styled from 'styles' -import { useStateDesigner } from '@state-designer/react' -import React, { useCallback, useEffect, useRef } from 'react' -import state, { useSelector } from 'state' -import { CodeError, CodeFile, CodeResult } from 'types' -import CodeDocs from './code-docs' -import { generateFromCode } from 'state/code/generate' -import * as Panel from '../panel' -import { breakpoints, IconButton } from '../shared' -import { - Cross2Icon, - CodeIcon, - PlayIcon, - ChevronUpIcon, - ChevronDownIcon, -} from '@radix-ui/react-icons' -import dynamic from 'next/dynamic' -import { ReaderIcon } from '@radix-ui/react-icons' -const CodeEditor = dynamic(() => import('./code-editor')) - -const increaseCodeSize = () => state.send('INCREASED_CODE_FONT_SIZE') -const decreaseCodeSize = () => state.send('DECREASED_CODE_FONT_SIZE') -const toggleCodePanel = () => state.send('TOGGLED_CODE_PANEL_OPEN') -const handleWheel = (e: React.WheelEvent) => e.stopPropagation() - -export default function CodePanel(): JSX.Element { - const rContainer = useRef(null) - const isReadOnly = useSelector((s) => s.data.isReadOnly) - const fileId = useSelector((s) => s.data.currentCodeFileId) - const file = useSelector( - (s) => s.data.document.code[s.data.currentCodeFileId] - ) - const isOpen = useSelector((s) => s.data.settings.isCodeOpen) - const fontSize = useSelector((s) => s.data.settings.fontSize) - - const local = useStateDesigner({ - data: { - code: file.code, - error: null as CodeError | null, - }, - on: { - MOUNTED: 'setCode', - CHANGED_FILE: 'loadFile', - }, - initial: 'editingCode', - states: { - editingCode: { - on: { - RAN_CODE: { do: 'saveCode', to: 'evaluatingCode' }, - SAVED_CODE: { do: 'saveCode', to: 'evaluatingCode' }, - CHANGED_CODE: { secretlyDo: 'setCode' }, - CLEARED_ERROR: { if: 'hasError', do: 'clearError' }, - TOGGLED_DOCS: { to: 'viewingDocs' }, - }, - }, - evaluatingCode: { - async: { - await: 'evalCode', - onResolve: { - do: ['clearError', 'sendResultToGlobalState'], - to: 'editingCode', - }, - onReject: { do: 'setErrorFromResult', to: 'editingCode' }, - }, - }, - viewingDocs: { - on: { - TOGGLED_DOCS: { to: 'editingCode' }, - }, - }, - }, - conditions: { - hasError(data) { - return !!data.error - }, - }, - actions: { - loadFile(data, payload: { file: CodeFile }) { - data.code = payload.file.code - }, - setCode(data, payload: { code: string }) { - data.code = payload.code - }, - saveCode(data) { - const { code } = data - state.send('SAVED_CODE', { code }) - }, - clearError(data) { - data.error = null - }, - setErrorFromResult(data, payload, result: CodeResult) { - data.error = result.error - }, - sendResultToGlobalState(data, payload, result: CodeResult) { - state.send('GENERATED_FROM_CODE', result) - }, - }, - asyncs: { - evalCode(data) { - return new Promise((resolve, reject) => { - generateFromCode(state.data, data.code).then((result) => { - if (result.error !== null) { - reject(result) - } else { - resolve(result) - } - }) - }) - }, - }, - }) - - useEffect(() => { - local.send('CHANGED_FILE', { file }) - }, [file]) - - useEffect(() => { - local.send('MOUNTED', { code: state.data.document.code[fileId].code }) - return () => { - state.send('CHANGED_CODE', { fileId, code: local.data.code }) - } - }, []) - - const handleCodeChange = useCallback( - (code: string) => local.send('CHANGED_CODE', { code }), - [local] - ) - - const handleSave = useCallback(() => local.send('SAVED_CODE'), [local]) - - const handleKey = useCallback(() => local.send('CLEARED_ERROR'), [local]) - - const toggleDocs = useCallback(() => local.send('TOGGLED_DOCS'), [local]) - - const { error } = local.data - - return ( - - {isOpen ? ( - - - - - -

Code

- - - - - - - - - - - - - - - - -
- - - - - - {error && {error.message}} -
- ) : ( - - - - )} -
- ) -} - -const ButtonsGroup = styled('div', { - gridRow: '1', - gridColumn: '3', - display: 'flex', -}) - -const FontSizeButtons = styled('div', { - paddingRight: 4, - display: 'flex', - flexDirection: 'column', - - '& > button': { - height: '50%', - '&:nth-of-type(1)': { - alignItems: 'flex-end', - }, - - '&:nth-of-type(2)': { - alignItems: 'flex-start', - }, - - '& svg': { - height: 12, - }, - }, -}) diff --git a/components/code-panel/docs-content.ts b/components/code-panel/docs-content.ts deleted file mode 100644 index 036c32399..000000000 --- a/components/code-panel/docs-content.ts +++ /dev/null @@ -1,129 +0,0 @@ -/* eslint-disable */ - -// HEY! DO NOT MODIFY THIS FILE. THE CONTENTS OF THIS FILE -// ARE AUTO-GENERATED BY A SCRIPT AT: /scripts/docs-gen.js -// ANY CHANGES WILL BE LOST WHEN THE SCRIPT RUNS AGAIN! - -export default { - name: 'docs-content.ts', - content: ` -Welcome to the documentation for tldraw's code editor. You can use the code editor to create shapes using JavaScript or TypeScript code. - -\`\`\`ts -const rect = new Rectangle({ - point: [100, 100], - size: [200, 200], - style: { - color: ColorStyle.Blue, - }, -}) - -rect.x = 300 -\`\`\` - -To run your code, press **Command + S**. - -Your new shapes will appear on the canvas. You can interact with code-created shapes just like any other shape: you can move the shape, change its style, delete it, etc. - -Each time you run your code, any existing code-created shapes will be replaced by your new code-created shapes. If you want to keep your code-created shapes, select the shapes that you want to keep, press **Command + D** to duplicate them, and move them off to the side. - -## Shapes - -You can use the code editor to create any of the regular shapes: - -- Draw -- Rectangle -- Ellipse -- Arrow -- Text - -You can also create shapes that can _only_ be created with code: - -- Dot -- Ray -- Line -- Polyline - -Each of these shapes is a \`class\`. To create the shape, use the following syntax: - -\`\`\`ts -const myShape = new Rectangle() -\`\`\` - -You can also create a shape with custom properties like this: - -\`\`\`ts -const myShape = new Rectangle({ - point: [100, 100], - size: [200, 200], - style: { - color: ColorStyle.Blue, - size: SizeStyle.Large, - dash: DashStyle.Dotted, - }, -}) -\`\`\` - -Once you've created a shape, you can set its properties like this: - -\`\`\`ts -const myShape = new Rectangle() - -myShape.x = 100 -myShape.color = ColorStyle.Red -\`\`\` - -You can find more information on each shape class by clicking its name in the list above. - -## Controls - -In addition to shapes, you can also use code to create controls. - -\`\`\`ts -new NumberControl({ - label: 'x', - value: 0, -}) - -const myShape = new Rectangle({ - point: [controls.x, 0], -}) -\`\`\` - -Once you've created a control, the app's will display a panel where you can edit the control's value. As you edit the value, your code will run again with the control's new value. - -There are two kinds of controls: - -- NumberControl -- VectorControl -- TextControl - -Each of these controls is a \`class\`. To create the control, use the following syntax: - -\`\`\`ts -const control = new TextControl({ - label: 'myLabel', - value: 'my value', -}) -\`\`\` - -Once you've created a control, you can use its value in your code like this: - -\`\`\`ts -const myShape = new Text({ - text: controls.myLabel, -}) -\`\`\` - -You can find more information on each control class by clicking its name in the list above. - -## Shape Classes - -... - -## Control Classes - -... - -`, -} diff --git a/components/code-panel/es5-lib.ts b/components/code-panel/es5-lib.ts deleted file mode 100644 index 9374b3f54..000000000 --- a/components/code-panel/es5-lib.ts +++ /dev/null @@ -1,5459 +0,0 @@ -/* eslint-disable */ - -// HEY! DO NOT MODIFY THIS FILE. - -export default { - name: 'es5-lib.d.ts', - content: ` - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ - -/// - -///////////////////////////// -/// ECMAScript APIs -///////////////////////////// - -declare let NaN: number -declare let Infinity: number - -/** - * Evaluates JavaScript code and executes it. - * @param x A String value that contains valid JavaScript code. - */ -declare function eval(x: string): any - -/** - * Converts a string to an integer. - * @param string A string to convert into a number. - * @param radix A value between 2 and 36 that specifies the base of the number in \`string\`. - * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. - * All other strings are considered decimal. - */ -declare function parseInt(string: string, radix?: number): number - -/** - * Converts a string to a floating-point number. - * @param string A string that contains a floating-point number. - */ -declare function parseFloat(string: string): number - -/** - * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). - * @param number A numeric value. - */ -declare function isNaN(number: number): boolean - -/** - * Determines whether a supplied number is finite. - * @param number Any numeric value. - */ -declare function isFinite(number: number): boolean - -/** - * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). - * @param encodedURI A value representing an encoded URI. - */ -declare function decodeURI(encodedURI: string): string - -/** - * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). - * @param encodedURIComponent A value representing an encoded URI component. - */ -declare function decodeURIComponent(encodedURIComponent: string): string - -/** - * Encodes a text string as a valid Uniform Resource Identifier (URI) - * @param uri A value representing an encoded URI. - */ -declare function encodeURI(uri: string): string - -/** - * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). - * @param uriComponent A value representing an encoded URI component. - */ -declare function encodeURIComponent( - uriComponent: string | number | boolean -): string - -/** - * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. - * @param string A string value - */ -declare function escape(string: string): string - -/** - * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. - * @param string A string value - */ -declare function unescape(string: string): string - -interface Symbol { - /** Returns a string representation of an object. */ - toString(): string - - /** Returns the primitive value of the specified object. */ - valueOf(): symbol -} - -declare type PropertyKey = string | number | symbol - -interface PropertyDescriptor { - configurable?: boolean - enumerable?: boolean - value?: any - writable?: boolean - get?(): any - set?(v: any): void -} - -interface PropertyDescriptorMap { - [s: string]: PropertyDescriptor -} - -interface Object { - /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ - constructor: Function - - /** Returns a string representation of an object. */ - toString(): string - - /** Returns a date converted to a string using the current locale. */ - toLocaleString(): string - - /** Returns the primitive value of the specified object. */ - valueOf(): Object - - /** - * Determines whether an object has a property with the specified name. - * @param v A property name. - */ - hasOwnProperty(v: PropertyKey): boolean - - /** - * Determines whether an object exists in another object's prototype chain. - * @param v Another object whose prototype chain is to be checked. - */ - isPrototypeOf(v: Object): boolean - - /** - * Determines whether a specified property is enumerable. - * @param v A property name. - */ - propertyIsEnumerable(v: PropertyKey): boolean -} - -interface ObjectConstructor { - new (value?: any): Object - (): any - (value: any): any - - /** A reference to the prototype for a class of objects. */ - readonly prototype: Object - - /** - * Returns the prototype of an object. - * @param o The object that references the prototype. - */ - getPrototypeOf(o: any): any - - /** - * Gets the own property descriptor of the specified object. - * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. - * @param o Object that contains the property. - * @param p Name of the property. - */ - getOwnPropertyDescriptor( - o: any, - p: PropertyKey - ): PropertyDescriptor | undefined - - /** - * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly - * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. - * @param o Object that contains the own properties. - */ - getOwnPropertyNames(o: any): string[] - - /** - * Creates an object that has the specified prototype or that has null prototype. - * @param o Object to use as a prototype. May be null. - */ - create(o: object | null): any - - /** - * Creates an object that has the specified prototype, and that optionally contains specified properties. - * @param o Object to use as a prototype. May be null - * @param properties JavaScript object that contains one or more property descriptors. - */ - create( - o: object | null, - properties: PropertyDescriptorMap & ThisType - ): any - - /** - * Adds a property to an object, or modifies attributes of an existing property. - * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. - * @param p The property name. - * @param attributes Descriptor for the property. It can be for a data property or an accessor property. - */ - defineProperty( - o: T, - p: PropertyKey, - attributes: PropertyDescriptor & ThisType - ): T - - /** - * Adds one or more properties to an object, and/or modifies attributes of existing properties. - * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. - * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. - */ - defineProperties( - o: T, - properties: PropertyDescriptorMap & ThisType - ): T - - /** - * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. - */ - seal(o: T): T - - /** - * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. - */ - freeze(a: T[]): readonly T[] - - /** - * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. - */ - freeze(f: T): T - - /** - * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. - * @param o Object on which to lock the attributes. - */ - freeze(o: T): Readonly - - /** - * Prevents the addition of new properties to an object. - * @param o Object to make non-extensible. - */ - preventExtensions(o: T): T - - /** - * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. - * @param o Object to test. - */ - isSealed(o: any): boolean - - /** - * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. - * @param o Object to test. - */ - isFrozen(o: any): boolean - - /** - * Returns a value that indicates whether new properties can be added to an object. - * @param o Object to test. - */ - isExtensible(o: any): boolean - - /** - * Returns the names of the enumerable string properties and methods of an object. - * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. - */ - keys(o: object): string[] -} - -/** - * Provides functionality common to all JavaScript objects. - */ -declare var Object: ObjectConstructor - -/** - * Creates a new function. - */ -interface Function { - /** - * Calls the function, substituting the specified object for the this value of the function, and the specified array for the arguments of the function. - * @param thisArg The object to be used as the this object. - * @param argArray A set of arguments to be passed to the function. - */ - apply(this: Function, thisArg: any, argArray?: any): any - - /** - * Calls a method of an object, substituting another object for the current object. - * @param thisArg The object to be used as the current object. - * @param argArray A list of arguments to be passed to the method. - */ - call(this: Function, thisArg: any, ...argArray: any[]): any - - /** - * For a given function, creates a bound function that has the same body as the original function. - * The this object of the bound function is associated with the specified object, and has the specified initial parameters. - * @param thisArg An object to which the this keyword can refer inside the new function. - * @param argArray A list of arguments to be passed to the new function. - */ - bind(this: Function, thisArg: any, ...argArray: any[]): any - - /** Returns a string representation of a function. */ - toString(): string - - prototype: any - readonly length: number - - // Non-standard extensions - arguments: any - caller: Function -} - -interface FunctionConstructor { - /** - * Creates a new function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): Function - (...args: string[]): Function - readonly prototype: Function -} - -declare var Function: FunctionConstructor - -/** - * Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter. - */ -type ThisParameterType = T extends (this: infer U, ...args: any[]) => any - ? U - : unknown - -/** - * Removes the 'this' parameter from a function type. - */ -type OmitThisParameter = unknown extends ThisParameterType - ? T - : T extends (...args: infer A) => infer R - ? (...args: A) => R - : T - -interface CallableFunction extends Function { - /** - * Calls the function with the specified object as the this value and the elements of specified array as the arguments. - * @param thisArg The object to be used as the this object. - * @param args An array of argument values to be passed to the function. - */ - apply(this: (this: T) => R, thisArg: T): R - apply( - this: (this: T, ...args: A) => R, - thisArg: T, - args: A - ): R - - /** - * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. - * @param thisArg The object to be used as the this object. - * @param args Argument values to be passed to the function. - */ - call( - this: (this: T, ...args: A) => R, - thisArg: T, - ...args: A - ): R - - /** - * For a given function, creates a bound function that has the same body as the original function. - * The this object of the bound function is associated with the specified object, and has the specified initial parameters. - * @param thisArg The object to be used as the this object. - * @param args Arguments to bind to the parameters of the function. - */ - bind(this: T, thisArg: ThisParameterType): OmitThisParameter - bind( - this: (this: T, arg0: A0, ...args: A) => R, - thisArg: T, - arg0: A0 - ): (...args: A) => R - bind( - this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, - thisArg: T, - arg0: A0, - arg1: A1 - ): (...args: A) => R - bind( - this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, - thisArg: T, - arg0: A0, - arg1: A1, - arg2: A2 - ): (...args: A) => R - bind( - this: (this: T, arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, - thisArg: T, - arg0: A0, - arg1: A1, - arg2: A2, - arg3: A3 - ): (...args: A) => R - bind( - this: (this: T, ...args: AX[]) => R, - thisArg: T, - ...args: AX[] - ): (...args: AX[]) => R -} - -interface NewableFunction extends Function { - /** - * Calls the function with the specified object as the this value and the elements of specified array as the arguments. - * @param thisArg The object to be used as the this object. - * @param args An array of argument values to be passed to the function. - */ - apply(this: new () => T, thisArg: T): void - apply( - this: new (...args: A) => T, - thisArg: T, - args: A - ): void - - /** - * Calls the function with the specified object as the this value and the specified rest arguments as the arguments. - * @param thisArg The object to be used as the this object. - * @param args Argument values to be passed to the function. - */ - call( - this: new (...args: A) => T, - thisArg: T, - ...args: A - ): void - - /** - * For a given function, creates a bound function that has the same body as the original function. - * The this object of the bound function is associated with the specified object, and has the specified initial parameters. - * @param thisArg The object to be used as the this object. - * @param args Arguments to bind to the parameters of the function. - */ - bind(this: T, thisArg: any): T - bind( - this: new (arg0: A0, ...args: A) => R, - thisArg: any, - arg0: A0 - ): new (...args: A) => R - bind( - this: new (arg0: A0, arg1: A1, ...args: A) => R, - thisArg: any, - arg0: A0, - arg1: A1 - ): new (...args: A) => R - bind( - this: new (arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, - thisArg: any, - arg0: A0, - arg1: A1, - arg2: A2 - ): new (...args: A) => R - bind( - this: new (arg0: A0, arg1: A1, arg2: A2, arg3: A3, ...args: A) => R, - thisArg: any, - arg0: A0, - arg1: A1, - arg2: A2, - arg3: A3 - ): new (...args: A) => R - bind( - this: new (...args: AX[]) => R, - thisArg: any, - ...args: AX[] - ): new (...args: AX[]) => R -} - -interface IArguments { - [index: number]: any - length: number - callee: Function -} - -interface String { - /** Returns a string representation of a string. */ - toString(): string - - /** - * Returns the character at the specified index. - * @param pos The zero-based index of the desired character. - */ - charAt(pos: number): string - - /** - * Returns the Unicode value of the character at the specified location. - * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. - */ - charCodeAt(index: number): number - - /** - * Returns a string that contains the concatenation of two or more strings. - * @param strings The strings to append to the end of the string. - */ - concat(...strings: string[]): string - - /** - * Returns the position of the first occurrence of a substring. - * @param searchString The substring to search for in the string - * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. - */ - indexOf(searchString: string, position?: number): number - - /** - * Returns the last occurrence of a substring in the string. - * @param searchString The substring to search for. - * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. - */ - lastIndexOf(searchString: string, position?: number): number - - /** - * Determines whether two strings are equivalent in the current locale. - * @param that String to compare to target string - */ - localeCompare(that: string): number - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A variable name or string literal containing the regular expression pattern and flags. - */ - match(regexp: string | RegExp): RegExpMatchArray | null - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A string to search for. - * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. - */ - replace(searchValue: string | RegExp, replaceValue: string): string - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A string to search for. - * @param replacer A function that returns the replacement text. - */ - replace( - searchValue: string | RegExp, - replacer: (substring: string, ...args: any[]) => string - ): string - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: string | RegExp): number - - /** - * Returns a section of a string. - * @param start The index to the beginning of the specified portion of stringObj. - * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. - * If this value is not specified, the substring continues to the end of stringObj. - */ - slice(start?: number, end?: number): string - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: string | RegExp, limit?: number): string[] - - /** - * Returns the substring at the specified location within a String object. - * @param start The zero-based index number indicating the beginning of the substring. - * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. - * If end is omitted, the characters from start through the end of the original string are returned. - */ - substring(start: number, end?: number): string - - /** Converts all the alphabetic characters in a string to lowercase. */ - toLowerCase(): string - - /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ - toLocaleLowerCase(locales?: string | string[]): string - - /** Converts all the alphabetic characters in a string to uppercase. */ - toUpperCase(): string - - /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ - toLocaleUpperCase(locales?: string | string[]): string - - /** Removes the leading and trailing white space and line terminator characters from a string. */ - trim(): string - - /** Returns the length of a String object. */ - readonly length: number - - // IE extensions - /** - * Gets a substring beginning at the specified location and having the specified length. - * @param from The starting position of the desired substring. The index of the first character in the string is zero. - * @param length The number of characters to include in the returned substring. - */ - substr(from: number, length?: number): string - - /** Returns the primitive value of the specified object. */ - valueOf(): string - - readonly [index: number]: string -} - -interface StringConstructor { - new (value?: any): string - (value?: any): string - readonly prototype: string - fromCharCode(...codes: number[]): string -} - -/** - * Allows manipulation and formatting of text strings and determination and location of substrings within strings. - */ -declare var String: StringConstructor - -interface Boolean { - /** Returns the primitive value of the specified object. */ - valueOf(): boolean -} - -interface BooleanConstructor { - new (value?: any): boolean - (value?: T): boolean - readonly prototype: boolean -} - -declare var Boolean: BooleanConstructor - -interface Number { - /** - * Returns a string representation of an object. - * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. - */ - toString(radix?: number): string - - /** - * Returns a string representing a number in fixed-point notation. - * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. - */ - toFixed(fractionDigits?: number): string - - /** - * Returns a string containing a number represented in exponential notation. - * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. - */ - toExponential(fractionDigits?: number): string - - /** - * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. - * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. - */ - toPrecision(precision?: number): string - - /** Returns the primitive value of the specified object. */ - valueOf(): number -} - -interface NumberConstructor { - new (value?: any): number - (value?: any): number - readonly prototype: number - - /** The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. */ - readonly MAX_VALUE: number - - /** The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. */ - readonly MIN_VALUE: number - - /** - * A value that is not a number. - * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. - */ - readonly NaN: number - - /** - * A value that is less than the largest negative number that can be represented in JavaScript. - * JavaScript displays NEGATIVE_INFINITY values as -infinity. - */ - readonly NEGATIVE_INFINITY: number - - /** - * A value greater than the largest number that can be represented in JavaScript. - * JavaScript displays POSITIVE_INFINITY values as infinity. - */ - readonly POSITIVE_INFINITY: number -} - -/** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ -declare var Number: NumberConstructor - -interface TemplateStringsArray extends ReadonlyArray { - readonly raw: readonly string[] -} - -/** - * The type of \`import.meta\`. - * - * If you need to declare that a given property exists on \`import.meta\`, - * this type may be augmented via interface merging. - */ -interface ImportMeta {} - -interface Math { - /** The mathematical constant e. This is Euler's number, the base of natural logarithms. */ - readonly E: number - /** The natural logarithm of 10. */ - readonly LN10: number - /** The natural logarithm of 2. */ - readonly LN2: number - /** The base-2 logarithm of e. */ - readonly LOG2E: number - /** The base-10 logarithm of e. */ - readonly LOG10E: number - /** Pi. This is the ratio of the circumference of a circle to its diameter. */ - readonly PI: number - /** The square root of 0.5, or, equivalently, one divided by the square root of 2. */ - readonly SQRT1_2: number - /** The square root of 2. */ - readonly SQRT2: number - /** - * Returns the absolute value of a number (the value without regard to whether it is positive or negative). - * For example, the absolute value of -5 is the same as the absolute value of 5. - * @param x A numeric expression for which the absolute value is needed. - */ - abs(x: number): number - /** - * Returns the arc cosine (or inverse cosine) of a number. - * @param x A numeric expression. - */ - acos(x: number): number - /** - * Returns the arcsine of a number. - * @param x A numeric expression. - */ - asin(x: number): number - /** - * Returns the arctangent of a number. - * @param x A numeric expression for which the arctangent is needed. - */ - atan(x: number): number - /** - * Returns the angle (in radians) from the X axis to a point. - * @param y A numeric expression representing the cartesian y-coordinate. - * @param x A numeric expression representing the cartesian x-coordinate. - */ - atan2(y: number, x: number): number - /** - * Returns the smallest integer greater than or equal to its numeric argument. - * @param x A numeric expression. - */ - ceil(x: number): number - /** - * Returns the cosine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - cos(x: number): number - /** - * Returns e (the base of natural logarithms) raised to a power. - * @param x A numeric expression representing the power of e. - */ - exp(x: number): number - /** - * Returns the greatest integer less than or equal to its numeric argument. - * @param x A numeric expression. - */ - floor(x: number): number - /** - * Returns the natural logarithm (base e) of a number. - * @param x A numeric expression. - */ - log(x: number): number - /** - * Returns the larger of a set of supplied numeric expressions. - * @param values Numeric expressions to be evaluated. - */ - max(...values: number[]): number - /** - * Returns the smaller of a set of supplied numeric expressions. - * @param values Numeric expressions to be evaluated. - */ - min(...values: number[]): number - /** - * Returns the value of a base expression taken to a specified power. - * @param x The base value of the expression. - * @param y The exponent value of the expression. - */ - pow(x: number, y: number): number - /** Returns a pseudorandom number between 0 and 1. */ - random(): number - /** - * Returns a supplied numeric expression rounded to the nearest integer. - * @param x The value to be rounded to the nearest integer. - */ - round(x: number): number - /** - * Returns the sine of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - sin(x: number): number - /** - * Returns the square root of a number. - * @param x A numeric expression. - */ - sqrt(x: number): number - /** - * Returns the tangent of a number. - * @param x A numeric expression that contains an angle measured in radians. - */ - tan(x: number): number -} -/** An intrinsic object that provides basic mathematics functionality and constants. */ -declare var Math: Math - -/** Enables basic storage and retrieval of dates and times. */ -interface Date { - /** Returns a string representation of a date. The format of the string depends on the locale. */ - toString(): string - /** Returns a date as a string value. */ - toDateString(): string - /** Returns a time as a string value. */ - toTimeString(): string - /** Returns a value as a string value appropriate to the host environment's current locale. */ - toLocaleString(): string - /** Returns a date as a string value appropriate to the host environment's current locale. */ - toLocaleDateString(): string - /** Returns a time as a string value appropriate to the host environment's current locale. */ - toLocaleTimeString(): string - /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */ - valueOf(): number - /** Gets the time value in milliseconds. */ - getTime(): number - /** Gets the year, using local time. */ - getFullYear(): number - /** Gets the year using Universal Coordinated Time (UTC). */ - getUTCFullYear(): number - /** Gets the month, using local time. */ - getMonth(): number - /** Gets the month of a Date object using Universal Coordinated Time (UTC). */ - getUTCMonth(): number - /** Gets the day-of-the-month, using local time. */ - getDate(): number - /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */ - getUTCDate(): number - /** Gets the day of the week, using local time. */ - getDay(): number - /** Gets the day of the week using Universal Coordinated Time (UTC). */ - getUTCDay(): number - /** Gets the hours in a date, using local time. */ - getHours(): number - /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */ - getUTCHours(): number - /** Gets the minutes of a Date object, using local time. */ - getMinutes(): number - /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */ - getUTCMinutes(): number - /** Gets the seconds of a Date object, using local time. */ - getSeconds(): number - /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */ - getUTCSeconds(): number - /** Gets the milliseconds of a Date, using local time. */ - getMilliseconds(): number - /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */ - getUTCMilliseconds(): number - /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */ - getTimezoneOffset(): number - /** - * Sets the date and time value in the Date object. - * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. - */ - setTime(time: number): number - /** - * Sets the milliseconds value in the Date object using local time. - * @param ms A numeric value equal to the millisecond value. - */ - setMilliseconds(ms: number): number - /** - * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). - * @param ms A numeric value equal to the millisecond value. - */ - setUTCMilliseconds(ms: number): number - - /** - * Sets the seconds value in the Date object using local time. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setSeconds(sec: number, ms?: number): number - /** - * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCSeconds(sec: number, ms?: number): number - /** - * Sets the minutes value in the Date object using local time. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setMinutes(min: number, sec?: number, ms?: number): number - /** - * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCMinutes(min: number, sec?: number, ms?: number): number - /** - * Sets the hour value in the Date object using local time. - * @param hours A numeric value equal to the hours value. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setHours(hours: number, min?: number, sec?: number, ms?: number): number - /** - * Sets the hours value in the Date object using Universal Coordinated Time (UTC). - * @param hours A numeric value equal to the hours value. - * @param min A numeric value equal to the minutes value. - * @param sec A numeric value equal to the seconds value. - * @param ms A numeric value equal to the milliseconds value. - */ - setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number - /** - * Sets the numeric day-of-the-month value of the Date object using local time. - * @param date A numeric value equal to the day of the month. - */ - setDate(date: number): number - /** - * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). - * @param date A numeric value equal to the day of the month. - */ - setUTCDate(date: number): number - /** - * Sets the month value in the Date object using local time. - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. - * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. - */ - setMonth(month: number, date?: number): number - /** - * Sets the month value in the Date object using Universal Coordinated Time (UTC). - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. - * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. - */ - setUTCMonth(month: number, date?: number): number - /** - * Sets the year of the Date object using local time. - * @param year A numeric value for the year. - * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. - * @param date A numeric value equal for the day of the month. - */ - setFullYear(year: number, month?: number, date?: number): number - /** - * Sets the year value in the Date object using Universal Coordinated Time (UTC). - * @param year A numeric value equal to the year. - * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. - * @param date A numeric value equal to the day of the month. - */ - setUTCFullYear(year: number, month?: number, date?: number): number - /** Returns a date converted to a string using Universal Coordinated Time (UTC). */ - toUTCString(): string - /** Returns a date as a string value in ISO format. */ - toISOString(): string - /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */ - toJSON(key?: any): string -} - -interface DateConstructor { - new (): Date - new (value: number | string): Date - new ( - year: number, - month: number, - date?: number, - hours?: number, - minutes?: number, - seconds?: number, - ms?: number - ): Date - (): string - readonly prototype: Date - /** - * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. - * @param s A date string - */ - parse(s: string): number - /** - * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. - * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. - * @param month The month as a number between 0 and 11 (January to December). - * @param date The date as a number between 1 and 31. - * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour. - * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes. - * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds. - * @param ms A number from 0 to 999 that specifies the milliseconds. - */ - UTC( - year: number, - month: number, - date?: number, - hours?: number, - minutes?: number, - seconds?: number, - ms?: number - ): number - now(): number -} - -declare var Date: DateConstructor - -interface RegExpMatchArray extends Array { - index?: number - input?: string -} - -interface RegExpExecArray extends Array { - index: number - input: string -} - -interface RegExp { - /** - * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. - * @param string The String object or string literal on which to perform the search. - */ - exec(string: string): RegExpExecArray | null - - /** - * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. - * @param string String on which to perform the search. - */ - test(string: string): boolean - - /** Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. */ - readonly source: string - - /** Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. */ - readonly global: boolean - - /** Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. */ - readonly ignoreCase: boolean - - /** Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. */ - readonly multiline: boolean - - lastIndex: number - - // Non-standard extensions - compile(): this -} - -interface RegExpConstructor { - new (pattern: RegExp | string): RegExp - new (pattern: string, flags?: string): RegExp - (pattern: RegExp | string): RegExp - (pattern: string, flags?: string): RegExp - readonly prototype: RegExp - - // Non-standard extensions - $1: string - $2: string - $3: string - $4: string - $5: string - $6: string - $7: string - $8: string - $9: string - lastMatch: string -} - -declare var RegExp: RegExpConstructor - -interface Error { - name: string - message: string - stack?: string -} - -interface ErrorConstructor { - new (message?: string): Error - (message?: string): Error - readonly prototype: Error -} - -declare var Error: ErrorConstructor - -type EvalError = Error - -interface EvalErrorConstructor extends ErrorConstructor { - new (message?: string): EvalError - (message?: string): EvalError - readonly prototype: EvalError -} - -declare var EvalError: EvalErrorConstructor - -type RangeError = Error - -interface RangeErrorConstructor extends ErrorConstructor { - new (message?: string): RangeError - (message?: string): RangeError - readonly prototype: RangeError -} - -declare var RangeError: RangeErrorConstructor - -type ReferenceError = Error - -interface ReferenceErrorConstructor extends ErrorConstructor { - new (message?: string): ReferenceError - (message?: string): ReferenceError - readonly prototype: ReferenceError -} - -declare var ReferenceError: ReferenceErrorConstructor - -type SyntaxError = Error - -interface SyntaxErrorConstructor extends ErrorConstructor { - new (message?: string): SyntaxError - (message?: string): SyntaxError - readonly prototype: SyntaxError -} - -declare var SyntaxError: SyntaxErrorConstructor - -type TypeError = Error - -interface TypeErrorConstructor extends ErrorConstructor { - new (message?: string): TypeError - (message?: string): TypeError - readonly prototype: TypeError -} - -declare var TypeError: TypeErrorConstructor - -type URIError = Error - -interface URIErrorConstructor extends ErrorConstructor { - new (message?: string): URIError - (message?: string): URIError - readonly prototype: URIError -} - -declare var URIError: URIErrorConstructor - -interface JSON { - /** - * Converts a JavaScript Object Notation (JSON) string into an object. - * @param text A valid JSON string. - * @param reviver A function that transforms the results. This function is called for each member of the object. - * If a member contains nested objects, the nested objects are transformed before the parent object is. - */ - parse( - text: string, - reviver?: (this: any, key: string, value: any) => any - ): any - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer A function that transforms the results. - * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. - */ - stringify( - value: any, - replacer?: (this: any, key: string, value: any) => any, - space?: string | number - ): string - /** - * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. - * @param value A JavaScript value, usually an object or array, to be converted. - * @param replacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified. - * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. - */ - stringify( - value: any, - replacer?: (number | string)[] | null, - space?: string | number - ): string -} - -/** - * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. - */ -declare var JSON: JSON - -///////////////////////////// -/// ECMAScript Array API (specially handled by compiler) -///////////////////////////// - -interface ReadonlyArray { - /** - * Gets the length of the array. This is a number one higher than the highest element defined in an array. - */ - readonly length: number - /** - * Returns a string representation of an array. - */ - toString(): string - /** - * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods. - */ - toLocaleString(): string - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: ConcatArray[]): T[] - /** - * Combines two or more arrays. - * @param items Additional items to add to the end of array1. - */ - concat(...items: (T | ConcatArray)[]): T[] - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. - */ - slice(start?: number, end?: number): T[] - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - */ - indexOf(searchElement: T, fromIndex?: number): number - /** - * Returns the index of the last occurrence of a specified value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. - */ - lastIndexOf(searchElement: T, fromIndex?: number): number - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: (value: T, index: number, array: readonly T[]) => value is S, - thisArg?: any - ): this is readonly S[] - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: (value: T, index: number, array: readonly T[]) => unknown, - thisArg?: any - ): boolean - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param predicate A function that accepts up to three arguments. The some method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - some( - predicate: (value: T, index: number, array: readonly T[]) => unknown, - thisArg?: any - ): boolean - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - forEach( - callbackfn: (value: T, index: number, array: readonly T[]) => void, - thisArg?: any - ): void - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map( - callbackfn: (value: T, index: number, array: readonly T[]) => U, - thisArg?: any - ): U[] - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: T, index: number, array: readonly T[]) => value is S, - thisArg?: any - ): S[] - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: T, index: number, array: readonly T[]) => unknown, - thisArg?: any - ): T[] - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: T, - currentValue: T, - currentIndex: number, - array: readonly T[] - ) => T - ): T - reduce( - callbackfn: ( - previousValue: T, - currentValue: T, - currentIndex: number, - array: readonly T[] - ) => T, - initialValue: T - ): T - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: U, - currentValue: T, - currentIndex: number, - array: readonly T[] - ) => U, - initialValue: U - ): U - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: T, - currentValue: T, - currentIndex: number, - array: readonly T[] - ) => T - ): T - reduceRight( - callbackfn: ( - previousValue: T, - currentValue: T, - currentIndex: number, - array: readonly T[] - ) => T, - initialValue: T - ): T - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: U, - currentValue: T, - currentIndex: number, - array: readonly T[] - ) => U, - initialValue: U - ): U - - readonly [n: number]: T -} - -interface ConcatArray { - readonly length: number - readonly [n: number]: T - join(separator?: string): string - slice(start?: number, end?: number): T[] -} - -interface Array { - /** - * Gets or sets the length of the array. This is a number one higher than the highest index in the array. - */ - length: number - /** - * Returns a string representation of an array. - */ - toString(): string - /** - * Returns a string representation of an array. The elements are converted to string using their toLocaleString methods. - */ - toLocaleString(): string - /** - * Removes the last element from an array and returns it. - * If the array is empty, undefined is returned and the array is not modified. - */ - pop(): T | undefined - /** - * Appends new elements to the end of an array, and returns the new length of the array. - * @param items New elements to add to the array. - */ - push(...items: T[]): number - /** - * Combines two or more arrays. - * This method returns a new array without modifying any existing arrays. - * @param items Additional arrays and/or items to add to the end of the array. - */ - concat(...items: ConcatArray[]): T[] - /** - * Combines two or more arrays. - * This method returns a new array without modifying any existing arrays. - * @param items Additional arrays and/or items to add to the end of the array. - */ - concat(...items: (T | ConcatArray)[]): T[] - /** - * Adds all the elements of an array into a string, separated by the specified separator string. - * @param separator A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string - /** - * Reverses the elements in an array in place. - * This method mutates the array and returns a reference to the same array. - */ - reverse(): T[] - /** - * Removes the first element from an array and returns it. - * If the array is empty, undefined is returned and the array is not modified. - */ - shift(): T | undefined - /** - * Returns a copy of a section of an array. - * For both start and end, a negative index can be used to indicate an offset from the end of the array. - * For example, -2 refers to the second to last element of the array. - * @param start The beginning index of the specified portion of the array. - * If start is undefined, then the slice begins at index 0. - * @param end The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. - * If end is undefined, then the slice extends to the end of the array. - */ - slice(start?: number, end?: number): T[] - /** - * Sorts an array in place. - * This method mutates the array and returns a reference to the same array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. - * \`\`\`ts - * [11,2,22,1].sort((a, b) => a - b) - * \`\`\` - */ - sort(compareFn?: (a: T, b: T) => number): this - /** - * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - * @param deleteCount The number of elements to remove. - * @returns An array containing the elements that were deleted. - */ - splice(start: number, deleteCount?: number): T[] - /** - * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - * @param start The zero-based location in the array from which to start removing elements. - * @param deleteCount The number of elements to remove. - * @param items Elements to insert into the array in place of the deleted elements. - * @returns An array containing the elements that were deleted. - */ - splice(start: number, deleteCount: number, ...items: T[]): T[] - /** - * Inserts new elements at the start of an array, and returns the new length of the array. - * @param items Elements to insert at the start of the array. - */ - unshift(...items: T[]): number - /** - * Returns the index of the first occurrence of a value in an array, or -1 if it is not present. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - */ - indexOf(searchElement: T, fromIndex?: number): number - /** - * Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array. - */ - lastIndexOf(searchElement: T, fromIndex?: number): number - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: (value: T, index: number, array: T[]) => value is S, - thisArg?: any - ): this is S[] - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: (value: T, index: number, array: T[]) => unknown, - thisArg?: any - ): boolean - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param predicate A function that accepts up to three arguments. The some method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - some( - predicate: (value: T, index: number, array: T[]) => unknown, - thisArg?: any - ): boolean - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - forEach( - callbackfn: (value: T, index: number, array: T[]) => void, - thisArg?: any - ): void - /** - * Calls a defined callback function on each element of an array, and returns an array that contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - */ - map( - callbackfn: (value: T, index: number, array: T[]) => U, - thisArg?: any - ): U[] - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: T, index: number, array: T[]) => value is S, - thisArg?: any - ): S[] - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: T, index: number, array: T[]) => unknown, - thisArg?: any - ): T[] - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: T, - currentValue: T, - currentIndex: number, - array: T[] - ) => T - ): T - reduce( - callbackfn: ( - previousValue: T, - currentValue: T, - currentIndex: number, - array: T[] - ) => T, - initialValue: T - ): T - /** - * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: U, - currentValue: T, - currentIndex: number, - array: T[] - ) => U, - initialValue: U - ): U - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: T, - currentValue: T, - currentIndex: number, - array: T[] - ) => T - ): T - reduceRight( - callbackfn: ( - previousValue: T, - currentValue: T, - currentIndex: number, - array: T[] - ) => T, - initialValue: T - ): T - /** - * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: U, - currentValue: T, - currentIndex: number, - array: T[] - ) => U, - initialValue: U - ): U - - [n: number]: T -} - -interface ArrayConstructor { - new (arrayLength?: number): any[] - new (arrayLength: number): T[] - new (...items: T[]): T[] - (arrayLength?: number): any[] - (arrayLength: number): T[] - (...items: T[]): T[] - isArray(arg: any): arg is any[] - readonly prototype: any[] -} - -declare var Array: ArrayConstructor - -interface TypedPropertyDescriptor { - enumerable?: boolean - configurable?: boolean - writable?: boolean - value?: T - get?: () => T - set?: (value: T) => void -} - -declare type ClassDecorator = ( - target: TFunction -) => TFunction | void -declare type PropertyDecorator = ( - target: Object, - propertyKey: string | symbol -) => void -declare type MethodDecorator = ( - target: Object, - propertyKey: string | symbol, - descriptor: TypedPropertyDescriptor -) => TypedPropertyDescriptor | void -declare type ParameterDecorator = ( - target: Object, - propertyKey: string | symbol, - parameterIndex: number -) => void - -declare type PromiseConstructorLike = new ( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: any) => void - ) => void -) => PromiseLike - -interface PromiseLike { - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then( - onfulfilled?: - | ((value: T) => TResult1 | PromiseLike) - | undefined - | null, - onrejected?: - | ((reason: any) => TResult2 | PromiseLike) - | undefined - | null - ): PromiseLike -} - -/** - * Represents the completion of an asynchronous operation - */ -interface Promise { - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then( - onfulfilled?: - | ((value: T) => TResult1 | PromiseLike) - | undefined - | null, - onrejected?: - | ((reason: any) => TResult2 | PromiseLike) - | undefined - | null - ): Promise - - /** - * Attaches a callback for only the rejection of the Promise. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of the callback. - */ - catch( - onrejected?: - | ((reason: any) => TResult | PromiseLike) - | undefined - | null - ): Promise -} - -interface ArrayLike { - readonly length: number - readonly [n: number]: T -} - -/** - * Make all properties in T optional - */ -type Partial = { - [P in keyof T]?: T[P] -} - -/** - * Make all properties in T required - */ -type Required = { - [P in keyof T]-?: T[P] -} - -/** - * Make all properties in T readonly - */ -type Readonly = { - readonly [P in keyof T]: T[P] -} - -/** - * From T, pick a set of properties whose keys are in the union K - */ -type Pick = { - [P in K]: T[P] -} - -/** - * Construct a type with a set of properties K of type T - */ -type Record = { - [P in K]: T -} - -/** - * Exclude from T those types that are assignable to U - */ -type Exclude = T extends U ? never : T - -/** - * Extract from T those types that are assignable to U - */ -type Extract = T extends U ? T : never - -/** - * Construct a type with the properties of T except for those in type K. - */ -type Omit = Pick> - -/** - * Exclude null and undefined from T - */ -type NonNullable = T extends null | undefined ? never : T - -/** - * Obtain the parameters of a function type in a tuple - */ -type Parameters any> = T extends ( - ...args: infer P -) => any - ? P - : never - -/** - * Obtain the parameters of a constructor function type in a tuple - */ -type ConstructorParameters any> = - T extends abstract new (...args: infer P) => any ? P : never - -/** - * Obtain the return type of a function type - */ -type ReturnType any> = T extends ( - ...args: any -) => infer R - ? R - : any - -/** - * Obtain the return type of a constructor function type - */ -type InstanceType any> = - T extends abstract new (...args: any) => infer R ? R : any - -/** - * Convert string literal type to uppercase - */ -type Uppercase = intrinsic - -/** - * Convert string literal type to lowercase - */ -type Lowercase = intrinsic - -/** - * Convert first character of string literal type to uppercase - */ -type Capitalize = intrinsic - -/** - * Convert first character of string literal type to lowercase - */ -type Uncapitalize = intrinsic - -/** - * Marker for contextual 'this' type - */ -interface ThisType {} - -/** - * Represents a raw buffer of binary data, which is used to store data for the - * different typed arrays. ArrayBuffers cannot be read from or written to directly, - * but can be passed to a typed array or DataView Object to interpret the raw - * buffer as needed. - */ -interface ArrayBuffer { - /** - * Read-only. The length of the ArrayBuffer (in bytes). - */ - readonly byteLength: number - - /** - * Returns a section of an ArrayBuffer. - */ - slice(begin: number, end?: number): ArrayBuffer -} - -/** - * Allowed ArrayBuffer types for the buffer of an ArrayBufferView and related Typed Arrays. - */ -interface ArrayBufferTypes { - ArrayBuffer: ArrayBuffer -} -type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes] - -interface ArrayBufferConstructor { - readonly prototype: ArrayBuffer - new (byteLength: number): ArrayBuffer - isView(arg: any): arg is ArrayBufferView -} -declare var ArrayBuffer: ArrayBufferConstructor - -interface ArrayBufferView { - /** - * The ArrayBuffer instance referenced by the array. - */ - buffer: ArrayBufferLike - - /** - * The length in bytes of the array. - */ - byteLength: number - - /** - * The offset in bytes of the array. - */ - byteOffset: number -} - -interface DataView { - readonly buffer: ArrayBuffer - readonly byteLength: number - readonly byteOffset: number - /** - * Gets the Float32 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getFloat32(byteOffset: number, littleEndian?: boolean): number - - /** - * Gets the Float64 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getFloat64(byteOffset: number, littleEndian?: boolean): number - - /** - * Gets the Int8 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getInt8(byteOffset: number): number - - /** - * Gets the Int16 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getInt16(byteOffset: number, littleEndian?: boolean): number - /** - * Gets the Int32 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getInt32(byteOffset: number, littleEndian?: boolean): number - - /** - * Gets the Uint8 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getUint8(byteOffset: number): number - - /** - * Gets the Uint16 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getUint16(byteOffset: number, littleEndian?: boolean): number - - /** - * Gets the Uint32 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ - getUint32(byteOffset: number, littleEndian?: boolean): number - - /** - * Stores an Float32 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void - - /** - * Stores an Float64 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void - - /** - * Stores an Int8 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - */ - setInt8(byteOffset: number, value: number): void - - /** - * Stores an Int16 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setInt16(byteOffset: number, value: number, littleEndian?: boolean): void - - /** - * Stores an Int32 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setInt32(byteOffset: number, value: number, littleEndian?: boolean): void - - /** - * Stores an Uint8 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - */ - setUint8(byteOffset: number, value: number): void - - /** - * Stores an Uint16 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setUint16(byteOffset: number, value: number, littleEndian?: boolean): void - - /** - * Stores an Uint32 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ - setUint32(byteOffset: number, value: number, littleEndian?: boolean): void -} - -interface DataViewConstructor { - readonly prototype: DataView - new ( - buffer: ArrayBufferLike, - byteOffset?: number, - byteLength?: number - ): DataView -} -declare var DataView: DataViewConstructor - -/** - * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Int8Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBufferLike - - /** - * The length in bytes of the array. - */ - readonly byteLength: number - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: (value: number, index: number, array: Int8Array) => unknown, - thisArg?: any - ): boolean - - /** - * Changes all array elements from \`start\` to \`end\` index to a static \`value\` and returns the modified array - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls - * the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: number, index: number, array: Int8Array) => any, - thisArg?: any - ): Int8Array - - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find( - predicate: (value: number, index: number, obj: Int8Array) => boolean, - thisArg?: any - ): number | undefined - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex( - predicate: (value: number, index: number, obj: Int8Array) => boolean, - thisArg?: any - ): number - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach( - callbackfn: (value: number, index: number, array: Int8Array) => void, - thisArg?: any - ): void - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number - - /** - * The length of the array. - */ - readonly length: number - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map( - callbackfn: (value: number, index: number, array: Int8Array) => number, - thisArg?: any - ): Int8Array - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Int8Array - ) => number - ): number - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Int8Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Int8Array - ) => U, - initialValue: U - ): U - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Int8Array - ) => number - ): number - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Int8Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Int8Array - ) => U, - initialValue: U - ): U - - /** - * Reverses the elements in an Array. - */ - reverse(): Int8Array - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. - */ - slice(start?: number, end?: number): Int8Array - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param predicate A function that accepts up to three arguments. The some method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - some( - predicate: (value: number, index: number, array: Int8Array) => unknown, - thisArg?: any - ): boolean - - /** - * Sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. - * \`\`\`ts - * [11,2,22,1].sort((a, b) => a - b) - * \`\`\` - */ - sort(compareFn?: (a: number, b: number) => number): this - - /** - * Gets a new Int8Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin?: number, end?: number): Int8Array - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string - - /** - * Returns a string representation of an array. - */ - toString(): string - - /** Returns the primitive value of the specified object. */ - valueOf(): Int8Array - - [index: number]: number -} -interface Int8ArrayConstructor { - readonly prototype: Int8Array - new (length: number): Int8Array - new (array: ArrayLike | ArrayBufferLike): Int8Array - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Int8Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - */ - from(arrayLike: ArrayLike): Int8Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from( - arrayLike: ArrayLike, - mapfn: (v: T, k: number) => number, - thisArg?: any - ): Int8Array -} -declare var Int8Array: Int8ArrayConstructor - -/** - * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBufferLike - - /** - * The length in bytes of the array. - */ - readonly byteLength: number - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: (value: number, index: number, array: Uint8Array) => unknown, - thisArg?: any - ): boolean - - /** - * Changes all array elements from \`start\` to \`end\` index to a static \`value\` and returns the modified array - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls - * the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: number, index: number, array: Uint8Array) => any, - thisArg?: any - ): Uint8Array - - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find( - predicate: (value: number, index: number, obj: Uint8Array) => boolean, - thisArg?: any - ): number | undefined - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex( - predicate: (value: number, index: number, obj: Uint8Array) => boolean, - thisArg?: any - ): number - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach( - callbackfn: (value: number, index: number, array: Uint8Array) => void, - thisArg?: any - ): void - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number - - /** - * The length of the array. - */ - readonly length: number - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map( - callbackfn: (value: number, index: number, array: Uint8Array) => number, - thisArg?: any - ): Uint8Array - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint8Array - ) => number - ): number - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint8Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Uint8Array - ) => U, - initialValue: U - ): U - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint8Array - ) => number - ): number - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint8Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Uint8Array - ) => U, - initialValue: U - ): U - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint8Array - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. - */ - slice(start?: number, end?: number): Uint8Array - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param predicate A function that accepts up to three arguments. The some method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - some( - predicate: (value: number, index: number, array: Uint8Array) => unknown, - thisArg?: any - ): boolean - - /** - * Sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. - * \`\`\`ts - * [11,2,22,1].sort((a, b) => a - b) - * \`\`\` - */ - sort(compareFn?: (a: number, b: number) => number): this - - /** - * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin?: number, end?: number): Uint8Array - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string - - /** - * Returns a string representation of an array. - */ - toString(): string - - /** Returns the primitive value of the specified object. */ - valueOf(): Uint8Array - - [index: number]: number -} - -interface Uint8ArrayConstructor { - readonly prototype: Uint8Array - new (length: number): Uint8Array - new (array: ArrayLike | ArrayBufferLike): Uint8Array - new ( - buffer: ArrayBufferLike, - byteOffset?: number, - length?: number - ): Uint8Array - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint8Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - */ - from(arrayLike: ArrayLike): Uint8Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from( - arrayLike: ArrayLike, - mapfn: (v: T, k: number) => number, - thisArg?: any - ): Uint8Array -} -declare var Uint8Array: Uint8ArrayConstructor - -/** - * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. - * If the requested number of bytes could not be allocated an exception is raised. - */ -interface Uint8ClampedArray { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBufferLike - - /** - * The length in bytes of the array. - */ - readonly byteLength: number - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: ( - value: number, - index: number, - array: Uint8ClampedArray - ) => unknown, - thisArg?: any - ): boolean - - /** - * Changes all array elements from \`start\` to \`end\` index to a static \`value\` and returns the modified array - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls - * the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: number, index: number, array: Uint8ClampedArray) => any, - thisArg?: any - ): Uint8ClampedArray - - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find( - predicate: ( - value: number, - index: number, - obj: Uint8ClampedArray - ) => boolean, - thisArg?: any - ): number | undefined - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex( - predicate: ( - value: number, - index: number, - obj: Uint8ClampedArray - ) => boolean, - thisArg?: any - ): number - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach( - callbackfn: ( - value: number, - index: number, - array: Uint8ClampedArray - ) => void, - thisArg?: any - ): void - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number - - /** - * The length of the array. - */ - readonly length: number - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map( - callbackfn: ( - value: number, - index: number, - array: Uint8ClampedArray - ) => number, - thisArg?: any - ): Uint8ClampedArray - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint8ClampedArray - ) => number - ): number - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint8ClampedArray - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Uint8ClampedArray - ) => U, - initialValue: U - ): U - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint8ClampedArray - ) => number - ): number - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint8ClampedArray - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Uint8ClampedArray - ) => U, - initialValue: U - ): U - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint8ClampedArray - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. - */ - slice(start?: number, end?: number): Uint8ClampedArray - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param predicate A function that accepts up to three arguments. The some method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - some( - predicate: ( - value: number, - index: number, - array: Uint8ClampedArray - ) => unknown, - thisArg?: any - ): boolean - - /** - * Sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. - * \`\`\`ts - * [11,2,22,1].sort((a, b) => a - b) - * \`\`\` - */ - sort(compareFn?: (a: number, b: number) => number): this - - /** - * Gets a new Uint8ClampedArray view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin?: number, end?: number): Uint8ClampedArray - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string - - /** - * Returns a string representation of an array. - */ - toString(): string - - /** Returns the primitive value of the specified object. */ - valueOf(): Uint8ClampedArray - - [index: number]: number -} - -interface Uint8ClampedArrayConstructor { - readonly prototype: Uint8ClampedArray - new (length: number): Uint8ClampedArray - new (array: ArrayLike | ArrayBufferLike): Uint8ClampedArray - new ( - buffer: ArrayBufferLike, - byteOffset?: number, - length?: number - ): Uint8ClampedArray - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint8ClampedArray - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - */ - from(arrayLike: ArrayLike): Uint8ClampedArray - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from( - arrayLike: ArrayLike, - mapfn: (v: T, k: number) => number, - thisArg?: any - ): Uint8ClampedArray -} -declare var Uint8ClampedArray: Uint8ClampedArrayConstructor - -/** - * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int16Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBufferLike - - /** - * The length in bytes of the array. - */ - readonly byteLength: number - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: (value: number, index: number, array: Int16Array) => unknown, - thisArg?: any - ): boolean - - /** - * Changes all array elements from \`start\` to \`end\` index to a static \`value\` and returns the modified array - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls - * the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: number, index: number, array: Int16Array) => any, - thisArg?: any - ): Int16Array - - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find( - predicate: (value: number, index: number, obj: Int16Array) => boolean, - thisArg?: any - ): number | undefined - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex( - predicate: (value: number, index: number, obj: Int16Array) => boolean, - thisArg?: any - ): number - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach( - callbackfn: (value: number, index: number, array: Int16Array) => void, - thisArg?: any - ): void - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number - - /** - * The length of the array. - */ - readonly length: number - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map( - callbackfn: (value: number, index: number, array: Int16Array) => number, - thisArg?: any - ): Int16Array - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Int16Array - ) => number - ): number - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Int16Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Int16Array - ) => U, - initialValue: U - ): U - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Int16Array - ) => number - ): number - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Int16Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Int16Array - ) => U, - initialValue: U - ): U - - /** - * Reverses the elements in an Array. - */ - reverse(): Int16Array - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. - */ - slice(start?: number, end?: number): Int16Array - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param predicate A function that accepts up to three arguments. The some method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - some( - predicate: (value: number, index: number, array: Int16Array) => unknown, - thisArg?: any - ): boolean - - /** - * Sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. - * \`\`\`ts - * [11,2,22,1].sort((a, b) => a - b) - * \`\`\` - */ - sort(compareFn?: (a: number, b: number) => number): this - - /** - * Gets a new Int16Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin?: number, end?: number): Int16Array - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string - - /** - * Returns a string representation of an array. - */ - toString(): string - - /** Returns the primitive value of the specified object. */ - valueOf(): Int16Array - - [index: number]: number -} - -interface Int16ArrayConstructor { - readonly prototype: Int16Array - new (length: number): Int16Array - new (array: ArrayLike | ArrayBufferLike): Int16Array - new ( - buffer: ArrayBufferLike, - byteOffset?: number, - length?: number - ): Int16Array - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Int16Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - */ - from(arrayLike: ArrayLike): Int16Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from( - arrayLike: ArrayLike, - mapfn: (v: T, k: number) => number, - thisArg?: any - ): Int16Array -} -declare var Int16Array: Int16ArrayConstructor - -/** - * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint16Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBufferLike - - /** - * The length in bytes of the array. - */ - readonly byteLength: number - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: (value: number, index: number, array: Uint16Array) => unknown, - thisArg?: any - ): boolean - - /** - * Changes all array elements from \`start\` to \`end\` index to a static \`value\` and returns the modified array - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls - * the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: number, index: number, array: Uint16Array) => any, - thisArg?: any - ): Uint16Array - - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find( - predicate: (value: number, index: number, obj: Uint16Array) => boolean, - thisArg?: any - ): number | undefined - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex( - predicate: (value: number, index: number, obj: Uint16Array) => boolean, - thisArg?: any - ): number - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach( - callbackfn: (value: number, index: number, array: Uint16Array) => void, - thisArg?: any - ): void - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number - - /** - * The length of the array. - */ - readonly length: number - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map( - callbackfn: (value: number, index: number, array: Uint16Array) => number, - thisArg?: any - ): Uint16Array - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint16Array - ) => number - ): number - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint16Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Uint16Array - ) => U, - initialValue: U - ): U - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint16Array - ) => number - ): number - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint16Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Uint16Array - ) => U, - initialValue: U - ): U - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint16Array - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. - */ - slice(start?: number, end?: number): Uint16Array - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param predicate A function that accepts up to three arguments. The some method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - some( - predicate: (value: number, index: number, array: Uint16Array) => unknown, - thisArg?: any - ): boolean - - /** - * Sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. - * \`\`\`ts - * [11,2,22,1].sort((a, b) => a - b) - * \`\`\` - */ - sort(compareFn?: (a: number, b: number) => number): this - - /** - * Gets a new Uint16Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin?: number, end?: number): Uint16Array - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string - - /** - * Returns a string representation of an array. - */ - toString(): string - - /** Returns the primitive value of the specified object. */ - valueOf(): Uint16Array - - [index: number]: number -} - -interface Uint16ArrayConstructor { - readonly prototype: Uint16Array - new (length: number): Uint16Array - new (array: ArrayLike | ArrayBufferLike): Uint16Array - new ( - buffer: ArrayBufferLike, - byteOffset?: number, - length?: number - ): Uint16Array - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint16Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - */ - from(arrayLike: ArrayLike): Uint16Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from( - arrayLike: ArrayLike, - mapfn: (v: T, k: number) => number, - thisArg?: any - ): Uint16Array -} -declare var Uint16Array: Uint16ArrayConstructor -/** - * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Int32Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBufferLike - - /** - * The length in bytes of the array. - */ - readonly byteLength: number - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: (value: number, index: number, array: Int32Array) => unknown, - thisArg?: any - ): boolean - - /** - * Changes all array elements from \`start\` to \`end\` index to a static \`value\` and returns the modified array - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls - * the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: number, index: number, array: Int32Array) => any, - thisArg?: any - ): Int32Array - - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find( - predicate: (value: number, index: number, obj: Int32Array) => boolean, - thisArg?: any - ): number | undefined - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex( - predicate: (value: number, index: number, obj: Int32Array) => boolean, - thisArg?: any - ): number - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach( - callbackfn: (value: number, index: number, array: Int32Array) => void, - thisArg?: any - ): void - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number - - /** - * The length of the array. - */ - readonly length: number - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map( - callbackfn: (value: number, index: number, array: Int32Array) => number, - thisArg?: any - ): Int32Array - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Int32Array - ) => number - ): number - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Int32Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Int32Array - ) => U, - initialValue: U - ): U - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Int32Array - ) => number - ): number - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Int32Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Int32Array - ) => U, - initialValue: U - ): U - - /** - * Reverses the elements in an Array. - */ - reverse(): Int32Array - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. - */ - slice(start?: number, end?: number): Int32Array - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param predicate A function that accepts up to three arguments. The some method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - some( - predicate: (value: number, index: number, array: Int32Array) => unknown, - thisArg?: any - ): boolean - - /** - * Sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. - * \`\`\`ts - * [11,2,22,1].sort((a, b) => a - b) - * \`\`\` - */ - sort(compareFn?: (a: number, b: number) => number): this - - /** - * Gets a new Int32Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin?: number, end?: number): Int32Array - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string - - /** - * Returns a string representation of an array. - */ - toString(): string - - /** Returns the primitive value of the specified object. */ - valueOf(): Int32Array - - [index: number]: number -} - -interface Int32ArrayConstructor { - readonly prototype: Int32Array - new (length: number): Int32Array - new (array: ArrayLike | ArrayBufferLike): Int32Array - new ( - buffer: ArrayBufferLike, - byteOffset?: number, - length?: number - ): Int32Array - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Int32Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - */ - from(arrayLike: ArrayLike): Int32Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from( - arrayLike: ArrayLike, - mapfn: (v: T, k: number) => number, - thisArg?: any - ): Int32Array -} -declare var Int32Array: Int32ArrayConstructor - -/** - * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated an exception is raised. - */ -interface Uint32Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBufferLike - - /** - * The length in bytes of the array. - */ - readonly byteLength: number - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: (value: number, index: number, array: Uint32Array) => unknown, - thisArg?: any - ): boolean - - /** - * Changes all array elements from \`start\` to \`end\` index to a static \`value\` and returns the modified array - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls - * the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: number, index: number, array: Uint32Array) => any, - thisArg?: any - ): Uint32Array - - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find( - predicate: (value: number, index: number, obj: Uint32Array) => boolean, - thisArg?: any - ): number | undefined - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex( - predicate: (value: number, index: number, obj: Uint32Array) => boolean, - thisArg?: any - ): number - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach( - callbackfn: (value: number, index: number, array: Uint32Array) => void, - thisArg?: any - ): void - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number - - /** - * The length of the array. - */ - readonly length: number - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map( - callbackfn: (value: number, index: number, array: Uint32Array) => number, - thisArg?: any - ): Uint32Array - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint32Array - ) => number - ): number - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint32Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Uint32Array - ) => U, - initialValue: U - ): U - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint32Array - ) => number - ): number - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Uint32Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Uint32Array - ) => U, - initialValue: U - ): U - - /** - * Reverses the elements in an Array. - */ - reverse(): Uint32Array - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. - */ - slice(start?: number, end?: number): Uint32Array - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param predicate A function that accepts up to three arguments. The some method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - some( - predicate: (value: number, index: number, array: Uint32Array) => unknown, - thisArg?: any - ): boolean - - /** - * Sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. - * \`\`\`ts - * [11,2,22,1].sort((a, b) => a - b) - * \`\`\` - */ - sort(compareFn?: (a: number, b: number) => number): this - - /** - * Gets a new Uint32Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin?: number, end?: number): Uint32Array - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string - - /** - * Returns a string representation of an array. - */ - toString(): string - - /** Returns the primitive value of the specified object. */ - valueOf(): Uint32Array - - [index: number]: number -} - -interface Uint32ArrayConstructor { - readonly prototype: Uint32Array - new (length: number): Uint32Array - new (array: ArrayLike | ArrayBufferLike): Uint32Array - new ( - buffer: ArrayBufferLike, - byteOffset?: number, - length?: number - ): Uint32Array - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Uint32Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - */ - from(arrayLike: ArrayLike): Uint32Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from( - arrayLike: ArrayLike, - mapfn: (v: T, k: number) => number, - thisArg?: any - ): Uint32Array -} -declare var Uint32Array: Uint32ArrayConstructor - -/** - * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number - * of bytes could not be allocated an exception is raised. - */ -interface Float32Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBufferLike - - /** - * The length in bytes of the array. - */ - readonly byteLength: number - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: (value: number, index: number, array: Float32Array) => unknown, - thisArg?: any - ): boolean - - /** - * Changes all array elements from \`start\` to \`end\` index to a static \`value\` and returns the modified array - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls - * the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: number, index: number, array: Float32Array) => any, - thisArg?: any - ): Float32Array - - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find( - predicate: (value: number, index: number, obj: Float32Array) => boolean, - thisArg?: any - ): number | undefined - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex( - predicate: (value: number, index: number, obj: Float32Array) => boolean, - thisArg?: any - ): number - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach( - callbackfn: (value: number, index: number, array: Float32Array) => void, - thisArg?: any - ): void - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number - - /** - * The length of the array. - */ - readonly length: number - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map( - callbackfn: (value: number, index: number, array: Float32Array) => number, - thisArg?: any - ): Float32Array - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Float32Array - ) => number - ): number - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Float32Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Float32Array - ) => U, - initialValue: U - ): U - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Float32Array - ) => number - ): number - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Float32Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Float32Array - ) => U, - initialValue: U - ): U - - /** - * Reverses the elements in an Array. - */ - reverse(): Float32Array - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. - */ - slice(start?: number, end?: number): Float32Array - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param predicate A function that accepts up to three arguments. The some method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - some( - predicate: (value: number, index: number, array: Float32Array) => unknown, - thisArg?: any - ): boolean - - /** - * Sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. - * \`\`\`ts - * [11,2,22,1].sort((a, b) => a - b) - * \`\`\` - */ - sort(compareFn?: (a: number, b: number) => number): this - - /** - * Gets a new Float32Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin?: number, end?: number): Float32Array - - /** - * Converts a number to a string by using the current locale. - */ - toLocaleString(): string - - /** - * Returns a string representation of an array. - */ - toString(): string - - /** Returns the primitive value of the specified object. */ - valueOf(): Float32Array - - [index: number]: number -} - -interface Float32ArrayConstructor { - readonly prototype: Float32Array - new (length: number): Float32Array - new (array: ArrayLike | ArrayBufferLike): Float32Array - new ( - buffer: ArrayBufferLike, - byteOffset?: number, - length?: number - ): Float32Array - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Float32Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - */ - from(arrayLike: ArrayLike): Float32Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from( - arrayLike: ArrayLike, - mapfn: (v: T, k: number) => number, - thisArg?: any - ): Float32Array -} -declare var Float32Array: Float32ArrayConstructor - -/** - * A typed array of 64-bit float values. The contents are initialized to 0. If the requested - * number of bytes could not be allocated an exception is raised. - */ -interface Float64Array { - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * The ArrayBuffer instance referenced by the array. - */ - readonly buffer: ArrayBufferLike - - /** - * The length in bytes of the array. - */ - readonly byteLength: number - - /** - * The offset in bytes of the array. - */ - readonly byteOffset: number - - /** - * Returns the this object after copying a section of the array identified by start and end - * to the same array starting at position target - * @param target If target is negative, it is treated as length+target where length is the - * length of the array. - * @param start If start is negative, it is treated as length+start. If end is negative, it - * is treated as length+end. - * @param end If not specified, length of the this object is used as its default value. - */ - copyWithin(target: number, start: number, end?: number): this - - /** - * Determines whether all the members of an array satisfy the specified test. - * @param predicate A function that accepts up to three arguments. The every method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value false, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - every( - predicate: (value: number, index: number, array: Float64Array) => unknown, - thisArg?: any - ): boolean - - /** - * Changes all array elements from \`start\` to \`end\` index to a static \`value\` and returns the modified array - * @param value value to fill array section with - * @param start index to start filling the array at. If start is negative, it is treated as - * length+start where length is the length of the array. - * @param end index to stop filling the array at. If end is negative, it is treated as - * length+end. - */ - fill(value: number, start?: number, end?: number): this - - /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @param predicate A function that accepts up to three arguments. The filter method calls - * the predicate function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - filter( - predicate: (value: number, index: number, array: Float64Array) => any, - thisArg?: any - ): Float64Array - - /** - * Returns the value of the first element in the array where predicate is true, and undefined - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, find - * immediately returns that element value. Otherwise, find returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - find( - predicate: (value: number, index: number, obj: Float64Array) => boolean, - thisArg?: any - ): number | undefined - - /** - * Returns the index of the first element in the array where predicate is true, and -1 - * otherwise. - * @param predicate find calls predicate once for each element of the array, in ascending - * order, until it finds one where predicate returns true. If such an element is found, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findIndex( - predicate: (value: number, index: number, obj: Float64Array) => boolean, - thisArg?: any - ): number - - /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - forEach( - callbackfn: (value: number, index: number, array: Float64Array) => void, - thisArg?: any - ): void - - /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - indexOf(searchElement: number, fromIndex?: number): number - - /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ - join(separator?: string): string - - /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ - lastIndexOf(searchElement: number, fromIndex?: number): number - - /** - * The length of the array. - */ - readonly length: number - - /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map method calls the - * callbackfn function one time for each element in the array. - * @param thisArg An object to which the this keyword can refer in the callbackfn function. - * If thisArg is omitted, undefined is used as the this value. - */ - map( - callbackfn: (value: number, index: number, array: Float64Array) => number, - thisArg?: any - ): Float64Array - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Float64Array - ) => number - ): number - reduce( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Float64Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array. The return value of - * the callback function is the accumulated result, and is provided as an argument in the next - * call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduce method calls the - * callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduce( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Float64Array - ) => U, - initialValue: U - ): U - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Float64Array - ) => number - ): number - reduceRight( - callbackfn: ( - previousValue: number, - currentValue: number, - currentIndex: number, - array: Float64Array - ) => number, - initialValue: number - ): number - - /** - * Calls the specified callback function for all the elements in an array, in descending order. - * The return value of the callback function is the accumulated result, and is provided as an - * argument in the next call to the callback function. - * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ - reduceRight( - callbackfn: ( - previousValue: U, - currentValue: number, - currentIndex: number, - array: Float64Array - ) => U, - initialValue: U - ): U - - /** - * Reverses the elements in an Array. - */ - reverse(): Float64Array - - /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ - set(array: ArrayLike, offset?: number): void - - /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. - */ - slice(start?: number, end?: number): Float64Array - - /** - * Determines whether the specified callback function returns true for any element of an array. - * @param predicate A function that accepts up to three arguments. The some method calls - * the predicate function for each element in the array until the predicate returns a value - * which is coercible to the Boolean value true, or until the end of the array. - * @param thisArg An object to which the this keyword can refer in the predicate function. - * If thisArg is omitted, undefined is used as the this value. - */ - some( - predicate: (value: number, index: number, array: Float64Array) => unknown, - thisArg?: any - ): boolean - - /** - * Sorts an array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if first argument is less than second argument, zero if they're equal and a positive - * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. - * \`\`\`ts - * [11,2,22,1].sort((a, b) => a - b) - * \`\`\` - */ - sort(compareFn?: (a: number, b: number) => number): this - - /** - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin?: number, end?: number): Float64Array - - toString(): string - - /** Returns the primitive value of the specified object. */ - valueOf(): Float64Array - - [index: number]: number -} - -interface Float64ArrayConstructor { - readonly prototype: Float64Array - new (length: number): Float64Array - new (array: ArrayLike | ArrayBufferLike): Float64Array - new ( - buffer: ArrayBufferLike, - byteOffset?: number, - length?: number - ): Float64Array - - /** - * The size in bytes of each element in the array. - */ - readonly BYTES_PER_ELEMENT: number - - /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ - of(...items: number[]): Float64Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - */ - from(arrayLike: ArrayLike): Float64Array - - /** - * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. - * @param mapfn A mapping function to call on every element of the array. - * @param thisArg Value of 'this' used to invoke the mapfn. - */ - from( - arrayLike: ArrayLike, - mapfn: (v: T, k: number) => number, - thisArg?: any - ): Float64Array -} -declare var Float64Array: Float64ArrayConstructor - -///////////////////////////// -/// ECMAScript Internationalization API -///////////////////////////// - -declare namespace Intl { - interface CollatorOptions { - usage?: string - localeMatcher?: string - numeric?: boolean - caseFirst?: string - sensitivity?: string - ignorePunctuation?: boolean - } - - interface ResolvedCollatorOptions { - locale: string - usage: string - sensitivity: string - ignorePunctuation: boolean - collation: string - caseFirst: string - numeric: boolean - } - - interface Collator { - compare(x: string, y: string): number - resolvedOptions(): ResolvedCollatorOptions - } - var Collator: { - new (locales?: string | string[], options?: CollatorOptions): Collator - (locales?: string | string[], options?: CollatorOptions): Collator - supportedLocalesOf( - locales: string | string[], - options?: CollatorOptions - ): string[] - } - - interface NumberFormatOptions { - localeMatcher?: string - style?: string - currency?: string - currencyDisplay?: string - currencySign?: string - useGrouping?: boolean - minimumIntegerDigits?: number - minimumFractionDigits?: number - maximumFractionDigits?: number - minimumSignificantDigits?: number - maximumSignificantDigits?: number - } - - interface ResolvedNumberFormatOptions { - locale: string - numberingSystem: string - style: string - currency?: string - currencyDisplay?: string - minimumIntegerDigits: number - minimumFractionDigits: number - maximumFractionDigits: number - minimumSignificantDigits?: number - maximumSignificantDigits?: number - useGrouping: boolean - } - - interface NumberFormat { - format(value: number): string - resolvedOptions(): ResolvedNumberFormatOptions - } - var NumberFormat: { - new ( - locales?: string | string[], - options?: NumberFormatOptions - ): NumberFormat - (locales?: string | string[], options?: NumberFormatOptions): NumberFormat - supportedLocalesOf( - locales: string | string[], - options?: NumberFormatOptions - ): string[] - } - - interface DateTimeFormatOptions { - localeMatcher?: 'best fit' | 'lookup' - weekday?: 'long' | 'short' | 'narrow' - era?: 'long' | 'short' | 'narrow' - year?: 'numeric' | '2-digit' - month?: 'numeric' | '2-digit' | 'long' | 'short' | 'narrow' - day?: 'numeric' | '2-digit' - hour?: 'numeric' | '2-digit' - minute?: 'numeric' | '2-digit' - second?: 'numeric' | '2-digit' - timeZoneName?: 'long' | 'short' - formatMatcher?: 'best fit' | 'basic' - hour12?: boolean - timeZone?: string - } - - interface ResolvedDateTimeFormatOptions { - locale: string - calendar: string - numberingSystem: string - timeZone: string - hour12?: boolean - weekday?: string - era?: string - year?: string - month?: string - day?: string - hour?: string - minute?: string - second?: string - timeZoneName?: string - } - - interface DateTimeFormat { - format(date?: Date | number): string - resolvedOptions(): ResolvedDateTimeFormatOptions - } - var DateTimeFormat: { - new ( - locales?: string | string[], - options?: DateTimeFormatOptions - ): DateTimeFormat - ( - locales?: string | string[], - options?: DateTimeFormatOptions - ): DateTimeFormat - supportedLocalesOf( - locales: string | string[], - options?: DateTimeFormatOptions - ): string[] - } -} - -interface String { - /** - * Determines whether two strings are equivalent in the current or specified locale. - * @param that String to compare to target string - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. - * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. - */ - localeCompare( - that: string, - locales?: string | string[], - options?: Intl.CollatorOptions - ): number -} - -interface Number { - /** - * Converts a number to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString( - locales?: string | string[], - options?: Intl.NumberFormatOptions - ): string -} - -interface Date { - /** - * Converts a date and time to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleString( - locales?: string | string[], - options?: Intl.DateTimeFormatOptions - ): string - /** - * Converts a date to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleDateString( - locales?: string | string[], - options?: Intl.DateTimeFormatOptions - ): string - - /** - * Converts a time to a string by using the current or specified locale. - * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. - * @param options An object that contains one or more properties that specify comparison options. - */ - toLocaleTimeString( - locales?: string | string[], - options?: Intl.DateTimeFormatOptions - ): string -} -`, -} diff --git a/components/code-panel/types-import.ts b/components/code-panel/types-import.ts deleted file mode 100644 index 63d7eb7e1..000000000 --- a/components/code-panel/types-import.ts +++ /dev/null @@ -1,3469 +0,0 @@ -/* eslint-disable */ - -// HEY! DO NOT MODIFY THIS FILE. THE CONTENTS OF THIS FILE -// ARE AUTO-GENERATED BY A SCRIPT AT: /scripts/type-gen.js -// ANY CHANGES WILL BE LOST WHEN THE SCRIPT RUNS AGAIN! - -export default { - name: 'types.ts', - content: ` - -type DeepPartial = { - [P in keyof T]?: DeepPartial; -}; - - - -enum ShapeType { - Dot = 'dot', - Ellipse = 'ellipse', - Line = 'line', - Ray = 'ray', - Polyline = 'polyline', - Rectangle = 'rectangle', - Draw = 'draw', - Arrow = 'arrow', - Text = 'text', - Group = 'group', -} - -enum ColorStyle { - White = 'White', - LightGray = 'LightGray', - Gray = 'Gray', - Black = 'Black', - Green = 'Green', - Cyan = 'Cyan', - Blue = 'Blue', - Indigo = 'Indigo', - Violet = 'Violet', - Red = 'Red', - Orange = 'Orange', - Yellow = 'Yellow', -} - -enum SizeStyle { - Small = 'Small', - Medium = 'Medium', - Large = 'Large', -} - -enum DashStyle { - Draw = 'Draw', - Solid = 'Solid', - Dashed = 'Dashed', - Dotted = 'Dotted', -} - -enum FontSize { - Small = 'Small', - Medium = 'Medium', - Large = 'Large', - ExtraLarge = 'ExtraLarge', -} - -type Theme = 'dark' | 'light' - -type ShapeStyles = { - color: ColorStyle - size: SizeStyle - dash: DashStyle - isFilled: boolean -} - -interface BaseShape { - id: string - type: ShapeType - parentId: string - childIndex: number - name: string - point: number[] - style: ShapeStyles - rotation: number - children?: string[] - bindings?: Record - handles?: Record - isLocked?: boolean - isHidden?: boolean - isEditing?: boolean - isGenerated?: boolean - isAspectRatioLocked?: boolean -} - -interface DotShape extends BaseShape { - type: ShapeType.Dot -} - -interface EllipseShape extends BaseShape { - type: ShapeType.Ellipse - radiusX: number - radiusY: number -} - -interface LineShape extends BaseShape { - type: ShapeType.Line - direction: number[] -} - -interface RayShape extends BaseShape { - type: ShapeType.Ray - direction: number[] -} - -interface PolylineShape extends BaseShape { - type: ShapeType.Polyline - points: number[][] -} - -interface RectangleShape extends BaseShape { - type: ShapeType.Rectangle - size: number[] - radius: number -} - -interface DrawShape extends BaseShape { - type: ShapeType.Draw - points: number[][] -} - -interface ArrowShape extends BaseShape { - type: ShapeType.Arrow - handles: Record - bend: number - decorations?: { - start: Decoration - end: Decoration - middle: Decoration - } -} - -interface TextShape extends BaseShape { - type: ShapeType.Text - text: string - scale: number -} - -interface GroupShape extends BaseShape { - type: ShapeType.Group - children: string[] - size: number[] -} - -type ShapeProps = { - [P in keyof T]?: P extends 'style' ? Partial : T[P] -} - -interface MutableShapes { - [ShapeType.Dot]: DotShape - [ShapeType.Ellipse]: EllipseShape - [ShapeType.Line]: LineShape - [ShapeType.Ray]: RayShape - [ShapeType.Polyline]: PolylineShape - [ShapeType.Draw]: DrawShape - [ShapeType.Rectangle]: RectangleShape - [ShapeType.Arrow]: ArrowShape - [ShapeType.Text]: TextShape - [ShapeType.Group]: GroupShape -} - -type MutableShape = MutableShapes[keyof MutableShapes] - -type Shapes = { [K in keyof MutableShapes]: Readonly } - -type Shape = Readonly - -type ShapeByType = Shapes[T] - -type IsParent = 'children' extends RequiredKeys ? T : never - -type ParentShape = { - [K in keyof MutableShapes]: IsParent -}[keyof MutableShapes] - -type ParentTypes = ParentShape['type'] & 'page' - -enum Decoration { - Arrow = 'Arrow', -} - -interface ShapeBinding { - id: string - index: number - point: number[] -} - -interface ShapeHandle { - id: string - index: number - point: number[] -} - -interface CodeFile { - id: string - name: string - code: string -} - -interface CodeError { - message: string - line: number - column: number -} - -interface CodeResult { - shapes: Shape[] - controls: CodeControl[] - error: CodeError -} - -interface ShapeTreeNode { - shape: Shape - children: ShapeTreeNode[] - isEditing: boolean - isHovered: boolean - isSelected: boolean - isDarkMode: boolean - isCurrentParent: boolean -} - -/* -------------------------------------------------- */ -/* Editor UI */ -/* -------------------------------------------------- */ - -interface PointerInfo { - target: string - pointerId: number - origin: number[] - point: number[] - pressure: number - shiftKey: boolean - ctrlKey: boolean - metaKey: boolean - altKey: boolean -} - -interface KeyboardInfo { - key: string - keys: string[] - shiftKey: boolean - ctrlKey: boolean - metaKey: boolean - altKey: boolean -} - -enum Edge { - Top = 'top_edge', - Right = 'right_edge', - Bottom = 'bottom_edge', - Left = 'left_edge', -} - -enum Corner { - TopLeft = 'top_left_corner', - TopRight = 'top_right_corner', - BottomRight = 'bottom_right_corner', - BottomLeft = 'bottom_left_corner', -} - -interface Bounds { - minX: number - minY: number - maxX: number - maxY: number - width: number - height: number - rotation?: number -} - -interface RotatedBounds extends Bounds { - rotation: number -} - -interface ShapeBounds extends Bounds { - id: string -} - -interface PointSnapshot extends Bounds { - nx: number - nmx: number - ny: number - nmy: number -} - -interface BoundsSnapshot extends PointSnapshot { - nw: number - nh: number -} - -type ShapeSpecificProps = Pick< - T, - Difference -> - -type ShapeIndicatorProps = ShapeSpecificProps - -type ShapeUtil = { - create(props: Partial): K - getBounds(shape: K): Bounds - hitTest(shape: K, test: number[]): boolean - hitTestBounds(shape: K, bounds: Bounds): boolean - rotate(shape: K): K - translate(shape: K, delta: number[]): K - scale(shape: K, scale: number): K - stretch(shape: K, scaleX: number, scaleY: number): K - render(shape: K): JSX.Element -} - -enum MoveType { - Backward, - Forward, - ToFront, - ToBack, -} - -enum AlignType { - Top, - CenterVertical, - Bottom, - Left, - CenterHorizontal, - Right, -} - -enum StretchType { - Horizontal, - Vertical, -} - -enum DistributeType { - Horizontal, - Vertical, -} - -interface BezierCurveSegment { - start: number[] - tangentStart: number[] - normalStart: number[] - pressureStart: number - end: number[] - tangentEnd: number[] - normalEnd: number[] - pressureEnd: number -} - -/* -------------------------------------------------- */ -/* Code Editor */ -/* -------------------------------------------------- */ - -enum ControlType { - Number = 'number', - Vector = 'vector', - Text = 'text', - Select = 'select', -} - -interface BaseCodeControl { - id: string - type: ControlType - label: string -} - -interface NumberCodeControl extends BaseCodeControl { - type: ControlType.Number - value: number - min?: number - max?: number - step?: number - format?: (value: number) => number -} - -interface VectorCodeControl extends BaseCodeControl { - type: ControlType.Vector - value: number[] - min?: number - max?: number - step?: number - isNormalized?: boolean - format?: (value: number[]) => number[] -} - -interface TextCodeControl extends BaseCodeControl { - type: ControlType.Text - value: string - format?: (value: string) => string -} - -interface SelectCodeControl - extends BaseCodeControl { - type: ControlType.Select - value: T - options: T[] - format?: (string: T) => string -} - -type CodeControl = - | NumberCodeControl - | VectorCodeControl - | TextCodeControl - -type PropsOfType> = { - [K in keyof T]: T[K] extends boolean ? K : never -}[keyof T] - -type Mutable = { -readonly [K in keyof T]: T[K] } - -interface ShapeUtility { - // Default properties when creating a new shape - defaultProps: K - - // A cache for the computed bounds of this kind of shape. - boundsCache: WeakMap - - // Whether to show transform controls when this shape is selected. - canTransform: boolean - - // Whether the shape's aspect ratio can change. - canChangeAspectRatio: boolean - - // Whether the shape's style can be filled. - canStyleFill: boolean - - // Whether the shape may be edited in an editing mode - canEdit: boolean - - // Whether the shape is a foreign object. - isForeignObject: boolean - - // Whether the shape can contain other shapes. - isParent: boolean - - // Whether the shape is only shown when on hovered. - isShy: boolean - - // Create a new shape. - create(this: ShapeUtility, props: Partial): K - - // Update a shape's styles - applyStyles( - this: ShapeUtility, - shape: Mutable, - style: Partial - ): ShapeUtility - - translateBy( - this: ShapeUtility, - shape: Mutable, - point: number[] - ): ShapeUtility - - translateTo( - this: ShapeUtility, - shape: Mutable, - point: number[] - ): ShapeUtility - - rotateBy( - this: ShapeUtility, - shape: Mutable, - rotation: number - ): ShapeUtility - - rotateTo( - this: ShapeUtility, - shape: Mutable, - rotation: number, - delta: number - ): ShapeUtility - - // Transform to fit a new bounding box when more than one shape is selected. - transform( - this: ShapeUtility, - shape: Mutable, - bounds: Bounds, - info: { - type: Edge | Corner - initialShape: K - scaleX: number - scaleY: number - transformOrigin: number[] - } - ): ShapeUtility - - // Transform a single shape to fit a new bounding box. - transformSingle( - this: ShapeUtility, - shape: Mutable, - bounds: Bounds, - info: { - type: Edge | Corner - initialShape: K - scaleX: number - scaleY: number - transformOrigin: number[] - } - ): ShapeUtility - - setProperty

( - this: ShapeUtility, - shape: Mutable, - prop: P, - value: K[P] - ): ShapeUtility - - // Respond when any child of this shape changes. - onChildrenChange( - this: ShapeUtility, - shape: Mutable, - children: Shape[] - ): ShapeUtility - - // Respond when a user moves one of the shape's bound elements. - onBindingChange( - this: ShapeUtility, - shape: Mutable, - bindings: Record - ): ShapeUtility - - // Respond when a user moves one of the shape's handles. - onHandleChange( - this: ShapeUtility, - shape: Mutable, - handle: Partial, - info?: Partial<{ - delta: number[] - shiftKey: boolean - altKey: boolean - metaKey: boolean - }> - ): ShapeUtility - - onDoublePointHandle( - this: ShapeUtility, - shape: Mutable, - handle: keyof K['handles'], - info: PointerInfo - ): ShapeUtility - - // Respond when a user double clicks the shape's bounds. - onBoundsReset(this: ShapeUtility, shape: Mutable): ShapeUtility - - // Respond when a user double clicks the center of the shape. - onDoubleFocus(this: ShapeUtility, shape: Mutable): ShapeUtility - - // Clean up changes when a session ends. - onSessionComplete(this: ShapeUtility, shape: Mutable): ShapeUtility - - // Render a shape to JSX. - render( - this: ShapeUtility, - shape: K, - info?: { - isEditing?: boolean - isHovered?: boolean - isSelected?: boolean - isCurrentParent?: boolean - isDarkMode?: boolean - ref?: React.MutableRefObject - } - ): JSX.Element - - invalidate(this: ShapeUtility, shape: K): ShapeUtility - - // Get the bounds of the a shape. - getBounds(this: ShapeUtility, shape: K): Bounds - - // Get the routated bounds of the a shape. - getRotatedBounds(this: ShapeUtility, shape: K): Bounds - - // Get the center of the shape - getCenter(this: ShapeUtility, shape: K): number[] - - // Test whether a point lies within a shape. - hitTest(this: ShapeUtility, shape: K, test: number[]): boolean - - // Test whether bounds collide with or contain a shape. - hitTestBounds(this: ShapeUtility, shape: K, bounds: Bounds): boolean - - // Get whether the shape should delete - shouldDelete(this: ShapeUtility, shape: K): boolean - - // Get whether the shape should render - shouldRender(this: ShapeUtility, shape: K, previous: K): boolean -} - -/* -------------------------------------------------- */ -/* Utilities */ -/* -------------------------------------------------- */ - -type Difference = A extends B ? never : A - -type RequiredKeys = { - [K in keyof T]-?: Record extends Pick ? never : K -}[keyof T] - - - - -enum ShapeType { - Dot = 'dot', - Ellipse = 'ellipse', - Line = 'line', - Ray = 'ray', - Polyline = 'polyline', - Rectangle = 'rectangle', - Draw = 'draw', - Arrow = 'arrow', - Text = 'text', - Group = 'group', -} - -enum ColorStyle { - White = 'White', - LightGray = 'LightGray', - Gray = 'Gray', - Black = 'Black', - Green = 'Green', - Cyan = 'Cyan', - Blue = 'Blue', - Indigo = 'Indigo', - Violet = 'Violet', - Red = 'Red', - Orange = 'Orange', - Yellow = 'Yellow', -} - -enum SizeStyle { - Small = 'Small', - Medium = 'Medium', - Large = 'Large', -} - -enum DashStyle { - Draw = 'Draw', - Solid = 'Solid', - Dashed = 'Dashed', - Dotted = 'Dotted', -} - -enum FontSize { - Small = 'Small', - Medium = 'Medium', - Large = 'Large', - ExtraLarge = 'ExtraLarge', -} - -type Theme = 'dark' | 'light' - -type ShapeStyles = { - color: ColorStyle - size: SizeStyle - dash: DashStyle - isFilled: boolean -} - -interface BaseShape { - id: string - type: ShapeType - parentId: string - childIndex: number - name: string - point: number[] - style: ShapeStyles - rotation: number - children?: string[] - bindings?: Record - handles?: Record - isLocked?: boolean - isHidden?: boolean - isEditing?: boolean - isGenerated?: boolean - isAspectRatioLocked?: boolean -} - -interface DotShape extends BaseShape { - type: ShapeType.Dot -} - -interface EllipseShape extends BaseShape { - type: ShapeType.Ellipse - radiusX: number - radiusY: number -} - -interface LineShape extends BaseShape { - type: ShapeType.Line - direction: number[] -} - -interface RayShape extends BaseShape { - type: ShapeType.Ray - direction: number[] -} - -interface PolylineShape extends BaseShape { - type: ShapeType.Polyline - points: number[][] -} - -interface RectangleShape extends BaseShape { - type: ShapeType.Rectangle - size: number[] - radius: number -} - -interface DrawShape extends BaseShape { - type: ShapeType.Draw - points: number[][] -} - -interface ArrowShape extends BaseShape { - type: ShapeType.Arrow - handles: Record - bend: number - decorations?: { - start: Decoration - end: Decoration - middle: Decoration - } -} - -interface TextShape extends BaseShape { - type: ShapeType.Text - text: string - scale: number -} - -interface GroupShape extends BaseShape { - type: ShapeType.Group - children: string[] - size: number[] -} - -type ShapeProps = { - [P in keyof T]?: P extends 'style' ? Partial : T[P] -} - -interface MutableShapes { - [ShapeType.Dot]: DotShape - [ShapeType.Ellipse]: EllipseShape - [ShapeType.Line]: LineShape - [ShapeType.Ray]: RayShape - [ShapeType.Polyline]: PolylineShape - [ShapeType.Draw]: DrawShape - [ShapeType.Rectangle]: RectangleShape - [ShapeType.Arrow]: ArrowShape - [ShapeType.Text]: TextShape - [ShapeType.Group]: GroupShape -} - -type MutableShape = MutableShapes[keyof MutableShapes] - -type Shapes = { [K in keyof MutableShapes]: Readonly } - -type Shape = Readonly - -type ShapeByType = Shapes[T] - -type IsParent = 'children' extends RequiredKeys ? T : never - -type ParentShape = { - [K in keyof MutableShapes]: IsParent -}[keyof MutableShapes] - -type ParentTypes = ParentShape['type'] & 'page' - -enum Decoration { - Arrow = 'Arrow', -} - -interface ShapeBinding { - id: string - index: number - point: number[] -} - -interface ShapeHandle { - id: string - index: number - point: number[] -} - -interface CodeFile { - id: string - name: string - code: string -} - -interface CodeError { - message: string - line: number - column: number -} - -interface CodeResult { - shapes: Shape[] - controls: CodeControl[] - error: CodeError -} - -interface ShapeTreeNode { - shape: Shape - children: ShapeTreeNode[] - isEditing: boolean - isHovered: boolean - isSelected: boolean - isDarkMode: boolean - isCurrentParent: boolean -} - -/* -------------------------------------------------- */ -/* Editor UI */ -/* -------------------------------------------------- */ - -interface PointerInfo { - target: string - pointerId: number - origin: number[] - point: number[] - pressure: number - shiftKey: boolean - ctrlKey: boolean - metaKey: boolean - altKey: boolean -} - -interface KeyboardInfo { - key: string - keys: string[] - shiftKey: boolean - ctrlKey: boolean - metaKey: boolean - altKey: boolean -} - -enum Edge { - Top = 'top_edge', - Right = 'right_edge', - Bottom = 'bottom_edge', - Left = 'left_edge', -} - -enum Corner { - TopLeft = 'top_left_corner', - TopRight = 'top_right_corner', - BottomRight = 'bottom_right_corner', - BottomLeft = 'bottom_left_corner', -} - -interface Bounds { - minX: number - minY: number - maxX: number - maxY: number - width: number - height: number - rotation?: number -} - -interface RotatedBounds extends Bounds { - rotation: number -} - -interface ShapeBounds extends Bounds { - id: string -} - -interface PointSnapshot extends Bounds { - nx: number - nmx: number - ny: number - nmy: number -} - -interface BoundsSnapshot extends PointSnapshot { - nw: number - nh: number -} - -type ShapeSpecificProps = Pick< - T, - Difference -> - -type ShapeIndicatorProps = ShapeSpecificProps - -type ShapeUtil = { - create(props: Partial): K - getBounds(shape: K): Bounds - hitTest(shape: K, test: number[]): boolean - hitTestBounds(shape: K, bounds: Bounds): boolean - rotate(shape: K): K - translate(shape: K, delta: number[]): K - scale(shape: K, scale: number): K - stretch(shape: K, scaleX: number, scaleY: number): K - render(shape: K): JSX.Element -} - -enum MoveType { - Backward, - Forward, - ToFront, - ToBack, -} - -enum AlignType { - Top, - CenterVertical, - Bottom, - Left, - CenterHorizontal, - Right, -} - -enum StretchType { - Horizontal, - Vertical, -} - -enum DistributeType { - Horizontal, - Vertical, -} - -interface BezierCurveSegment { - start: number[] - tangentStart: number[] - normalStart: number[] - pressureStart: number - end: number[] - tangentEnd: number[] - normalEnd: number[] - pressureEnd: number -} - -/* -------------------------------------------------- */ -/* Code Editor */ -/* -------------------------------------------------- */ - -enum ControlType { - Number = 'number', - Vector = 'vector', - Text = 'text', - Select = 'select', -} - -interface BaseCodeControl { - id: string - type: ControlType - label: string -} - -interface NumberCodeControl extends BaseCodeControl { - type: ControlType.Number - value: number - min?: number - max?: number - step?: number - format?: (value: number) => number -} - -interface VectorCodeControl extends BaseCodeControl { - type: ControlType.Vector - value: number[] - min?: number - max?: number - step?: number - isNormalized?: boolean - format?: (value: number[]) => number[] -} - -interface TextCodeControl extends BaseCodeControl { - type: ControlType.Text - value: string - format?: (value: string) => string -} - -interface SelectCodeControl - extends BaseCodeControl { - type: ControlType.Select - value: T - options: T[] - format?: (string: T) => string -} - -type CodeControl = - | NumberCodeControl - | VectorCodeControl - | TextCodeControl - -type PropsOfType> = { - [K in keyof T]: T[K] extends boolean ? K : never -}[keyof T] - -type Mutable = { -readonly [K in keyof T]: T[K] } - -interface ShapeUtility { - // Default properties when creating a new shape - defaultProps: K - - // A cache for the computed bounds of this kind of shape. - boundsCache: WeakMap - - // Whether to show transform controls when this shape is selected. - canTransform: boolean - - // Whether the shape's aspect ratio can change. - canChangeAspectRatio: boolean - - // Whether the shape's style can be filled. - canStyleFill: boolean - - // Whether the shape may be edited in an editing mode - canEdit: boolean - - // Whether the shape is a foreign object. - isForeignObject: boolean - - // Whether the shape can contain other shapes. - isParent: boolean - - // Whether the shape is only shown when on hovered. - isShy: boolean - - // Create a new shape. - create(this: ShapeUtility, props: Partial): K - - // Update a shape's styles - applyStyles( - this: ShapeUtility, - shape: Mutable, - style: Partial - ): ShapeUtility - - translateBy( - this: ShapeUtility, - shape: Mutable, - point: number[] - ): ShapeUtility - - translateTo( - this: ShapeUtility, - shape: Mutable, - point: number[] - ): ShapeUtility - - rotateBy( - this: ShapeUtility, - shape: Mutable, - rotation: number - ): ShapeUtility - - rotateTo( - this: ShapeUtility, - shape: Mutable, - rotation: number, - delta: number - ): ShapeUtility - - // Transform to fit a new bounding box when more than one shape is selected. - transform( - this: ShapeUtility, - shape: Mutable, - bounds: Bounds, - info: { - type: Edge | Corner - initialShape: K - scaleX: number - scaleY: number - transformOrigin: number[] - } - ): ShapeUtility - - // Transform a single shape to fit a new bounding box. - transformSingle( - this: ShapeUtility, - shape: Mutable, - bounds: Bounds, - info: { - type: Edge | Corner - initialShape: K - scaleX: number - scaleY: number - transformOrigin: number[] - } - ): ShapeUtility - - setProperty

( - this: ShapeUtility, - shape: Mutable, - prop: P, - value: K[P] - ): ShapeUtility - - // Respond when any child of this shape changes. - onChildrenChange( - this: ShapeUtility, - shape: Mutable, - children: Shape[] - ): ShapeUtility - - // Respond when a user moves one of the shape's bound elements. - onBindingChange( - this: ShapeUtility, - shape: Mutable, - bindings: Record - ): ShapeUtility - - // Respond when a user moves one of the shape's handles. - onHandleChange( - this: ShapeUtility, - shape: Mutable, - handle: Partial, - info?: Partial<{ - delta: number[] - shiftKey: boolean - altKey: boolean - metaKey: boolean - }> - ): ShapeUtility - - onDoublePointHandle( - this: ShapeUtility, - shape: Mutable, - handle: keyof K['handles'], - info: PointerInfo - ): ShapeUtility - - // Respond when a user double clicks the shape's bounds. - onBoundsReset(this: ShapeUtility, shape: Mutable): ShapeUtility - - // Respond when a user double clicks the center of the shape. - onDoubleFocus(this: ShapeUtility, shape: Mutable): ShapeUtility - - // Clean up changes when a session ends. - onSessionComplete(this: ShapeUtility, shape: Mutable): ShapeUtility - - // Render a shape to JSX. - render( - this: ShapeUtility, - shape: K, - info?: { - isEditing?: boolean - isHovered?: boolean - isSelected?: boolean - isCurrentParent?: boolean - isDarkMode?: boolean - ref?: React.MutableRefObject - } - ): JSX.Element - - invalidate(this: ShapeUtility, shape: K): ShapeUtility - - // Get the bounds of the a shape. - getBounds(this: ShapeUtility, shape: K): Bounds - - // Get the routated bounds of the a shape. - getRotatedBounds(this: ShapeUtility, shape: K): Bounds - - // Get the center of the shape - getCenter(this: ShapeUtility, shape: K): number[] - - // Test whether a point lies within a shape. - hitTest(this: ShapeUtility, shape: K, test: number[]): boolean - - // Test whether bounds collide with or contain a shape. - hitTestBounds(this: ShapeUtility, shape: K, bounds: Bounds): boolean - - // Get whether the shape should delete - shouldDelete(this: ShapeUtility, shape: K): boolean - - // Get whether the shape should render - shouldRender(this: ShapeUtility, shape: K, previous: K): boolean -} - -/* -------------------------------------------------- */ -/* Utilities */ -/* -------------------------------------------------- */ - -type Difference = A extends B ? never : A - -type RequiredKeys = { - [K in keyof T]-?: Record extends Pick ? never : K -}[keyof T] - - - - - class Vec { - /** - * Clamp a value into a range. - * @param n - * @param min - */ - static clamp(n: number, min: number): number - static clamp(n: number, min: number, max: number): number - static clamp(n: number, min: number, max?: number): number { - return Math.max(min, typeof max !== 'undefined' ? Math.min(n, max) : n) - } - - /** - * Negate a vector. - * @param A - */ - static neg = (A: number[]): number[] => { - return [-A[0], -A[1]] - } - - /** - * Add vectors. - * @param A - * @param B - */ - static add = (A: number[], B: number[]): number[] => { - return [A[0] + B[0], A[1] + B[1]] - } - - /** - * Add scalar to vector. - * @param A - * @param B - */ - static addScalar = (A: number[], n: number): number[] => { - return [A[0] + n, A[1] + n] - } - - /** - * Subtract vectors. - * @param A - * @param B - */ - static sub = (A: number[], B: number[]): number[] => { - return [A[0] - B[0], A[1] - B[1]] - } - - /** - * Subtract scalar from vector. - * @param A - * @param B - */ - static subScalar = (A: number[], n: number): number[] => { - return [A[0] - n, A[1] - n] - } - - /** - * Get the vector from vectors A to B. - * @param A - * @param B - */ - static vec = (A: number[], B: number[]): number[] => { - // A, B as vectors get the vector from A to B - return [B[0] - A[0], B[1] - A[1]] - } - - /** - * Vector multiplication by scalar - * @param A - * @param n - */ - static mul = (A: number[], n: number): number[] => { - return [A[0] * n, A[1] * n] - } - - static mulV = (A: number[], B: number[]): number[] => { - return [A[0] * B[0], A[1] * B[1]] - } - - /** - * Vector division by scalar. - * @param A - * @param n - */ - static div = (A: number[], n: number): number[] => { - return [A[0] / n, A[1] / n] - } - - /** - * Vector division by vector. - * @param A - * @param n - */ - static divV = (A: number[], B: number[]): number[] => { - return [A[0] / B[0], A[1] / B[1]] - } - - /** - * Perpendicular rotation of a vector A - * @param A - */ - static per = (A: number[]): number[] => { - return [A[1], -A[0]] - } - - /** - * Dot product - * @param A - * @param B - */ - static dpr = (A: number[], B: number[]): number => { - return A[0] * B[0] + A[1] * B[1] - } - - /** - * Cross product (outer product) | A X B | - * @param A - * @param B - */ - static cpr = (A: number[], B: number[]): number => { - return A[0] * B[1] - B[0] * A[1] - } - - /** - * Length of the vector squared - * @param A - */ - static len2 = (A: number[]): number => { - return A[0] * A[0] + A[1] * A[1] - } - - /** - * Length of the vector - * @param A - */ - static len = (A: number[]): number => { - return Math.hypot(A[0], A[1]) - } - - /** - * Project A over B - * @param A - * @param B - */ - static pry = (A: number[], B: number[]): number => { - return Vec.dpr(A, B) / Vec.len(B) - } - - /** - * Get normalized / unit vector. - * @param A - */ - static uni = (A: number[]): number[] => { - return Vec.div(A, Vec.len(A)) - } - - /** - * Get normalized / unit vector. - * @param A - */ - static normalize = (A: number[]): number[] => { - return Vec.uni(A) - } - - /** - * Get the tangent between two vectors. - * @param A - * @param B - * @returns - */ - static tangent = (A: number[], B: number[]): number[] => { - return Vec.normalize(Vec.sub(A, B)) - } - - /** - * Dist length from A to B squared. - * @param A - * @param B - */ - static dist2 = (A: number[], B: number[]): number => { - return Vec.len2(Vec.sub(A, B)) - } - - /** - * Dist length from A to B - * @param A - * @param B - */ - static dist = (A: number[], B: number[]): number => { - return Math.hypot(A[1] - B[1], A[0] - B[0]) - } - - /** - * A faster, though less accurate method for testing distances. Maybe faster? - * @param A - * @param B - * @returns - */ - static fastDist = (A: number[], B: number[]): number[] => { - const V = [B[0] - A[0], B[1] - A[1]] - const aV = [Math.abs(V[0]), Math.abs(V[1])] - let r = 1 / Math.max(aV[0], aV[1]) - r = r * (1.29289 - (aV[0] + aV[1]) * r * 0.29289) - return [V[0] * r, V[1] * r] - } - - /** - * Angle between vector A and vector B in radians - * @param A - * @param B - */ - static ang = (A: number[], B: number[]): number => { - return Math.atan2(Vec.cpr(A, B), Vec.dpr(A, B)) - } - - /** - * Angle between vector A and vector B in radians - * @param A - * @param B - */ - static angle = (A: number[], B: number[]): number => { - return Math.atan2(B[1] - A[1], B[0] - A[0]) - } - - /** - * Mean between two vectors or mid vector between two vectors - * @param A - * @param B - */ - static med = (A: number[], B: number[]): number[] => { - return Vec.mul(Vec.add(A, B), 0.5) - } - - /** - * Vector rotation by r (radians) - * @param A - * @param r rotation in radians - */ - static rot = (A: number[], r: number): number[] => { - return [ - A[0] * Math.cos(r) - A[1] * Math.sin(r), - A[0] * Math.sin(r) + A[1] * Math.cos(r), - ] - } - - /** - * Rotate a vector around another vector by r (radians) - * @param A vector - * @param C center - * @param r rotation in radians - */ - static rotWith = (A: number[], C: number[], r: number): number[] => { - if (r === 0) return A - - const s = Math.sin(r) - const c = Math.cos(r) - - const px = A[0] - C[0] - const py = A[1] - C[1] - - const nx = px * c - py * s - const ny = px * s + py * c - - return [nx + C[0], ny + C[1]] - } - - /** - * Check of two vectors are identical. - * @param A - * @param B - */ - static isEqual = (A: number[], B: number[]): boolean => { - return A[0] === B[0] && A[1] === B[1] - } - - /** - * Interpolate vector A to B with a scalar t - * @param A - * @param B - * @param t scalar - */ - static lrp = (A: number[], B: number[], t: number): number[] => { - return Vec.add(A, Vec.mul(Vec.vec(A, B), t)) - } - - /** - * Interpolate from A to B when curVAL goes fromVAL: number[] => to - * @param A - * @param B - * @param from Starting value - * @param to Ending value - * @param s Strength - */ - static int = ( - A: number[], - B: number[], - from: number, - to: number, - s = 1 - ): number[] => { - const t = (Vec.clamp(from, to) - from) / (to - from) - return Vec.add(Vec.mul(A, 1 - t), Vec.mul(B, s)) - } - - /** - * Get the angle between the three vectors A, B, and C. - * @param p1 - * @param pc - * @param p2 - */ - static ang3 = (p1: number[], pc: number[], p2: number[]): number => { - // this, - const v1 = Vec.vec(pc, p1) - const v2 = Vec.vec(pc, p2) - return Vec.ang(v1, v2) - } - - /** - * Absolute value of a vector. - * @param A - * @returns - */ - static abs = (A: number[]): number[] => { - return [Math.abs(A[0]), Math.abs(A[1])] - } - - static rescale = (a: number[], n: number): number[] => { - const l = Vec.len(a) - return [(n * a[0]) / l, (n * a[1]) / l] - } - - /** - * Get whether p1 is left of p2, relative to pc. - * @param p1 - * @param pc - * @param p2 - */ - static isLeft = (p1: number[], pc: number[], p2: number[]): number => { - // isLeft: >0 for counterclockwise - // =0 for none (degenerate) - // <0 for clockwise - return (pc[0] - p1[0]) * (p2[1] - p1[1]) - (p2[0] - p1[0]) * (pc[1] - p1[1]) - } - - static clockwise = (p1: number[], pc: number[], p2: number[]): boolean => { - return Vec.isLeft(p1, pc, p2) > 0 - } - - static round = (a: number[], d = 5): number[] => { - return a.map((v) => +v.toPrecision(d)) - } - - /** - * Get the minimum distance from a point P to a line with a segment AB. - * @param A The start of the line. - * @param B The end of the line. - * @param P A point. - * @returns - */ - // static distanceToLine(A: number[], B: number[], P: number[]) { - // const delta = sub(B, A) - // const angle = Math.atan2(delta[1], delta[0]) - // const dir = rot(sub(P, A), -angle) - // return dir[1] - // } - - /** - * Get the nearest point on a line segment AB. - * @param A The start of the line. - * @param B The end of the line. - * @param P A point. - * @param clamp Whether to clamp the resulting point to the segment. - * @returns - */ - // static nearestPointOnLine( - // A: number[], - // B: number[], - // P: number[], - // clamp = true - // ) { - // const delta = sub(B, A) - // const length = len(delta) - // const angle = Math.atan2(delta[1], delta[0]) - // const dir = rot(sub(P, A), -angle) - - // if (clamp) { - // if (dir[0] < 0) return A - // if (dir[0] > length) return B - // } - - // return add(A, div(mul(delta, dir[0]), length)) - // } - - /** - * Get the nearest point on a line with a known unit vector that passes through point A - * @param A Any point on the line - * @param u The unit vector for the line. - * @param P A point not on the line to test. - * @returns - */ - static nearestPointOnLineThroughPoint = ( - A: number[], - u: number[], - P: number[] - ): number[] => { - return Vec.add(A, Vec.mul(u, Vec.pry(Vec.sub(P, A), u))) - } - - /** - * Distance between a point and a line with a known unit vector that passes through a point. - * @param A Any point on the line - * @param u The unit vector for the line. - * @param P A point not on the line to test. - * @returns - */ - static distanceToLineThroughPoint = ( - A: number[], - u: number[], - P: number[] - ): number => { - return Vec.dist(P, Vec.nearestPointOnLineThroughPoint(A, u, P)) - } - - /** - * Get the nearest point on a line segment between A and B - * @param A The start of the line segment - * @param B The end of the line segment - * @param P The off-line point - * @param clamp Whether to clamp the point between A and B. - * @returns - */ - static nearestPointOnLineSegment = ( - A: number[], - B: number[], - P: number[], - clamp = true - ): number[] => { - const delta = Vec.sub(B, A) - const length = Vec.len(delta) - const u = Vec.div(delta, length) - - const pt = Vec.add(A, Vec.mul(u, Vec.pry(Vec.sub(P, A), u))) - - if (clamp) { - const da = Vec.dist(A, pt) - const db = Vec.dist(B, pt) - - if (db < da && da > length) return B - if (da < db && db > length) return A - } - - return pt - } - - /** - * Distance between a point and the nearest point on a line segment between A and B - * @param A The start of the line segment - * @param B The end of the line segment - * @param P The off-line point - * @param clamp Whether to clamp the point between A and B. - * @returns - */ - static distanceToLineSegment = ( - A: number[], - B: number[], - P: number[], - clamp = true - ): number => { - return Vec.dist(P, Vec.nearestPointOnLineSegment(A, B, P, clamp)) - } - - /** - * Push a point A towards point B by a given distance. - * @param A - * @param B - * @param d - * @returns - */ - static nudge = (A: number[], B: number[], d: number): number[] => { - return Vec.add(A, Vec.mul(Vec.uni(Vec.vec(A, B)), d)) - } - - /** - * Push a point in a given angle by a given distance. - * @param A - * @param B - * @param d - */ - static nudgeAtAngle = (A: number[], a: number, d: number): number[] => { - return [Math.cos(a) * d + A[0], Math.sin(a) * d + A[1]] - } - - /** - * Round a vector to a precision length. - * @param a - * @param n - */ - static toPrecision = (a: number[], n = 4): number[] => { - return [+a[0].toPrecision(n), +a[1].toPrecision(n)] - } - - /** - * Get a number of points between two points. - * @param a - * @param b - * @param steps - */ - static pointsBetween = (a: number[], b: number[], steps = 6): number[][] => { - return Array.from(Array(steps)) - .map((_, i) => { - const t = i / steps - return t * t * t - }) - .map((t) => Vec.round([...Vec.lrp(a, b, t), (1 - t) / 2])) - } -} - - - - - class Utils { - /** - * Linear interpolation betwen two numbers. - * @param y1 - * @param y2 - * @param mu - */ - static lerp(y1: number, y2: number, mu: number): number { - mu = Utils.clamp(mu, 0, 1) - return y1 * (1 - mu) + y2 * mu - } - - /** - * Modulate a value between two ranges. - * @param value - * @param rangeA from [low, high] - * @param rangeB to [low, high] - * @param clamp - */ - static modulate( - value: number, - rangeA: number[], - rangeB: number[], - clamp = false - ): number { - const [fromLow, fromHigh] = rangeA - const [v0, v1] = rangeB - const result = v0 + ((value - fromLow) / (fromHigh - fromLow)) * (v1 - v0) - - return clamp - ? v0 < v1 - ? Math.max(Math.min(result, v1), v0) - : Math.max(Math.min(result, v0), v1) - : result - } - - /** - * Clamp a value into a range. - * @param n - * @param min - */ - static clamp(n: number, min: number): number - static clamp(n: number, min: number, max: number): number - static clamp(n: number, min: number, max?: number): number { - return Math.max(min, typeof max !== 'undefined' ? Math.min(n, max) : n) - } - - // TODO: replace with a string compression algorithm - static compress(s: string): string { - return s - } - - // TODO: replace with a string decompression algorithm - static decompress(s: string): string { - return s - } - - /** - * Recursively clone an object or array. - * @param obj - */ - static deepClone(obj: T): T { - if (obj === null) return null - - const clone: any = { ...obj } - - Object.keys(obj).forEach( - (key) => - (clone[key] = - typeof obj[key] === 'object' ? Utils.deepClone(obj[key]) : obj[key]) - ) - - if (Array.isArray(obj)) { - clone.length = obj.length - return Array.from(clone) as any as T - } - - return clone as T - } - - /** - * Seeded random number generator, using [xorshift](https://en.wikipedia.org/wiki/Xorshift). - * The result will always be betweeen -1 and 1. - * - * Adapted from [seedrandom](https://github.com/davidbau/seedrandom). - */ - static rng(seed = ''): () => number { - let x = 0 - let y = 0 - let z = 0 - let w = 0 - - function next() { - const t = x ^ (x << 11) - ;(x = y), (y = z), (z = w) - w ^= ((w >>> 19) ^ t ^ (t >>> 8)) >>> 0 - return w / 0x100000000 - } - - for (let k = 0; k < seed.length + 64; k++) { - ;(x ^= seed.charCodeAt(k) | 0), next() - } - - return next - } - - /** - * Shuffle the contents of an array. - * @param arr - * @param offset - */ - static shuffleArr(arr: T[], offset: number): T[] { - return arr.map((_, i) => arr[(i + offset) % arr.length]) - } - - /** - * Deep compare two arrays. - * @param a - * @param b - */ - static deepCompareArrays(a: T[], b: T[]): boolean { - if (a?.length !== b?.length) return false - return Utils.deepCompare(a, b) - } - - /** - * Deep compare any values. - * @param a - * @param b - */ - static deepCompare(a: T, b: T): boolean { - return a === b || JSON.stringify(a) === JSON.stringify(b) - } - - /** - * Find whether two arrays intersect. - * @param a - * @param b - * @param fn An optional function to apply to the items of a; will check if b includes the result. - */ - static arrsIntersect(a: T[], b: K[], fn?: (item: K) => T): boolean - static arrsIntersect(a: T[], b: T[]): boolean - static arrsIntersect( - a: T[], - b: unknown[], - fn?: (item: unknown) => T - ): boolean { - return a.some((item) => b.includes(fn ? fn(item) : item)) - } - - /** - * Get the unique values from an array of strings or numbers. - * @param items - */ - static uniqueArray(...items: T[]): T[] { - return Array.from(new Set(items).values()) - } - - /** - * Convert a set to an array. - * @param set - */ - static setToArray(set: Set): T[] { - return Array.from(set.values()) - } - - /** - * Get the outer of between a circle and a point. - * @param C The circle's center. - * @param r The circle's radius. - * @param P The point. - * @param side - */ - static getCircleTangentToPoint( - C: number[], - r: number, - P: number[], - side: number - ): number[] { - const B = Vec.lrp(C, P, 0.5), - r1 = Vec.dist(C, B), - delta = Vec.sub(B, C), - d = Vec.len(delta) - - if (!(d <= r + r1 && d >= Math.abs(r - r1))) { - return - } - - const a = (r * r - r1 * r1 + d * d) / (2.0 * d), - n = 1 / d, - p = Vec.add(C, Vec.mul(delta, a * n)), - h = Math.sqrt(r * r - a * a), - k = Vec.mul(Vec.per(delta), h * n) - - return side === 0 ? Vec.add(p, k) : Vec.sub(p, k) - } - - /** - * Get outer tangents of two circles. - * @param x0 - * @param y0 - * @param r0 - * @param x1 - * @param y1 - * @param r1 - * @returns [lx0, ly0, lx1, ly1, rx0, ry0, rx1, ry1] - */ - static getOuterTangentsOfCircles( - C0: number[], - r0: number, - C1: number[], - r1: number - ): number[][] { - const a0 = Vec.angle(C0, C1) - const d = Vec.dist(C0, C1) - - // Circles are overlapping, no tangents - if (d < Math.abs(r1 - r0)) return - - const a1 = Math.acos((r0 - r1) / d), - t0 = a0 + a1, - t1 = a0 - a1 - - return [ - [C0[0] + r0 * Math.cos(t1), C0[1] + r0 * Math.sin(t1)], - [C1[0] + r1 * Math.cos(t1), C1[1] + r1 * Math.sin(t1)], - [C0[0] + r0 * Math.cos(t0), C0[1] + r0 * Math.sin(t0)], - [C1[0] + r1 * Math.cos(t0), C1[1] + r1 * Math.sin(t0)], - ] - } - - /** - * Get the closest point on the perimeter of a circle to a given point. - * @param C The circle's center. - * @param r The circle's radius. - * @param P The point. - */ - static getClosestPointOnCircle( - C: number[], - r: number, - P: number[] - ): number[] { - const v = Vec.sub(C, P) - return Vec.sub(C, Vec.mul(Vec.div(v, Vec.len(v)), r)) - } - - static det( - a: number, - b: number, - c: number, - d: number, - e: number, - f: number, - g: number, - h: number, - i: number - ): number { - return a * e * i + b * f * g + c * d * h - a * f * h - b * d * i - c * e * g - } - - /** - * Get a circle from three points. - * @param A - * @param B - * @param C - * @returns [x, y, r] - */ - static circleFromThreePoints( - A: number[], - B: number[], - C: number[] - ): number[] { - const a = Utils.det(A[0], A[1], 1, B[0], B[1], 1, C[0], C[1], 1) - - const bx = -Utils.det( - A[0] * A[0] + A[1] * A[1], - A[1], - 1, - B[0] * B[0] + B[1] * B[1], - B[1], - 1, - C[0] * C[0] + C[1] * C[1], - C[1], - 1 - ) - const by = Utils.det( - A[0] * A[0] + A[1] * A[1], - A[0], - 1, - B[0] * B[0] + B[1] * B[1], - B[0], - 1, - C[0] * C[0] + C[1] * C[1], - C[0], - 1 - ) - const c = -Utils.det( - A[0] * A[0] + A[1] * A[1], - A[0], - A[1], - B[0] * B[0] + B[1] * B[1], - B[0], - B[1], - C[0] * C[0] + C[1] * C[1], - C[0], - C[1] - ) - - const x = -bx / (2 * a) - const y = -by / (2 * a) - const r = Math.sqrt(bx * bx + by * by - 4 * a * c) / (2 * Math.abs(a)) - - return [x, y, r] - } - - /** - * Find the approximate perimeter of an ellipse. - * @param rx - * @param ry - */ - static perimeterOfEllipse(rx: number, ry: number): number { - const h = Math.pow(rx - ry, 2) / Math.pow(rx + ry, 2) - const p = Math.PI * (rx + ry) * (1 + (3 * h) / (10 + Math.sqrt(4 - 3 * h))) - return p - } - - /** - * Get the short angle distance between two angles. - * @param a0 - * @param a1 - */ - static shortAngleDist(a0: number, a1: number): number { - const max = Math.PI * 2 - const da = (a1 - a0) % max - return ((2 * da) % max) - da - } - - /** - * Get the long angle distance between two angles. - * @param a0 - * @param a1 - */ - static longAngleDist(a0: number, a1: number): number { - return Math.PI * 2 - Utils.shortAngleDist(a0, a1) - } - - /** - * Interpolate an angle between two angles. - * @param a0 - * @param a1 - * @param t - */ - static lerpAngles(a0: number, a1: number, t: number): number { - return a0 + Utils.shortAngleDist(a0, a1) * t - } - - /** - * Get the short distance between two angles. - * @param a0 - * @param a1 - */ - static angleDelta(a0: number, a1: number): number { - return Utils.shortAngleDist(a0, a1) - } - - /** - * Get the "sweep" or short distance between two points on a circle's perimeter. - * @param C - * @param A - * @param B - */ - static getSweep(C: number[], A: number[], B: number[]): number { - return Utils.angleDelta(Vec.angle(C, A), Vec.angle(C, B)) - } - - /** - * Rotate a point around a center. - * @param x The x-axis coordinate of the point. - * @param y The y-axis coordinate of the point. - * @param cx The x-axis coordinate of the point to rotate round. - * @param cy The y-axis coordinate of the point to rotate round. - * @param angle The distance (in radians) to rotate. - */ - static rotatePoint(A: number[], B: number[], angle: number): number[] { - const s = Math.sin(angle) - const c = Math.cos(angle) - - const px = A[0] - B[0] - const py = A[1] - B[1] - - const nx = px * c - py * s - const ny = px * s + py * c - - return [nx + B[0], ny + B[1]] - } - - /** - * Clamp radians within 0 and 2PI - * @param r - */ - static clampRadians(r: number): number { - return (Math.PI * 2 + r) % (Math.PI * 2) - } - - /** - * Clamp rotation to even segments. - * @param r - * @param segments - */ - static clampToRotationToSegments(r: number, segments: number): number { - const seg = (Math.PI * 2) / segments - return Math.floor((Utils.clampRadians(r) + seg / 2) / seg) * seg - } - - /** - * Is angle c between angles a and b? - * @param a - * @param b - * @param c - */ - static isAngleBetween(a: number, b: number, c: number): boolean { - if (c === a || c === b) return true - const PI2 = Math.PI * 2 - const AB = (b - a + PI2) % PI2 - const AC = (c - a + PI2) % PI2 - return AB <= Math.PI !== AC > AB - } - - /** - * Convert degrees to radians. - * @param d - */ - static degreesToRadians(d: number): number { - return (d * Math.PI) / 180 - } - - /** - * Convert radians to degrees. - * @param r - */ - static radiansToDegrees(r: number): number { - return (r * 180) / Math.PI - } - - /** - * Get the length of an arc between two points on a circle's perimeter. - * @param C - * @param r - * @param A - * @param B - */ - static getArcLength( - C: number[], - r: number, - A: number[], - B: number[] - ): number { - const sweep = Utils.getSweep(C, A, B) - return r * (2 * Math.PI) * (sweep / (2 * Math.PI)) - } - - /** - * Get a dash offset for an arc, based on its length. - * @param C - * @param r - * @param A - * @param B - * @param step - */ - static getArcDashOffset( - C: number[], - r: number, - A: number[], - B: number[], - step: number - ): number { - const del0 = Utils.getSweep(C, A, B) - const len0 = Utils.getArcLength(C, r, A, B) - const off0 = del0 < 0 ? len0 : 2 * Math.PI * C[2] - len0 - return -off0 / 2 + step - } - - /** - * Get a dash offset for an ellipse, based on its length. - * @param A - * @param step - */ - static getEllipseDashOffset(A: number[], step: number): number { - const c = 2 * Math.PI * A[2] - return -c / 2 + -step - } - - /** - * Get an array of points between two points. - * @param a - * @param b - * @param options - */ - static getPointsBetween( - a: number[], - b: number[], - options = {} as { - steps?: number - ease?: (t: number) => number - } - ): number[][] { - const { steps = 6, ease = (t) => t * t * t } = options - - return Array.from(Array(steps)) - .map((_, i) => ease(i / steps)) - .map((t) => [...Vec.lrp(a, b, t), (1 - t) / 2]) - } - - static getRayRayIntersection( - p0: number[], - n0: number[], - p1: number[], - n1: number[] - ): number[] { - const p0e = Vec.add(p0, n0), - p1e = Vec.add(p1, n1), - m0 = (p0e[1] - p0[1]) / (p0e[0] - p0[0]), - m1 = (p1e[1] - p1[1]) / (p1e[0] - p1[0]), - b0 = p0[1] - m0 * p0[0], - b1 = p1[1] - m1 * p1[0], - x = (b1 - b0) / (m0 - m1), - y = m0 * x + b0 - - return [x, y] - } - - static bez1d(a: number, b: number, c: number, d: number, t: number): number { - return ( - a * (1 - t) * (1 - t) * (1 - t) + - 3 * b * t * (1 - t) * (1 - t) + - 3 * c * t * t * (1 - t) + - d * t * t * t - ) - } - - static getCubicBezierBounds( - p0: number[], - c0: number[], - c1: number[], - p1: number[] - ): Bounds { - // solve for x - let a = 3 * p1[0] - 9 * c1[0] + 9 * c0[0] - 3 * p0[0] - let b = 6 * p0[0] - 12 * c0[0] + 6 * c1[0] - let c = 3 * c0[0] - 3 * p0[0] - let disc = b * b - 4 * a * c - let xl = p0[0] - let xh = p0[0] - - if (p1[0] < xl) xl = p1[0] - if (p1[0] > xh) xh = p1[0] - - if (disc >= 0) { - const t1 = (-b + Math.sqrt(disc)) / (2 * a) - if (t1 > 0 && t1 < 1) { - const x1 = Utils.bez1d(p0[0], c0[0], c1[0], p1[0], t1) - if (x1 < xl) xl = x1 - if (x1 > xh) xh = x1 - } - const t2 = (-b - Math.sqrt(disc)) / (2 * a) - if (t2 > 0 && t2 < 1) { - const x2 = Utils.bez1d(p0[0], c0[0], c1[0], p1[0], t2) - if (x2 < xl) xl = x2 - if (x2 > xh) xh = x2 - } - } - - // Solve for y - a = 3 * p1[1] - 9 * c1[1] + 9 * c0[1] - 3 * p0[1] - b = 6 * p0[1] - 12 * c0[1] + 6 * c1[1] - c = 3 * c0[1] - 3 * p0[1] - disc = b * b - 4 * a * c - let yl = p0[1] - let yh = p0[1] - if (p1[1] < yl) yl = p1[1] - if (p1[1] > yh) yh = p1[1] - if (disc >= 0) { - const t1 = (-b + Math.sqrt(disc)) / (2 * a) - if (t1 > 0 && t1 < 1) { - const y1 = Utils.bez1d(p0[1], c0[1], c1[1], p1[1], t1) - if (y1 < yl) yl = y1 - if (y1 > yh) yh = y1 - } - const t2 = (-b - Math.sqrt(disc)) / (2 * a) - if (t2 > 0 && t2 < 1) { - const y2 = Utils.bez1d(p0[1], c0[1], c1[1], p1[1], t2) - if (y2 < yl) yl = y2 - if (y2 > yh) yh = y2 - } - } - - return { - minX: xl, - minY: yl, - maxX: xh, - maxY: yh, - width: Math.abs(xl - xh), - height: Math.abs(yl - yh), - } - } - - static getExpandedBounds(a: Bounds, b: Bounds): Bounds { - const minX = Math.min(a.minX, b.minX), - minY = Math.min(a.minY, b.minY), - maxX = Math.max(a.maxX, b.maxX), - maxY = Math.max(a.maxY, b.maxY), - width = Math.abs(maxX - minX), - height = Math.abs(maxY - minY) - - return { minX, minY, maxX, maxY, width, height } - } - - static getCommonBounds(...b: Bounds[]): Bounds { - if (b.length < 2) return b[0] - - let bounds = b[0] - - for (let i = 1; i < b.length; i++) { - bounds = Utils.getExpandedBounds(bounds, b[i]) - } - - return bounds - } - - /** - * Get a bezier curve data for a spline that fits an array of points. - * @param pts - * @param tension - * @param isClosed - * @param numOfSegments - */ - static getCurvePoints( - pts: number[][], - tension = 0.5, - isClosed = false, - numOfSegments = 3 - ): number[][] { - const _pts = [...pts], - len = pts.length, - res: number[][] = [] // results - - let t1x: number, // tension vectors - t2x: number, - t1y: number, - t2y: number, - c1: number, // cardinal points - c2: number, - c3: number, - c4: number, - st: number, - st2: number, - st3: number - - // The algorithm require a previous and next point to the actual point array. - // Check if we will draw closed or open curve. - // If closed, copy end points to beginning and first points to end - // If open, duplicate first points to befinning, end points to end - if (isClosed) { - _pts.unshift(_pts[len - 1]) - _pts.push(_pts[0]) - } else { - //copy 1. point and insert at beginning - _pts.unshift(_pts[0]) - _pts.push(_pts[len - 1]) - // _pts.push(_pts[len - 1]) - } - - // For each point, calculate a segment - for (let i = 1; i < _pts.length - 2; i++) { - // Calculate points along segment and add to results - for (let t = 0; t <= numOfSegments; t++) { - // Step - st = t / numOfSegments - st2 = Math.pow(st, 2) - st3 = Math.pow(st, 3) - - // Cardinals - c1 = 2 * st3 - 3 * st2 + 1 - c2 = -(2 * st3) + 3 * st2 - c3 = st3 - 2 * st2 + st - c4 = st3 - st2 - - // Tension - t1x = (_pts[i + 1][0] - _pts[i - 1][0]) * tension - t2x = (_pts[i + 2][0] - _pts[i][0]) * tension - t1y = (_pts[i + 1][1] - _pts[i - 1][1]) * tension - t2y = (_pts[i + 2][1] - _pts[i][1]) * tension - - // Control points - res.push([ - c1 * _pts[i][0] + c2 * _pts[i + 1][0] + c3 * t1x + c4 * t2x, - c1 * _pts[i][1] + c2 * _pts[i + 1][1] + c3 * t1y + c4 * t2y, - ]) - } - } - - res.push(pts[pts.length - 1]) - - return res - } - - /** - * Simplify a line (using Ramer-Douglas-Peucker algorithm). - * @param points An array of points as [x, y, ...][] - * @param tolerance The minimum line distance (also called epsilon). - * @returns Simplified array as [x, y, ...][] - */ - static simplify(points: number[][], tolerance = 1): number[][] { - const len = points.length, - a = points[0], - b = points[len - 1], - [x1, y1] = a, - [x2, y2] = b - - if (len > 2) { - let distance = 0 - let index = 0 - const max = Math.hypot(y2 - y1, x2 - x1) - - for (let i = 1; i < len - 1; i++) { - const [x0, y0] = points[i], - d = - Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) / max - - if (distance > d) continue - - distance = d - index = i - } - - if (distance > tolerance) { - const l0 = Utils.simplify(points.slice(0, index + 1), tolerance) - const l1 = Utils.simplify(points.slice(index + 1), tolerance) - return l0.concat(l1.slice(1)) - } - } - - return [a, b] - } -} - - - - - class CodeShape { - private _shape: Mutable - protected utils: ShapeUtility - - constructor(props: T) { - this._shape = createShape(props.type, props) as Mutable - this.utils = getShapeUtils(this._shape) - codeShapes.add(this) - } - - /** - * Destroy the shape. - * - * \`\`\`ts - * shape.destroy() - * \`\`\` - */ - destroy = (): void => { - codeShapes.delete(this) - } - - /** - * Move the shape to a point. - * - * \`\`\`ts - * shape.moveTo(100,100) - * \`\`\` - */ - moveTo = (point: number[]): CodeShape => { - return this.translateTo(point) - } - - /** - * Move the shape to a point. - * - * \`\`\`ts - * shape.translateTo([100,100]) - * \`\`\` - */ - translateTo = (point: number[]): CodeShape => { - this.utils.translateTo(this._shape, point) - return this - } - - /** - * Move the shape by a delta. - * - * \`\`\`ts - * shape.translateBy([100,100]) - * \`\`\` - */ - translateBy = (delta: number[]): CodeShape => { - this.utils.translateTo(this._shape, delta) - return this - } - - /** - * Rotate the shape. - * - * \`\`\`ts - * shape.rotateTo(Math.PI / 2) - * \`\`\` - */ - rotateTo = (rotation: number): CodeShape => { - this.utils.rotateTo(this._shape, rotation, this.shape.rotation - rotation) - return this - } - - /** - * Rotate the shape by a delta. - * - * \`\`\`ts - * shape.rotateBy(Math.PI / 2) - * \`\`\` - */ - rotateBy = (rotation: number): CodeShape => { - this.utils.rotateBy(this._shape, rotation) - return this - } - - /** - * Get the shape's bounding box. - * - * \`\`\`ts - * const bounds = shape.getBounds() - * \`\`\` - */ - getBounds = (): CodeShape => { - this.utils.getBounds(this.shape) - return this - } - - /** - * Test whether a point is inside of the shape. - * - * \`\`\`ts - * const isHit = shape.hitTest() - * \`\`\` - */ - hitTest = (point: number[]): CodeShape => { - this.utils.hitTest(this.shape, point) - return this - } - - /** - * Duplicate this shape. - * - * \`\`\`ts - * const shapeB = shape.duplicate() - * \`\`\` - */ - duplicate = (): CodeShape => { - const duplicate = Object.assign( - Object.create(Object.getPrototypeOf(this)), - this - ) - - duplicate._shape = createShape(this._shape.type, { - ...this._shape, - id: uniqueId(), - } as any) - - codeShapes.add(duplicate) - return duplicate - } - - /** - * Move the shape to the back of the painting order. - * - * \`\`\`ts - * shape.moveToBack() - * \`\`\` - */ - moveToBack = (): CodeShape => { - const sorted = getOrderedShapes() - - if (sorted.length <= 1) return - - const first = sorted[0].childIndex - sorted.forEach((shape) => shape.childIndex++) - this.childIndex = first - - codeShapes.clear() - sorted.forEach((shape) => codeShapes.add(shape)) - - return this - } - - /** - * Move the shape to the top of the painting order. - * - * \`\`\`ts - * shape.moveToFront() - * \`\`\` - */ - moveToFront = (): CodeShape => { - const sorted = getOrderedShapes() - - if (sorted.length <= 1) return - - const ahead = sorted.slice(sorted.indexOf(this)) - const last = ahead[ahead.length - 1].childIndex - ahead.forEach((shape) => shape.childIndex--) - this.childIndex = last - - codeShapes.clear() - sorted.forEach((shape) => codeShapes.add(shape)) - - return this - } - - /** - * Move the shape backward in the painting order. - * - * \`\`\`ts - * shape.moveBackward() - * \`\`\` - */ - moveBackward = (): CodeShape => { - const sorted = getOrderedShapes() - - if (sorted.length <= 1) return - - const next = sorted[sorted.indexOf(this) - 1] - - if (!next) return - - const index = next.childIndex - next.childIndex = this.childIndex - this.childIndex = index - - codeShapes.clear() - sorted.forEach((shape) => codeShapes.add(shape)) - - return this - } - - /** - * Move the shape forward in the painting order. - * - * \`\`\`ts - * shape.moveForward() - * \`\`\` - */ - moveForward = (): CodeShape => { - const sorted = getOrderedShapes() - - if (sorted.length <= 1) return - - const next = sorted[sorted.indexOf(this) + 1] - - if (!next) return - - const index = next.childIndex - next.childIndex = this.childIndex - this.childIndex = index - - codeShapes.clear() - sorted.forEach((shape) => codeShapes.add(shape)) - - return this - } - - get id(): string { - return this._shape.id - } - - /** - * The shape's underlying shape (readonly). - * - * \`\`\`ts - * const underlyingShape = shape.shape - * \`\`\` - */ - get shape(): Readonly { - return this._shape - } - - /** - * The shape's current point. - * - * \`\`\`ts - * const shapePoint = shape.point() - * \`\`\` - */ - get point(): number[] { - return [...this.shape.point] - } - - set point(point: number[]) { - this.utils.translateTo(this._shape, point) - } - - /** - * The shape's current x position. - * - * \`\`\`ts - * const shapeX = shape.x - * - * shape.x = 100 - * \`\`\` - */ - get x(): number { - return this.point[0] - } - - set x(x: number) { - this.utils.translateTo(this._shape, [x, this.y]) - } - - /** - * The shape's current y position. - * - * \`\`\`ts - * const shapeY = shape.y - * - * shape.y = 100 - * \`\`\` - */ - get y(): number { - return this.point[1] - } - - set y(y: number) { - this.utils.translateTo(this._shape, [this.x, y]) - } - - /** - * The shape's rotation. - * - * \`\`\`ts - * const shapeRotation = shape.rotation - * - * shape.rotation = Math.PI / 2 - * \`\`\` - */ - get rotation(): number { - return this.shape.rotation - } - - set rotation(rotation: number) { - this.utils.rotateTo(this._shape, rotation, rotation - this.shape.rotation) - } - - /** - * The shape's color style (ColorStyle). - * - * \`\`\`ts - * const shapeColor = shape.color - * - * shape.color = ColorStyle.Red - * \`\`\` - */ - get color(): ColorStyle { - return this.shape.style.color - } - - set color(color: ColorStyle) { - this.utils.applyStyles(this._shape, { color }) - } - - /** - * The shape's dash style (DashStyle). - * - * \`\`\`ts - * const shapeDash = shape.dash - * - * shape.dash = DashStyle.Dotted - * \`\`\` - */ - get dash(): DashStyle { - return this.shape.style.dash - } - - set dash(dash: DashStyle) { - this.utils.applyStyles(this._shape, { dash }) - } - - /** - * The shape's size (SizeStyle). - * - * \`\`\`ts - * const shapeSize = shape.size - * - * shape.size = SizeStyle.Large - * \`\`\` - */ - get size(): SizeStyle { - return this.shape.style.size - } - - set size(size: SizeStyle) { - this.utils.applyStyles(this._shape, { size }) - } - - /** - * The shape's index in the painting order. - * - * \`\`\`ts - * const shapeChildIndex = shape.childIndex - * - * shape.childIndex = 10 - * \`\`\` - */ - get childIndex(): number { - return this.shape.childIndex - } - - set childIndex(childIndex: number) { - this.utils.setProperty(this._shape, 'childIndex', childIndex) - } - - /** - * The shape's center. - * - * \`\`\`ts - * const shapeCenter = shape.center - * - * shape.center = [100, 100] - * \`\`\` - */ - get center(): number[] { - return this.utils.getCenter(this.shape) - } - - set center(center: number[]) { - const oldCenter = this.utils.getCenter(this.shape) - const delta = Vec.sub(center, oldCenter) - this.translateBy(delta) - } -} - - - - - class Dot extends CodeShape { - constructor(props = {} as ShapeProps) { - super({ - id: uniqueId(), - parentId: (window as any).currentPageId, - type: ShapeType.Dot, - isGenerated: true, - name: 'Dot', - childIndex: 0, - point: [0, 0], - rotation: 0, - ...props, - style: { - ...defaultStyle, - ...props.style, - isFilled: true, - }, - }) - } -} - - - - - class Ellipse extends CodeShape { - constructor(props = {} as ShapeProps) { - super({ - id: uniqueId(), - parentId: (window as any).currentPageId, - type: ShapeType.Ellipse, - isGenerated: true, - name: 'Ellipse', - childIndex: 0, - point: [0, 0], - radiusX: 50, - radiusY: 50, - rotation: 0, - ...props, - style: { ...defaultStyle, ...props.style }, - }) - } - - /** - * The ellipse's x radius. - * - * \`\`\`ts - * const shapeRadiusX = shape.radiusX - * - * shape.radiusX = 100 - * \`\`\` - */ - get radiusX(): number { - return this.shape.radiusX - } - - set radiusX(radiusX: number) { - this.utils.setProperty(this.shape, 'radiusX', radiusX) - } - - /** - * The ellipse's y radius. - * - * \`\`\`ts - * const shapeRadiusY = shape.radiusY - * - * shape.radiusY = 100 - * \`\`\` - */ - get radiusY(): number { - return this.shape.radiusY - } - - set radiusY(radiusY: number) { - this.utils.setProperty(this.shape, 'radiusY', radiusY) - } -} - - - - - class Line extends CodeShape { - constructor(props = {} as ShapeProps) { - super({ - id: uniqueId(), - parentId: (window as any).currentPageId, - type: ShapeType.Line, - isGenerated: true, - name: 'Line', - childIndex: 0, - point: [0, 0], - direction: [-0.5, 0.5], - rotation: 0, - ...props, - style: { - ...defaultStyle, - ...props.style, - isFilled: false, - }, - }) - } - - /** - * The line's direction. - * - * \`\`\`ts - * const shapeDirection = shape.direction - * - * shape.direction = [0,0] - * \`\`\` - */ - get direction(): number[] { - return this.shape.direction - } - set direction(direction: number[]) { - this.utils.setProperty(this.shape, 'direction', direction) - } -} - - - - - class Polyline extends CodeShape { - constructor(props = {} as ShapeProps) { - super({ - id: uniqueId(), - parentId: (window as any).currentPageId, - type: ShapeType.Polyline, - isGenerated: true, - name: 'Polyline', - childIndex: 0, - point: [0, 0], - points: [[0, 0]], - rotation: 0, - ...props, - style: { - ...defaultStyle, - ...props.style, - }, - }) - } - - /** - * Add a point to the polyline's points. - * - * \`\`\`ts - * shape.addPoint([100,100]) - * \`\`\` - */ - addPoint(point: number[]): CodeShape { - this.utils.setProperty(this.shape, 'points', [...this.points, point]) - return this - } - - /** - * The polyline's points. - * - * \`\`\`ts - * const shapePoints = shape.points - * - * shape.points = [[0,0], [100,100], [100,200]] - * \`\`\` - */ - get points(): number[][] { - return this.shape.points - } - - set points(points: number[][]) { - this.utils.setProperty(this.shape, 'points', points) - } -} - - - - - class Ray extends CodeShape { - constructor(props = {} as ShapeProps) { - super({ - id: uniqueId(), - type: ShapeType.Ray, - isGenerated: true, - name: 'Ray', - parentId: 'page1', - childIndex: 0, - point: [0, 0], - direction: [0, 1], - rotation: 0, - ...props, - style: { - ...defaultStyle, - ...props.style, - isFilled: false, - }, - }) - } - - /** - * The ray's direction. - * - * \`\`\`ts - * const shapeDirection = shape.direction - * - * shape.direction = [0,0] - * \`\`\` - */ - get direction(): number[] { - return this.shape.direction - } - set direction(direction: number[]) { - this.utils.setProperty(this.shape, 'direction', direction) - } -} - - - - - class Arrow extends CodeShape { - constructor( - props = {} as ShapeProps & { start: number[]; end: number[] } - ) { - const { start = [0, 0], end = [100, 100] } = props - - const { - point = [0, 0], - handles = { - start: { - id: 'start', - index: 0, - point: start, - }, - end: { - id: 'end', - index: 1, - point: end, - }, - bend: { - id: 'bend', - index: 2, - point: Vec.med(start, end), - }, - }, - } = props - - super({ - id: uniqueId(), - type: ShapeType.Arrow, - name: 'Arrow', - parentId: 'page1', - childIndex: 0, - point, - rotation: 0, - bend: 0, - handles, - decorations: { - start: null, - middle: null, - end: Decoration.Arrow, - }, - ...props, - style: { - ...defaultStyle, - ...props.style, - isFilled: false, - }, - }) - } - - /** - * The arrow's start point. - * - * \`\`\`ts - * const startPoint = shape.start - * - * shape.start = [100, 100] - * \`\`\` - */ - get start(): number[] { - return this.shape.handles.start.point - } - - set start(point: number[]) { - getShapeUtils(this.shape).onHandleChange(this.shape, { - start: { ...this.shape.handles.start, point }, - }) - } - - /** - * The arrow's middle point. - * - * \`\`\`ts - * const middlePoint = shape.middle - * - * shape.middle = [100, 100] - * \`\`\` - */ - get middle(): number[] { - return this.shape.handles.bend.point - } - - set middle(point: number[]) { - getShapeUtils(this.shape).onHandleChange(this.shape, { - bend: { ...this.shape.handles.bend, point }, - }) - } - - /** - * The arrow's end point. - * - * \`\`\`ts - * const endPoint = shape.end - * - * shape.end = [100, 100] - * \`\`\` - */ - get end(): number[] { - return this.shape.handles.end.point - } - - set end(point: number[]) { - getShapeUtils(this.shape).onHandleChange(this.shape, { - end: { ...this.shape.handles.end, point }, - }) - } - - get bend(): number { - return this.shape.bend - } -} - - - - - class Draw extends CodeShape { - constructor(props = {} as ShapeProps) { - super({ - id: uniqueId(), - type: ShapeType.Draw, - parentId: (window as any).currentPageId, - name: 'Draw', - childIndex: 0, - point: [0, 0], - points: [], - rotation: 0, - ...props, - style: { - ...defaultStyle, - ...props.style, - }, - }) - } - - /** - * Add a point to the draw shape's points. - * - * \`\`\`ts - * shape.addPoint([100,100]) - * \`\`\` - */ - addPoint(point: number[]): CodeShape { - this.utils.setProperty(this.shape, 'points', [...this.points, point]) - return this - } - - /** - * The draw shape's points. - * - * \`\`\`ts - * const shapePoints = shape.points - * - * shape.points = [[0,0], [100,100], [100,200]] - * \`\`\` - */ - get points(): number[][] { - return this.shape.points - } - - set points(points: number[][]) { - this.utils.setProperty(this.shape, 'points', points) - } -} - - - - - class Text extends CodeShape { - constructor(props = {} as ShapeProps) { - super({ - id: uniqueId(), - parentId: (window as any).currentPageId, - type: ShapeType.Text, - isGenerated: true, - name: 'Text', - childIndex: 0, - point: [0, 0], - rotation: 0, - text: 'Text', - scale: 1, - ...props, - style: { - ...defaultStyle, - ...props.style, - }, - }) - } - - /** - * The text shape's text content. - * - * \`\`\`ts - * const shapeText = shape.text - * - * shape.text = "Hello world!" - * \`\`\` - */ - get text(): string { - return this.shape.text - } - - set text(text: string) { - getShapeUtils(this.shape).setProperty(this.shape, 'text', text) - } - - /** - * The text's scale. - * - * \`\`\`ts - * const shapeScale = shape.scale - * - * shape.scale = 2 - * \`\`\` - */ - get scale(): number { - return this.shape.scale - } - - set scale(scale: number) { - getShapeUtils(this.shape).setProperty(this.shape, 'scale', scale) - } -} - - - - - class Rectangle extends CodeShape { - constructor(props = {} as ShapeProps) { - super({ - id: uniqueId(), - parentId: (window as any).currentPageId, - type: ShapeType.Rectangle, - isGenerated: true, - name: 'Rectangle', - childIndex: 0, - point: [0, 0], - size: [100, 100], - rotation: 0, - radius: 2, - ...props, - style: { - ...defaultStyle, - ...props.style, - }, - }) - } - - /** - * The rectangle's width. - * - * \`\`\`ts - * const shapeWidth = shape.width - * - * shape.width = 100 - * \`\`\` - */ - get width(): number { - return this.shape.size[0] - } - - set width(width: number) { - getShapeUtils(this.shape).setProperty(this.shape, 'size', [ - width, - this.height, - ]) - } - - /** - * The rectangle's height. - * - * \`\`\`ts - * const shapeHeight = shape.height - * - * shape.height = 100 - * \`\`\` - */ - get height(): number { - return this.shape.size[1] - } - - set height(height: number) { - getShapeUtils(this.shape).setProperty(this.shape, 'size', [ - this.width, - height, - ]) - } -} - - - - -class Control { - _control: T - - constructor(control: T) { - this._control = { ...control } - codeControls.add(this._control) - - // Could there be a better way to prevent this? - // When updating, constructor should just bind to - // the existing control rather than creating a new one? - if (!(window as any).isUpdatingCode) { - controls[this._control.label] = this._control.value - } - } - - destroy(): void { - codeControls.delete(this.control) - delete controls[this.control.label] - } - - get control(): T { - return this._control - } - - get id(): string { - return this.control.id - } - - get value(): T['value'] { - return this.control.value - } -} - -type ControlProps = Omit, 'type'> - -class NumberControl extends Control { - constructor(options: ControlProps) { - const { id = uniqueId(), label = 'Number', value = 0, step = 1 } = options - - super({ - type: ControlType.Number, - ...options, - label, - value, - step, - id, - }) - } -} - -class VectorControl extends Control { - constructor(options: ControlProps) { - const { - id = uniqueId(), - label = 'Vector', - value = [0, 0], - isNormalized = false, - } = options - - super({ - type: ControlType.Vector, - ...options, - label, - value, - isNormalized, - id, - }) - } -} - -class TextControl extends Control { - constructor(options: ControlProps) { - const { id = uniqueId(), label = 'Text', value = 'text' } = options - - super({ - type: ControlType.Text, - ...options, - label, - value, - id, - }) - } -} - - -const codeShapes = new Set>() -const controls: Record = {} -const defaultStyle: ShapeStyles = { - color: ColorStyle.Black, - size: SizeStyle.Medium, - isFilled: false, - dash: DashStyle.Solid, -} -const uniqueId = () => '' -const codeControls = new Set([]) - -declare function createShape(type: ShapeType, shape: Shape): any -declare function getShapeUtils(shape: T): any -declare function getOrderedShapes(): CodeShape[] - -`, -} diff --git a/components/controls-panel/control.tsx b/components/controls-panel/control.tsx deleted file mode 100644 index b13296c87..000000000 --- a/components/controls-panel/control.tsx +++ /dev/null @@ -1,165 +0,0 @@ -import state, { useSelector } from 'state' -import styled from 'styles' -import { - ControlType, - NumberCodeControl, - TextCodeControl, - VectorCodeControl, -} from 'types' - -export default function Control({ id }: { id: string }): JSX.Element { - const control = useSelector((s) => s.data.codeControls[id]) - - if (!control) return null - - return ( - <> - - {(() => { - switch (control.type) { - case ControlType.Number: - return - case ControlType.Vector: - return - case ControlType.Text: - return - } - })()} - - ) -} - -function NumberControl({ id, min, max, step, value }: NumberCodeControl) { - return ( - - - state.send('CHANGED_CODE_CONTROL', { - [id]: Number(e.currentTarget.value), - }) - } - /> - - state.send('CHANGED_CODE_CONTROL', { - [id]: Number(e.currentTarget.value), - }) - } - /> - - ) -} - -function VectorControl({ - id, - value, - min = -Infinity, - max = Infinity, - step = 0.01, - isNormalized = false, -}: VectorCodeControl) { - return ( - - - state.send('CHANGED_CODE_CONTROL', { - [id]: [Number(e.currentTarget.value), value[1]], - }) - } - /> - - state.send('CHANGED_CODE_CONTROL', { - [id]: [Number(e.currentTarget.value), value[1]], - }) - } - /> - - state.send('CHANGED_CODE_CONTROL', { - [id]: [value[0], Number(e.currentTarget.value)], - }) - } - /> - - state.send('CHANGED_CODE_CONTROL', { - [id]: [value[0], Number(e.currentTarget.value)], - }) - } - /> - - ) -} - -function TextControl({ id, value }: TextCodeControl) { - return ( - - - state.send('CHANGED_CODE_CONTROL', { - [id]: e.currentTarget.value, - }) - } - /> - - ) -} - -const Inputs = styled('div', { - display: 'flex', - gap: '8px', - height: '100%', - - '& input': { - font: '$ui', - width: '64px', - fontSize: '$1', - border: '1px solid $inputBorder', - backgroundColor: '$input', - color: '$text', - height: '100%', - padding: '0px 6px', - }, - "& input[type='range']": { - padding: 0, - flexGrow: 2, - }, - "& input[type='text']": { - minWidth: 200, - padding: 4, - flexGrow: 2, - }, -}) diff --git a/components/controls-panel/controls-panel.tsx b/components/controls-panel/controls-panel.tsx deleted file mode 100644 index 7d57656b6..000000000 --- a/components/controls-panel/controls-panel.tsx +++ /dev/null @@ -1,76 +0,0 @@ -/* eslint-disable @typescript-eslint/ban-ts-comment */ -import styled from 'styles' -import React, { useRef } from 'react' -import state, { useSelector } from 'state' -import { X } from 'react-feather' -import { breakpoints, IconButton } from 'components/shared' -import * as Panel from '../panel' -import Control from './control' -import { deepCompareArrays } from 'utils' - -function handleClose() { - state.send('CLOSED_CONTROLS') -} - -const stopKeyboardPropagation = (e: KeyboardEvent | React.KeyboardEvent) => - e.stopPropagation() - -export default function ControlPanel(): JSX.Element { - const rContainer = useRef(null) - const isOpen = useSelector((s) => Object.keys(s.data.codeControls).length > 0) - - const codeControls = useSelector( - (state) => Object.keys(state.data.codeControls), - deepCompareArrays - ) - - if (codeControls.length === 0) { - return null - } - - return ( - - - - - - -

Controls

- - - {codeControls.map((id) => ( - - ))} - - - - ) -} - -const ControlsList = styled(Panel.Content, { - padding: 12, - display: 'grid', - gridTemplateColumns: '1fr 4fr', - gridAutoRows: '24px', - alignItems: 'center', - gridColumnGap: '8px', - gridRowGap: '8px', - - '& input': { - font: '$ui', - fontSize: '$1', - border: '1px solid $inputBorder', - backgroundColor: '$input', - color: '$text', - height: '100%', - padding: '0px 6px', - }, -}) diff --git a/components/debug-panel/debug-panel.tsx b/components/debug-panel/debug-panel.tsx deleted file mode 100644 index 35e5f0617..000000000 --- a/components/debug-panel/debug-panel.tsx +++ /dev/null @@ -1,224 +0,0 @@ -/* eslint-disable @typescript-eslint/ban-ts-comment */ -import styled from 'styles' -import React, { useRef } from 'react' -import state, { useSelector } from 'state' -import * as Panel from 'components/panel' -import { - breakpoints, - IconButton, - RowButton, - IconWrapper, -} from 'components/shared' -import { - Cross2Icon, - PlayIcon, - DotIcon, - CrumpledPaperIcon, - StopIcon, - ClipboardIcon, - ClipboardCopyIcon, - TrashIcon, -} from '@radix-ui/react-icons' -import logger from 'state/logger' -import { useStateDesigner } from '@state-designer/react' - -const stopPropagation = (e: React.KeyboardEvent) => e.stopPropagation() -const toggleDebugPanel = () => state.send('TOGGLED_DEBUG_PANEL') -const handleStateCopy = () => state.send('COPIED_STATE_TO_CLIPBOARD') -const handleError = () => { - throw Error('Error!') -} - -export default function CodePanel(): JSX.Element { - const rContainer = useRef(null) - const isDebugging = useSelector((s) => s.data.settings.isDebugMode) - const isOpen = useSelector((s) => s.data.settings.isDebugOpen) - - const rTextArea = useRef(null) - - const local = useStateDesigner({ - initial: 'stopped', - data: { - log: '', - }, - states: { - stopped: { - on: { - CHANGED_LOG: 'setLog', - COPIED_LOG: { if: 'hasLog', do: 'copyLog' }, - PLAYED_BACK_LOG: { if: 'hasLog', do: 'playbackLog' }, - STARTED_LOGGING: { do: 'startLogger', to: 'logging' }, - }, - }, - logging: { - on: { - STOPPED_LOGGING: { do: 'stopLogger', to: 'stopped' }, - }, - }, - }, - conditions: { - hasLog(data) { - return data.log !== '' - }, - }, - actions: { - setLog(data, payload: { value: string }) { - data.log = payload.value - }, - startLogger(data) { - logger.start(state.data) - data.log = '' - }, - stopLogger(data) { - logger.stop(state.data) - data.log = logger.copyToJson() - }, - playbackLog(data) { - logger.playback(state.data, data.log) - }, - copyLog() { - logger.copyToJson() - }, - }, - }) - - if (!isDebugging) return null - - const handleLoggingStop = () => local.send('STOPPED_LOGGING') - - const handlePlayback = () => - local.send('PLAYED_BACK_LOG', { log: rTextArea.current?.value }) - - const handleLoggingStart = () => local.send('STARTED_LOGGING') - - const handleLoggingCopy = () => local.send('COPIED_DEBUG_LOG') - - return ( - e.stopPropagation()} - > - {isOpen ? ( - - - - - - Debugging -
- - -
- - Copy State - - - - - - Create Error - - - - -
- {local.isIn('stopped') ? ( - - Start Logger - - - - - ) : ( - - Stop Logger - - - - - )} - - - - - - local.send('CHANGED_LOG', { value: e.currentTarget.value }) - } - /> - - - Play Back Log - - - - -
- - ) : ( - - - - )} - - ) -} - -const StylePanelRoot = styled(Panel.Root, { - width: 'fit-content', - maxWidth: 'fit-content', - overflow: 'hidden', - position: 'relative', - border: '1px solid $panel', - boxShadow: '$4', - display: 'flex', - flexDirection: 'column', - alignItems: 'center', - pointerEvents: 'all', - padding: '$0', - - '& hr': { - marginTop: 2, - marginBottom: 2, - marginLeft: '-$0', - border: 'none', - height: 1, - backgroundColor: '$brushFill', - width: 'calc(100% + 4px)', - }, -}) - -const JSONTextAreaWrapper = styled('div', { - position: 'relative', - margin: '4px 0', -}) - -const JSONTextArea = styled('textarea', { - minHeight: '100px', - width: '100%', - font: '$mono', - backgroundColor: '$panel', - border: '1px solid $border', - borderRadius: '4px', - padding: '4px', - outline: 'none', -}) diff --git a/components/editor.tsx b/components/editor.tsx deleted file mode 100644 index aab9587b5..000000000 --- a/components/editor.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import useKeyboardEvents from 'hooks/useKeyboardEvents' -import useLoadOnMount from 'hooks/useLoadOnMount' -import useStateTheme from 'hooks/useStateTheme' -import Menu from './menu/menu' -import Canvas from './canvas/canvas' -import ToolsPanel from './tools-panel/tools-panel' -import StylePanel from './style-panel/style-panel' -import styled from 'styles' -import PagePanel from './page-panel/page-panel' -import CodePanel from './code-panel/code-panel' -import DebugPanel from './debug-panel/debug-panel' -import ControlsPanel from './controls-panel/controls-panel' - -export default function Editor({ roomId }: { roomId?: string }): JSX.Element { - useLoadOnMount(roomId) - useStateTheme() - useKeyboardEvents() - - return ( - - - - - - - - - - - - - - ) -} - -const Spacer = styled('div', { - flexGrow: 2, -}) - -const MenuButtons = styled('div', { - display: 'flex', - gap: 8, -}) - -const Layout = styled('main', { - position: 'fixed', - overflow: 'hidden', - top: 0, - left: 0, - bottom: 0, - right: 0, - height: '100%', - width: '100%', - padding: '8px 8px 0 8px', - zIndex: 200, - display: 'flex', - alignItems: 'flex-start', - justifyContent: 'flex-start', - boxSizing: 'border-box', - outline: 'none', - - pointerEvents: 'none', - '& > *': { - PointerEvent: 'all', - }, -}) diff --git a/components/page-panel/page-options.tsx b/components/page-panel/page-options.tsx deleted file mode 100644 index fda1afd64..000000000 --- a/components/page-panel/page-options.tsx +++ /dev/null @@ -1,135 +0,0 @@ -import * as Dialog from '@radix-ui/react-alert-dialog' -import { MixerVerticalIcon } from '@radix-ui/react-icons' -import { - breakpoints, - IconButton, - DialogOverlay, - DialogContent, - RowButton, - MenuTextInput, - DialogInputWrapper, - Divider, -} from 'components/shared' -import { useEffect, useRef, useState } from 'react' -import state, { useSelector } from 'state' -import { Page } from 'types' - -export default function PageOptions({ page }: { page: Page }): JSX.Element { - const [isOpen, setIsOpen] = useState(false) - - const rInput = useRef(null) - - const hasOnlyOnePage = useSelector( - (s) => Object.keys(s.data.document.pages).length <= 1 - ) - - const [name, setName] = useState(page.name) - - function handleNameChange(e: React.ChangeEvent) { - setName(e.currentTarget.value) - } - - function handleDuplicate() { - state.send('DUPLICATED_PAGE', { id: page.id }) - } - - function handleDelete() { - state.send('DELETED_PAGE', { id: page.id }) - } - - function handleOpenChange(isOpen: boolean) { - setIsOpen(isOpen) - - if (isOpen) { - return - } - - if (page.name.length === 0) { - state.send('RENAMED_PAGE', { - id: page.id, - name: 'Page', - }) - } - - state.send('SAVED_PAGE_RENAME', { id: page.id }) - } - - function handleSave() { - state.send('RENAMED_PAGE', { - id: page.id, - name, - }) - } - - function stopPropagation(e: React.KeyboardEvent) { - e.stopPropagation() - } - - function handleKeydown(e: React.KeyboardEvent) { - if (e.key === 'Enter') { - handleSave() - setIsOpen(false) - } - } - - useEffect(() => { - if (isOpen) { - setTimeout(() => { - rInput.current?.focus() - rInput.current?.select() - }, 0) - } - }, [isOpen]) - - return ( - - - - - - - - - - - - Duplicate - - - Delete - - - - Save - - - Cancel - - - - ) -} diff --git a/components/page-panel/page-panel.tsx b/components/page-panel/page-panel.tsx deleted file mode 100644 index 2a42534ff..000000000 --- a/components/page-panel/page-panel.tsx +++ /dev/null @@ -1,106 +0,0 @@ -import * as DropdownMenu from '@radix-ui/react-dropdown-menu' -import styled from 'styles' -import { - breakpoints, - DropdownMenuButton, - DropdownMenuDivider, - RowButton, - MenuContent, - FloatingContainer, - IconWrapper, -} from 'components/shared' -import PageOptions from './page-options' -import { PlusIcon, CheckIcon } from '@radix-ui/react-icons' -import state, { useSelector } from 'state' -import { useEffect, useRef, useState } from 'react' - -function handleCreatePage() { - state.send('CREATED_PAGE') -} - -export default function PagePanel(): JSX.Element { - const rIsOpen = useRef(false) - const [isOpen, setIsOpen] = useState(false) - - useEffect(() => { - if (rIsOpen.current !== isOpen) { - rIsOpen.current = isOpen - } - }, [isOpen]) - - const documentPages = useSelector((s) => s.data.document.pages) - const currentPageId = useSelector((s) => s.data.currentPageId) - - if (!documentPages[currentPageId]) return null - - const sorted = Object.values(documentPages).sort( - (a, b) => a.childIndex - b.childIndex - ) - - return ( - { - if (rIsOpen.current !== isOpen) { - setIsOpen(isOpen) - } - }} - > - - - {documentPages[currentPageId].name} - - - - { - setIsOpen(false) - state.send('CHANGED_PAGE', { id }) - }} - > - {sorted.map((page) => ( - - - {page.name} - - - - - - - - - ))} - - - - Create Page - - - - - - - ) -} - -const ButtonWithOptions = styled('div', { - display: 'grid', - gridTemplateColumns: '1fr auto', - gridAutoFlow: 'column', - - '& > *[data-shy="true"]': { - opacity: 0, - }, - - '&:hover > *[data-shy="true"]': { - opacity: 1, - }, -}) diff --git a/components/panel.tsx b/components/panel.tsx deleted file mode 100644 index 6a28546d1..000000000 --- a/components/panel.tsx +++ /dev/null @@ -1,136 +0,0 @@ -import styled from 'styles' - -export const Root = styled('div', { - position: 'relative', - backgroundColor: '$panel', - borderRadius: '4px', - overflow: 'hidden', - pointerEvents: 'all', - userSelect: 'none', - zIndex: 200, - border: '1px solid $panel', - boxShadow: '$4', - font: '$ui', - - variants: { - bp: { - mobile: {}, - small: {}, - }, - variant: { - code: {}, - controls: { - position: 'absolute', - right: 156, - }, - }, - isOpen: { - true: {}, - false: { - padding: '$0', - height: 38, - width: 38, - }, - }, - }, - compoundVariants: [ - { - isOpen: true, - variant: 'code', - css: { - position: 'absolute', - top: 8, - left: 8, - right: 8, - bottom: 48, - maxWidth: 680, - zIndex: 1000, - }, - }, - { - isOpen: true, - variant: 'code', - bp: 'small', - css: { - position: 'absolute', - top: 8, - left: 8, - right: 8, - bottom: 128, - maxWidth: 720, - zIndex: 1000, - }, - }, - ], -}) - -export const Layout = styled('div', { - display: 'grid', - gridTemplateColumns: '1fr', - gridTemplateRows: 'auto 1fr', - gridAutoRows: '28px', - height: '100%', - width: 'auto', - minWidth: '100%', - maxWidth: 560, - overflow: 'hidden', - userSelect: 'none', - pointerEvents: 'all', -}) - -export const Header = styled('div', { - pointerEvents: 'all', - display: 'flex', - width: '100%', - alignItems: 'center', - justifyContent: 'space-between', - padding: '$0', - position: 'relative', - - '& h3': { - position: 'absolute', - top: 0, - left: 0, - width: '100%', - height: '100%', - textAlign: 'center', - padding: 0, - margin: 0, - display: 'flex', - justifyContent: 'center', - alignItems: 'center', - fontSize: '13px', - pointerEvents: 'none', - userSelect: 'none', - }, - - variants: { - side: { - left: { - flexDirection: 'row', - }, - right: { - flexDirection: 'row-reverse', - }, - }, - }, -}) - -export const ButtonsGroup = styled('div', { - display: 'flex', -}) - -export const Content = styled('div', { - position: 'relative', - pointerEvents: 'all', - overflowY: 'scroll', -}) - -export const Footer = styled('div', { - overflowX: 'scroll', - color: '$text', - font: '$debug', - padding: '0 12px', - display: 'flex', - alignItems: 'center', -}) diff --git a/components/shared.tsx b/components/shared.tsx deleted file mode 100644 index d310028c1..000000000 --- a/components/shared.tsx +++ /dev/null @@ -1,727 +0,0 @@ -import React from 'react' -import Tooltip from 'components/tooltip' -import * as ContextMenu from '@radix-ui/react-context-menu' -import * as DropdownMenu from '@radix-ui/react-dropdown-menu' -import * as RadioGroup from '@radix-ui/react-radio-group' -import * as Panel from './panel' -import styled from 'styles' -import { CheckIcon, ChevronRightIcon } from '@radix-ui/react-icons' -import { isMobile } from 'utils' - -export const breakpoints: any = { '@initial': 'mobile', '@sm': 'small' } - -export const IconButton = styled('button', { - position: 'relative', - height: '32px', - width: '32px', - backgroundColor: '$panel', - borderRadius: '4px', - padding: '0', - margin: '0', - display: 'grid', - alignItems: 'center', - justifyContent: 'center', - outline: 'none', - border: 'none', - pointerEvents: 'all', - fontSize: '$0', - color: '$text', - cursor: 'pointer', - - '& > *': { - gridRow: 1, - gridColumn: 1, - }, - - '&:disabled': { - opacity: '0.5', - }, - - '& > span': { - width: '100%', - height: '100%', - display: 'flex', - alignItems: 'center', - }, - - variants: { - bp: { - mobile: { - backgroundColor: 'transparent', - }, - small: { - '&:hover:not(:disabled)': { - backgroundColor: '$hover', - }, - }, - }, - size: { - small: { - height: 32, - width: 32, - '& svg:nth-of-type(1)': { - height: '16px', - width: '16px', - }, - }, - medium: { - height: 44, - width: 44, - '& svg:nth-of-type(1)': { - height: '18px', - width: '18px', - }, - }, - large: { - height: 44, - width: 44, - '& svg:nth-of-type(1)': { - height: '20px', - width: '20px', - }, - }, - }, - isActive: { - true: { - color: '$selected', - }, - }, - }, -}) - -export const RowButton = styled('button', { - position: 'relative', - display: 'flex', - width: '100%', - background: 'none', - height: '32px', - border: 'none', - cursor: 'pointer', - color: '$text', - outline: 'none', - alignItems: 'center', - fontFamily: '$ui', - fontWeight: 400, - fontSize: '$1', - justifyContent: 'space-between', - padding: '4px 8px 4px 12px', - borderRadius: 4, - userSelect: 'none', - - '& label': { - fontWeight: '$1', - margin: 0, - padding: 0, - }, - - '& svg': { - position: 'relative', - stroke: '$overlay', - strokeWidth: 1, - zIndex: 1, - }, - - '&[data-disabled]': { - opacity: 0.3, - }, - - '&:disabled': { - opacity: 0.3, - }, - - variants: { - bp: { - mobile: {}, - small: { - '& *[data-shy="true"]': { - opacity: 0, - }, - '&:hover:not(:disabled)': { - backgroundColor: '$hover', - '& *[data-shy="true"]': { - opacity: 1, - }, - }, - }, - }, - size: { - icon: { - padding: '4px ', - width: 'auto', - }, - }, - variant: { - noIcon: { - padding: '4px 12px', - }, - pageButton: { - display: 'grid', - gridTemplateColumns: '24px auto', - width: '100%', - paddingLeft: '$1', - gap: '$3', - justifyContent: 'flex-start', - [`& > *[data-state="checked"]`]: { - gridRow: 1, - gridColumn: 1, - }, - '& > span': { - gridRow: 1, - gridColumn: 2, - width: '100%', - }, - }, - }, - warn: { - true: { - color: '$warn', - }, - }, - isActive: { - true: { - backgroundColor: '$hover', - }, - }, - }, -}) - -export const StylePanelRoot = styled(Panel.Root, { - minWidth: 1, - width: 184, - maxWidth: 184, - overflow: 'hidden', - position: 'relative', - border: '1px solid $panel', - boxShadow: '$4', - - variants: { - isOpen: { - true: {}, - false: { - padding: '$0', - height: 38, - width: 38, - }, - }, - }, -}) - -export const Group = styled(RadioGroup.Root, { - display: 'flex', -}) - -export const ShortcutKey = styled('span', { - fontSize: '$0', - width: '16px', - height: '16px', - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - boxShadow: '1px 1px 0px rgba(0,0,0,.5)', -}) - -export const IconWrapper = styled('div', { - height: '100%', - borderRadius: '4px', - marginRight: '1px', - display: 'grid', - alignItems: 'center', - justifyContent: 'center', - outline: 'none', - border: 'none', - pointerEvents: 'all', - cursor: 'pointer', - color: '$text', - - '& svg': { - height: 22, - width: 22, - strokeWidth: 1, - }, - - '& > *': { - gridRow: 1, - gridColumn: 1, - }, - - variants: { - size: { - small: { - '& svg': { - height: '16px', - width: '16px', - }, - }, - medium: { - '& svg': { - height: '22px', - width: '22px', - }, - }, - }, - }, -}) - -export const ButtonsRow = styled('div', { - position: 'relative', - display: 'flex', - width: '100%', - background: 'none', - border: 'none', - cursor: 'pointer', - outline: 'none', - alignItems: 'center', - justifyContent: 'flex-start', - padding: 0, -}) - -export const VerticalDivider = styled('hr', { - width: '1px', - margin: '-2px 3px', - border: 'none', - backgroundColor: '$brushFill', -}) - -export const FloatingContainer = styled('div', { - backgroundColor: '$panel', - border: '1px solid $panel', - borderRadius: '4px', - boxShadow: '$4', - display: 'flex', - height: 'fit-content', - padding: '$0', - pointerEvents: 'all', - position: 'relative', - userSelect: 'none', - zIndex: 200, - - variants: { - direction: { - row: { - flexDirection: 'row', - }, - column: { - flexDirection: 'column', - }, - }, - elevation: { - 0: { - boxShadow: 'none', - }, - 2: { - boxShadow: '$2', - }, - 3: { - boxShadow: '$3', - }, - 4: { - boxShadow: '$4', - }, - }, - }, -}) - -export const StyledKbd = styled('kbd', { - marginLeft: '32px', - fontSize: '$1', - fontFamily: '$ui', - fontWeight: 400, - - '& > span': { - display: 'inline-block', - width: '12px', - }, -}) - -export function Kbd({ children }: { children: React.ReactNode }): JSX.Element { - if (isMobile()) return null - return {children} -} - -/* -------------------------------------------------- */ -/* Dialog */ -/* -------------------------------------------------- */ - -export const DialogContent = styled('div', { - position: 'fixed', - top: '50%', - left: '50%', - transform: 'translate(-50%, -50%)', - minWidth: 240, - maxWidth: 'fit-content', - maxHeight: '85vh', - marginTop: '-5vh', - pointerEvents: 'all', - backgroundColor: '$panel', - border: '1px solid $panel', - padding: '$0', - boxShadow: '$4', - borderRadius: '4px', - font: '$ui', - - '&:focus': { - outline: 'none', - }, -}) - -export const DialogOverlay = styled('div', { - backgroundColor: 'rgba(0, 0, 0, .15)', - position: 'fixed', - top: 0, - right: 0, - bottom: 0, - left: 0, -}) - -export const DialogInputWrapper = styled('div', { - padding: '$4 $2', -}) - -export const DialogTitleRow = styled('div', { - display: 'flex', - padding: '0 0 0 $4', - alignItems: 'center', - justifyContent: 'space-between', - - h3: { - fontSize: '$1', - }, -}) - -/* -------------------------------------------------- */ -/* Menus */ -/* -------------------------------------------------- */ - -export const MenuContent = styled('div', { - position: 'relative', - overflow: 'hidden', - userSelect: 'none', - zIndex: 180, - minWidth: 180, - pointerEvents: 'all', - backgroundColor: '$panel', - border: '1px solid $panel', - padding: '$0', - boxShadow: '$4', - borderRadius: '4px', - font: '$ui', -}) - -export const Divider = styled('div', { - backgroundColor: '$hover', - height: 1, - marginTop: '$2', - marginRight: '-$2', - marginBottom: '$2', - marginLeft: '-$2', -}) - -export function MenuButton({ - warn, - onSelect, - children, - disabled = false, -}: { - warn?: boolean - onSelect?: () => void - disabled?: boolean - children: React.ReactNode -}): JSX.Element { - return ( - - {children} - - ) -} - -export const MenuTextInput = styled('input', { - backgroundColor: '$panel', - border: 'none', - padding: '$4 $3', - width: '100%', - outline: 'none', - background: '$input', - borderRadius: '4px', - font: '$ui', - fontSize: '$1', -}) - -/* -------------------------------------------------- */ -/* Dropdown Menu */ -/* -------------------------------------------------- */ - -export function DropdownMenuRoot({ - isOpen, - onOpenChange, - children, -}: { - isOpen?: boolean - onOpenChange?: (isOpen: boolean) => void - children: React.ReactNode -}): JSX.Element { - return ( - - {children} - - ) -} - -export function DropdownMenuSubMenu({ - children, - disabled = false, - label, -}: { - label: string - disabled?: boolean - children: React.ReactNode -}): JSX.Element { - return ( - - - {label} - - - - - - {children} - - - - ) -} - -export const DropdownMenuDivider = styled(DropdownMenu.Separator, { - backgroundColor: '$hover', - height: 1, - marginTop: '$2', - marginRight: '-$2', - marginBottom: '$2', - marginLeft: '-$2', -}) - -export const DropdownMenuArrow = styled(DropdownMenu.Arrow, { - fill: '$panel', -}) - -export function DropdownMenuButton({ - onSelect, - children, - disabled = false, -}: { - onSelect?: () => void - disabled?: boolean - children: React.ReactNode -}): JSX.Element { - return ( - - {children} - - ) -} - -interface DropdownMenuIconButtonProps { - onSelect: () => void - disabled?: boolean - children: React.ReactNode -} - -export function DropdownMenuIconButton({ - onSelect, - children, - disabled = false, -}: DropdownMenuIconButtonProps): JSX.Element { - return ( - - {children} - - ) -} - -interface DropdownMenuIconTriggerButtonProps { - label: string - kbd?: string - disabled?: boolean - children: React.ReactNode -} -export function DropdownMenuIconTriggerButton({ - label, - kbd, - children, - disabled = false, -}: DropdownMenuIconTriggerButtonProps): JSX.Element { - return ( - - - {children} - - - ) -} - -interface MenuCheckboxItemProps { - checked: boolean - disabled?: boolean - onCheckedChange: (isChecked: boolean) => void - children: React.ReactNode -} - -export function DropdownMenuCheckboxItem({ - checked, - disabled = false, - onCheckedChange, - children, -}: MenuCheckboxItemProps): JSX.Element { - return ( - - {children} - - - - - - - ) -} - -/* -------------------------------------------------- */ -/* Context Menu */ -/* -------------------------------------------------- */ - -export function ContextMenuRoot({ - onOpenChange, - children, -}: { - onOpenChange?: (isOpen: boolean) => void - children: React.ReactNode -}): JSX.Element { - return ( - - {children} - - ) -} - -export function ContextMenuSubMenu({ - children, - label, -}: { - label: string - children: React.ReactNode -}): JSX.Element { - return ( - - - {label} - - - - - - {children} - - - - ) -} - -export const ContextMenuDivider = styled(ContextMenu.Separator, { - backgroundColor: '$hover', - height: 1, - margin: '$2 -$2', -}) - -export const ContextMenuArrow = styled(ContextMenu.Arrow, { - fill: '$panel', -}) - -export function ContextMenuButton({ - onSelect, - children, - disabled = false, -}: { - onSelect?: () => void - disabled?: boolean - children: React.ReactNode -}): JSX.Element { - return ( - - {children} - - ) -} - -export function ContextMenuIconButton({ - onSelect, - children, - disabled = false, -}: { - onSelect: () => void - disabled?: boolean - children: React.ReactNode -}): JSX.Element { - return ( - - {children} - - ) -} - -export function ContextMenuCheckboxItem({ - checked, - disabled = false, - onCheckedChange, - children, -}: MenuCheckboxItemProps): JSX.Element { - return ( - - {children} - - - - - - - ) -} diff --git a/components/status-bar.tsx b/components/status-bar.tsx deleted file mode 100644 index 913e03dac..000000000 --- a/components/status-bar.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import { useStateDesigner } from '@state-designer/react' -import state from 'state' -import styled from 'styles' - -const size: any = { '@sm': 'small' } - -export default function StatusBar(): JSX.Element { - const local = useStateDesigner(state) - - const shapesInView = state.values.shapesToRender.length - - const active = local.active - .slice(1) - .map((s) => { - const states = s.split('.') - return states[states.length - 1] - }) - .join(' | ') - - const log = local.log[0] - - if (process.env.NODE_ENV !== 'development') return null - - return ( - -
- {active} - {log} -
-
{shapesInView || '0'} Shapes
-
- ) -} - -const StatusBarContainer = styled('div', { - height: 40, - userSelect: 'none', - borderTop: '1px solid $border', - gridArea: 'status', - display: 'flex', - color: '$text', - justifyContent: 'space-between', - alignItems: 'center', - backgroundColor: '$panel', - gap: 8, - fontSize: '$0', - padding: '0 16px', - - variants: { - size: { - small: { - fontSize: '$1', - }, - }, - }, -}) - -const Section = styled('div', { - whiteSpace: 'nowrap', - overflow: 'hidden', -}) diff --git a/components/style-panel/align-distribute.tsx b/components/style-panel/align-distribute.tsx deleted file mode 100644 index c5af4acb5..000000000 --- a/components/style-panel/align-distribute.tsx +++ /dev/null @@ -1,155 +0,0 @@ -import { - AlignBottomIcon, - AlignCenterHorizontallyIcon, - AlignCenterVerticallyIcon, - AlignLeftIcon, - AlignRightIcon, - AlignTopIcon, - SpaceEvenlyHorizontallyIcon, - SpaceEvenlyVerticallyIcon, - StretchHorizontallyIcon, - StretchVerticallyIcon, -} from '@radix-ui/react-icons' -import { breakpoints, ButtonsRow, IconButton } from 'components/shared' -import { memo } from 'react' -import state from 'state' -import { AlignType, DistributeType, StretchType } from 'types' - -function alignTop() { - state.send('ALIGNED', { type: AlignType.Top }) -} - -function alignCenterVertical() { - state.send('ALIGNED', { type: AlignType.CenterVertical }) -} - -function alignBottom() { - state.send('ALIGNED', { type: AlignType.Bottom }) -} - -function stretchVertically() { - state.send('STRETCHED', { type: StretchType.Vertical }) -} - -function distributeVertically() { - state.send('DISTRIBUTED', { type: DistributeType.Vertical }) -} - -function alignLeft() { - state.send('ALIGNED', { type: AlignType.Left }) -} - -function alignCenterHorizontal() { - state.send('ALIGNED', { type: AlignType.CenterHorizontal }) -} - -function alignRight() { - state.send('ALIGNED', { type: AlignType.Right }) -} - -function stretchHorizontally() { - state.send('STRETCHED', { type: StretchType.Horizontal }) -} - -function distributeHorizontally() { - state.send('DISTRIBUTED', { type: DistributeType.Horizontal }) -} - -function AlignDistribute({ - hasTwoOrMore, - hasThreeOrMore, -}: { - hasTwoOrMore: boolean - hasThreeOrMore: boolean -}): JSX.Element { - return ( - <> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ) -} - -export default memo(AlignDistribute) diff --git a/components/style-panel/quick-fill-select.tsx b/components/style-panel/quick-fill-select.tsx deleted file mode 100644 index 1e31b9b68..000000000 --- a/components/style-panel/quick-fill-select.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import * as Checkbox from '@radix-ui/react-checkbox' -import tld from 'utils/tld' -import { breakpoints, IconButton, IconWrapper } from '../shared' -import { BoxIcon, IsFilledFillIcon } from './shared' -import state, { useSelector } from 'state' -import { getShapeUtils } from 'state/shape-utils' -import Tooltip from 'components/tooltip' - -function handleIsFilledChange(isFilled: boolean) { - state.send('CHANGED_STYLE', { isFilled }) -} - -export default function IsFilledPicker(): JSX.Element { - const isFilled = useSelector((s) => s.values.selectedStyle.isFilled) - const canFill = useSelector((s) => { - const selectedShapes = tld.getSelectedShapes(s.data) - - return ( - selectedShapes.length === 0 || - selectedShapes.some((shape) => getShapeUtils(shape).canStyleFill) - ) - }) - - return ( - - - - - - - - - - - ) -} diff --git a/components/style-panel/shapes-functions.tsx b/components/style-panel/shapes-functions.tsx deleted file mode 100644 index b498efaf8..000000000 --- a/components/style-panel/shapes-functions.tsx +++ /dev/null @@ -1,214 +0,0 @@ -import tld from 'utils/tld' -import state, { useSelector } from 'state' -import { IconButton, ButtonsRow, breakpoints } from 'components/shared' -import { memo } from 'react' -import { MoveType, ShapeType } from 'types' -import { Trash2 } from 'react-feather' -import Tooltip from 'components/tooltip' -import { - ArrowDownIcon, - ArrowUpIcon, - AspectRatioIcon, - CopyIcon, - GroupIcon, - LockClosedIcon, - LockOpen1Icon, - PinBottomIcon, - PinTopIcon, - RotateCounterClockwiseIcon, -} from '@radix-ui/react-icons' -import { commandKey } from 'utils' - -function handleRotateCcw() { - state.send('ROTATED_CCW') -} - -function handleDuplicate() { - state.send('DUPLICATED') -} - -function handleGroup() { - state.send('GROUPED') -} - -function handleUngroup() { - state.send('UNGROUPED') -} - -function handleLock() { - state.send('TOGGLED_SHAPE_LOCK') -} - -function handleAspectLock() { - state.send('TOGGLED_SHAPE_ASPECT_LOCK') -} - -function handleMoveToBack() { - state.send('MOVED', { type: MoveType.ToBack }) -} - -function handleMoveBackward() { - state.send('MOVED', { type: MoveType.Backward }) -} - -function handleMoveForward() { - state.send('MOVED', { type: MoveType.Forward }) -} - -function handleMoveToFront() { - state.send('MOVED', { type: MoveType.ToFront }) -} - -function handleDelete() { - state.send('DELETED') -} - -function ShapesFunctions() { - const isAllLocked = useSelector((s) => { - const page = tld.getPage(s.data) - return s.values.selectedIds.every((id) => page.shapes[id].isLocked) - }) - - const isAllAspectLocked = useSelector((s) => { - const page = tld.getPage(s.data) - return s.values.selectedIds.every( - (id) => page.shapes[id].isAspectRatioLocked - ) - }) - - const isAllGrouped = useSelector((s) => { - const selectedShapes = tld.getSelectedShapes(s.data) - return selectedShapes.every( - (shape) => - shape.type === ShapeType.Group || - (shape.parentId === selectedShapes[0].parentId && - selectedShapes[0].parentId !== s.data.currentPageId) - ) - }) - - const hasSelection = useSelector((s) => { - return tld.getSelectedIds(s.data).length > 0 - }) - - const hasMultipleSelection = useSelector((s) => { - return tld.getSelectedIds(s.data).length > 1 - }) - - return ( - <> - - - - - - - - - - - - - - - - {isAllLocked ? : } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ) -} - -export default memo(ShapesFunctions) diff --git a/components/style-panel/style-panel.tsx b/components/style-panel/style-panel.tsx deleted file mode 100644 index 6f96293d8..000000000 --- a/components/style-panel/style-panel.tsx +++ /dev/null @@ -1,101 +0,0 @@ -import state, { useSelector } from 'state' -import { - IconButton, - ButtonsRow, - breakpoints, - RowButton, - FloatingContainer, - Divider, - Kbd, -} from 'components/shared' -import ShapesFunctions from './shapes-functions' -import AlignDistribute from './align-distribute' -import QuickColorSelect from './quick-color-select' -import QuickSizeSelect from './quick-size-select' -import QuickDashSelect from './quick-dash-select' -import QuickFillSelect from './quick-fill-select' -import Tooltip from 'components/tooltip' -import { DotsHorizontalIcon, Cross2Icon } from '@radix-ui/react-icons' -import { commandKey, isMobile } from 'utils' - -const handleStylePanelOpen = () => state.send('TOGGLED_STYLE_PANEL_OPEN') -const handleCopy = () => state.send('COPIED') -const handlePaste = () => state.send('PASTED') -const handleCopyToSvg = () => state.send('COPIED_TO_SVG') - -export default function StylePanel(): JSX.Element { - const isOpen = useSelector((s) => s.data.settings.isStyleOpen) - - return ( - - - - - - - - - {isOpen ? : } - - - - {isOpen && } - - ) -} - -function SelectedShapeContent(): JSX.Element { - const selectedShapesCount = useSelector((s) => s.values.selectedIds.length) - - const showKbds = !isMobile() - - return ( - <> - - - - 1} - hasThreeOrMore={selectedShapesCount > 2} - /> - - - Copy - {showKbds && ( - - {commandKey()} - C - - )} - - - Paste - {showKbds && ( - - {commandKey()} - V - - )} - - - Copy to SVG - {showKbds && ( - - - {commandKey()} - C - - )} - - - ) -} diff --git a/components/tools-panel/back-to-content.tsx b/components/tools-panel/back-to-content.tsx deleted file mode 100644 index 4528f3c2d..000000000 --- a/components/tools-panel/back-to-content.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import { FloatingContainer, RowButton } from 'components/shared' -import { motion } from 'framer-motion' -import { memo } from 'react' -import state, { useSelector } from 'state' -import styled from 'styles' - -function BackToContent() { - const shouldDisplay = useSelector((s) => { - const { currentShapes, shapesToRender } = s.values - return currentShapes.length > 0 && shapesToRender.length === 0 - }) - - if (!shouldDisplay) return null - - return ( - - state.send('ZOOMED_TO_CONTENT')}> - Back to content - - - ) -} - -export default memo(BackToContent) - -const BackToContentButton = styled(motion(FloatingContainer), { - pointerEvents: 'all', - width: 'fit-content', - gridRow: 1, - flexGrow: 2, - display: 'block', -}) diff --git a/components/tools-panel/undo-redo.tsx b/components/tools-panel/undo-redo.tsx deleted file mode 100644 index d49b69f66..000000000 --- a/components/tools-panel/undo-redo.tsx +++ /dev/null @@ -1,24 +0,0 @@ -import { TertiaryButton, TertiaryButtonsContainer } from './shared' -import { Undo, Redo, Trash } from 'components/icons' -import state from 'state' -import { commandKey } from 'utils' - -const undo = () => state.send('UNDO') -const redo = () => state.send('REDO') -const clear = () => state.send('CLEARED_PAGE') - -export default function UndoRedo(): JSX.Element { - return ( - - - - - - - - - - - - ) -} diff --git a/components/tools-panel/zoom.tsx b/components/tools-panel/zoom.tsx deleted file mode 100644 index e638228f3..000000000 --- a/components/tools-panel/zoom.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import { ZoomInIcon, ZoomOutIcon } from '@radix-ui/react-icons' -import { TertiaryButton, TertiaryButtonsContainer } from './shared' -import state, { useSelector } from 'state' -import tld from 'utils/tld' -import { commandKey } from 'utils' - -const zoomIn = () => state.send('ZOOMED_IN') -const zoomOut = () => state.send('ZOOMED_OUT') -const zoomToFit = () => state.send('ZOOMED_TO_FIT') -const zoomToActual = () => state.send('ZOOMED_TO_ACTUAL') - -export default function Zoom(): JSX.Element { - return ( - - - - - - - - - - ) -} - -function ZoomCounter() { - const zoom = useSelector((s) => tld.getCurrentCamera(s.data).zoom) - - return ( - - {Math.round(zoom * 100)}% - - ) -} diff --git a/components/tooltip.tsx b/components/tooltip.tsx deleted file mode 100644 index b159cff50..000000000 --- a/components/tooltip.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import * as _Tooltip from '@radix-ui/react-tooltip' -import React from 'react' -import styled from 'styles' - -interface TooltipProps { - children: React.ReactNode - label: string - kbd?: string - side?: 'bottom' | 'left' | 'right' | 'top' -} - -export default function Tooltip({ - children, - label, - kbd, - side = 'top', -}: TooltipProps): JSX.Element { - return ( - <_Tooltip.Root> - <_Tooltip.Trigger as="span">{children} - - {label} - {kbd ? ( - - {kbd.split('').map((k, i) => ( - {k} - ))} - - ) : null} - - - - ) -} - -const StyledContent = styled(_Tooltip.Content, { - borderRadius: 3, - padding: '$3 $3 $3 $3', - fontSize: '$1', - backgroundColor: '$tooltipBg', - color: '$tooltipText', - boxShadow: '$3', - display: 'flex', - alignItems: 'center', - - '& kbd': { - marginLeft: '$3', - textShadow: '$2', - textAlign: 'center', - fontSize: '$1', - fontFamily: '$ui', - fontWeight: 400, - gap: '$1', - display: 'flex', - alignItems: 'center', - - '& > span': { - padding: '$0', - borderRadius: '$0', - background: '$overlayContrast', - boxShadow: '$key', - width: '20px', - height: '20px', - display: 'flex', - alignItems: 'center', - justifyContent: 'center', - }, - }, -}) - -const StyledArrow = styled(_Tooltip.Arrow, { - fill: '$tooltipBg', - margin: '0 8px', -}) diff --git a/decs.d.ts b/decs.d.ts deleted file mode 100644 index 7ec0b3638..000000000 --- a/decs.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -type CSSOMString = string -type FontFaceLoadStatus = 'unloaded' | 'loading' | 'loaded' | 'error' -type FontFaceSetStatus = 'loading' | 'loaded' - -interface FontFace { - family: CSSOMString - style: CSSOMString - weight: CSSOMString - stretch: CSSOMString - unicodeRange: CSSOMString - variant: CSSOMString - featureSettings: CSSOMString - variationSettings: CSSOMString - display: CSSOMString - readonly status: FontFaceLoadStatus - readonly loaded: Promise - load(): Promise -} - -interface FontFaceSet { - readonly status: FontFaceSetStatus - readonly ready: Promise - check(font: string, text?: string): boolean - load(font: string, text?: string): Promise -} - -declare global { - interface Document { - fonts: FontFaceSet - } -} diff --git a/hooks/useBoundsEvents.ts b/hooks/useBoundsEvents.ts deleted file mode 100644 index 81bd917de..000000000 --- a/hooks/useBoundsEvents.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import { useCallback } from 'react' -import { fastTransform } from 'state/hacks' -import inputs from 'state/inputs' -import { Edge, Corner } from 'types' - -import state from '../state' - -export default function useBoundsEvents(handle: Edge | Corner | 'rotate') { - const onPointerDown = useCallback( - (e) => { - if (!inputs.canAccept(e.pointerId)) return - e.stopPropagation() - e.currentTarget.setPointerCapture(e.pointerId) - - if (e.button === 0) { - const info = inputs.pointerDown(e, handle) - - if (inputs.isDoubleClick() && !(info.altKey || info.metaKey)) { - state.send('DOUBLE_POINTED_BOUNDS_HANDLE', info) - } - - state.send('POINTED_BOUNDS_HANDLE', info) - } - }, - [handle] - ) - - const onPointerMove = useCallback( - (e) => { - if (e.buttons !== 1) return - if (!inputs.canAccept(e.pointerId)) return - e.stopPropagation() - - const info = inputs.pointerMove(e) - - if (state.isIn('transformingSelection')) { - fastTransform(info) - return - } - - state.send('MOVED_POINTER', info) - }, - [handle] - ) - - const onPointerUp = useCallback((e) => { - if (e.buttons !== 1) return - if (!inputs.canAccept(e.pointerId)) return - e.stopPropagation() - e.currentTarget.releasePointerCapture(e.pointerId) - e.currentTarget.replaceWith(e.currentTarget) - state.send('STOPPED_POINTING', inputs.pointerUp(e, 'bounds')) - }, []) - - return { onPointerDown, onPointerMove, onPointerUp } -} diff --git a/hooks/useCamera.ts b/hooks/useCamera.ts deleted file mode 100644 index 6ecb9597c..000000000 --- a/hooks/useCamera.ts +++ /dev/null @@ -1,34 +0,0 @@ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import React, { useEffect } from 'react' -import state from 'state' -import storage from 'state/storage' -import tld from 'utils/tld' - -/** - * When the state's camera changes, update the transform of - * the SVG group to reflect the correct zoom and pan. - * @param ref - */ -export default function useCamera(ref: React.MutableRefObject) { - useEffect(() => { - let prev = tld.getCurrentCamera(state.data) - - return state.onUpdate(() => { - const g = ref.current - if (!g) return - - const { point, zoom } = tld.getCurrentCamera(state.data) - - if (point !== prev.point || zoom !== prev.zoom) { - g.setAttribute( - 'transform', - `scale(${zoom}) translate(${point[0]} ${point[1]})` - ) - - storage.savePageState(state.data) - - prev = tld.getCurrentCamera(state.data) - } - }) - }, [state]) -} diff --git a/hooks/useCanvasEvents.ts b/hooks/useCanvasEvents.ts deleted file mode 100644 index f8d1ad45a..000000000 --- a/hooks/useCanvasEvents.ts +++ /dev/null @@ -1,142 +0,0 @@ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import { MutableRefObject, useCallback, useEffect } from 'react' -import state from 'state' -import { - fastBrushSelect, - fastDrawUpdate, - fastPanUpdate, - fastTransform, - fastTranslate, -} from 'state/hacks' -import inputs from 'state/inputs' -import Vec from 'utils/vec' - -export default function useCanvasEvents( - rCanvas: MutableRefObject -) { - const handlePointerDown = useCallback( - (e: React.PointerEvent) => { - if (!inputs.canAccept(e.pointerId)) return - - rCanvas.current.setPointerCapture(e.pointerId) - - const info = inputs.pointerDown(e, 'canvas') - - if (e.button === 0) { - if (inputs.isDoubleClick() && !(info.altKey || info.metaKey)) { - state.send('DOUBLE_POINTED_CANVAS', info) - } - - state.send('POINTED_CANVAS', info) - } else if (e.button === 2) { - state.send('RIGHT_POINTED', info) - } - }, - [] - ) - - const handlePointerMove = useCallback( - (e: React.PointerEvent) => { - if (!inputs.canAccept(e.pointerId)) return - - const prev = inputs.pointer?.point - const info = inputs.pointerMove(e) - - if (prev && state.isIn('selecting') && inputs.keys[' ']) { - const delta = Vec.sub(prev, info.point) - fastPanUpdate(delta) - state.send('KEYBOARD_PANNED_CAMERA', { - delta: Vec.sub(prev, info.point), - }) - return - } - - if (state.isIn('draw.editing')) { - fastDrawUpdate(info) - } else if (state.isIn('brushSelecting')) { - fastBrushSelect(info.point) - } else if (state.isIn('translatingSelection')) { - fastTranslate(info) - } else if (state.isIn('transformingSelection')) { - fastTransform(info) - } - - state.send('MOVED_POINTER', info) - }, - [] - ) - - const handlePointerUp = useCallback( - (e: React.PointerEvent) => { - if (!inputs.canAccept(e.pointerId)) return - - rCanvas.current.releasePointerCapture(e.pointerId) - - state.send('STOPPED_POINTING', { - id: 'canvas', - ...inputs.pointerUp(e, 'canvas'), - }) - }, - [] - ) - - const handleTouchStart = useCallback((e: React.TouchEvent) => { - if ('safari' in window) { - e.preventDefault() - } - }, []) - - useEffect(() => { - const preventGestureNavigation = (event: TouchEvent) => { - event.preventDefault() - } - - const preventNavigation = (event: TouchEvent) => { - // Center point of the touch area - const touchXPosition = event.touches[0].pageX - // Size of the touch area - const touchXRadius = event.touches[0].radiusX || 0 - - // We set a threshold (10px) on both sizes of the screen, - // if the touch area overlaps with the screen edges - // it's likely to trigger the navigation. We prevent the - // touchstart event in that case. - if ( - touchXPosition - touchXRadius < 10 || - touchXPosition + touchXRadius > window.innerWidth - 10 - ) { - event.preventDefault() - } - } - - rCanvas.current.addEventListener('gestureend', preventGestureNavigation) - rCanvas.current.addEventListener('gesturechange', preventGestureNavigation) - rCanvas.current.addEventListener('gesturestart', preventGestureNavigation) - rCanvas.current.addEventListener('touchstart', preventNavigation) - - return () => { - if (rCanvas.current) { - rCanvas.current.removeEventListener( - 'gestureend', - preventGestureNavigation - ) - rCanvas.current.removeEventListener( - 'gesturechange', - preventGestureNavigation - ) - rCanvas.current.removeEventListener( - 'gesturestart', - preventGestureNavigation - ) - rCanvas.current.removeEventListener('touchstart', preventNavigation) - } - } - }, []) - - return { - onPointerDown: handlePointerDown, - onPointerMove: handlePointerMove, - onPointerUp: handlePointerUp, - onTouchStart: handleTouchStart, - } -} diff --git a/hooks/useGtag.ts b/hooks/useGtag.ts deleted file mode 100644 index b7e36125e..000000000 --- a/hooks/useGtag.ts +++ /dev/null @@ -1,20 +0,0 @@ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import router from 'next/router' -import { useEffect } from 'react' -import * as gtag from 'utils/gtag' - -export default function useGtag() { - useEffect(() => { - if (process.env.NODE_ENV !== 'production') return - - function handleRouteChange(url: URL) { - gtag.pageview(url) - } - - router.events.on('routeChangeComplete', handleRouteChange) - - return () => { - router.events.off('routeChangeComplete', handleRouteChange) - } - }, [router.events]) -} diff --git a/hooks/useHandleEvents.ts b/hooks/useHandleEvents.ts deleted file mode 100644 index 1b4d13385..000000000 --- a/hooks/useHandleEvents.ts +++ /dev/null @@ -1,70 +0,0 @@ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import { MutableRefObject, useCallback } from 'react' -import state from 'state' -import inputs from 'state/inputs' - -export default function useHandleEvents( - id: string, - rGroup: MutableRefObject -) { - const handlePointerDown = useCallback( - (e: React.PointerEvent) => { - if (!inputs.canAccept(e.pointerId)) return - e.stopPropagation() - rGroup.current.setPointerCapture(e.pointerId) - const info = inputs.pointerDown(e, id) - - state.send('POINTED_HANDLE', info) - }, - [id] - ) - - const handlePointerUp = useCallback( - (e: React.PointerEvent) => { - if (!inputs.canAccept(e.pointerId)) return - e.stopPropagation() - rGroup.current.releasePointerCapture(e.pointerId) - const isDoubleClick = inputs.isDoubleClick() - const info = inputs.pointerUp(e, id) - - if (isDoubleClick && !(info.altKey || info.metaKey)) { - state.send('DOUBLE_POINTED_HANDLE', info) - } else { - state.send('STOPPED_POINTING', inputs.pointerUp(e, id)) - } - }, - [id] - ) - - const handlePointerEnter = useCallback( - (e: React.PointerEvent) => { - if (!inputs.canAccept(e.pointerId)) return - state.send('HOVERED_HANDLE', inputs.pointerEnter(e, id)) - }, - [id] - ) - - const handlePointerMove = useCallback( - (e: React.PointerEvent) => { - if (!inputs.canAccept(e.pointerId)) return - state.send('MOVED_OVER_HANDLE', inputs.pointerEnter(e, id)) - }, - [id] - ) - - const handlePointerLeave = useCallback( - (e: React.PointerEvent) => { - if (!inputs.canAccept(e.pointerId)) return - state.send('UNHOVERED_HANDLE', { target: id }) - }, - [id] - ) - - return { - onPointerDown: handlePointerDown, - onPointerUp: handlePointerUp, - onPointerEnter: handlePointerEnter, - onPointerMove: handlePointerMove, - onPointerLeave: handlePointerLeave, - } -} diff --git a/hooks/useKeyboardEvents.ts b/hooks/useKeyboardEvents.ts deleted file mode 100644 index bd61ffd33..000000000 --- a/hooks/useKeyboardEvents.ts +++ /dev/null @@ -1,375 +0,0 @@ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import { useEffect } from 'react' -import state from 'state' -import inputs from 'state/inputs' -import { ColorStyle, MoveType, SizeStyle } from 'types' -import { metaKey } from 'utils' - -export default function useKeyboardEvents() { - useEffect(() => { - function handleKeyDown(e: KeyboardEvent) { - const info = inputs.keydown(e) - const meta = metaKey(e) - - if ( - meta && - ![ - 'a', - 'i', - 'r', - 'j', - 'ArrowLeft', - 'ArrowRight', - 'ArrowUp', - 'ArrowDown', - 'z', - ].includes(e.key) - ) { - e.preventDefault() - } - - switch (e.key) { - case '1': { - if (meta) { - state.send('CHANGED_STYLE', { color: ColorStyle.Black }) - break - } - if (e.altKey) { - state.send('CHANGED_STYLE', { size: SizeStyle.Small }) - break - } - state.send('SELECTED_SELECT_TOOL', info) - break - } - case '2': { - if (meta) { - state.send('CHANGED_STYLE', { color: ColorStyle.White }) - break - } - if (e.altKey) { - state.send('CHANGED_STYLE', { size: SizeStyle.Medium }) - break - } - state.send('SELECTED_DRAW_TOOL', info) - break - } - case '3': { - if (meta) { - state.send('CHANGED_STYLE', { color: ColorStyle.Green }) - break - } - if (e.altKey) { - state.send('CHANGED_STYLE', { size: SizeStyle.Large }) - break - } - state.send('SELECTED_RECTANGLE_TOOL', info) - break - } - case '4': { - if (meta) { - state.send('CHANGED_STYLE', { color: ColorStyle.Blue }) - } - state.send('SELECTED_ELLIPSE_TOOL', info) - break - } - case '5': { - if (meta) { - state.send('CHANGED_STYLE', { color: ColorStyle.Indigo }) - break - } - state.send('SELECTED_ARROW_TOOL', info) - break - } - case '6': { - if (meta) { - state.send('CHANGED_STYLE', { color: ColorStyle.Violet }) - break - } - state.send('SELECTED_TEXT_TOOL', info) - break - } - case '7': { - if (meta) { - state.send('CHANGED_STYLE', { color: ColorStyle.Red }) - break - } - state.send('TOGGLED_TOOL_LOCK', info) - break - } - case '8': { - if (meta) { - state.send('CHANGED_STYLE', { color: ColorStyle.Orange }) - break - } - break - } - case '9': { - if (meta) { - state.send('CHANGED_STYLE', { color: ColorStyle.Yellow }) - break - } - break - } - case 'ArrowUp': { - state.send('NUDGED', { delta: [0, -1], ...info }) - break - } - case 'ArrowRight': { - state.send('NUDGED', { delta: [1, 0], ...info }) - break - } - case 'ArrowDown': { - state.send('NUDGED', { delta: [0, 1], ...info }) - break - } - case 'ArrowLeft': { - state.send('NUDGED', { delta: [-1, 0], ...info }) - break - } - case '=': { - if (e.metaKey) { - state.send('ZOOMED_IN') - } - break - } - case '-': { - if (e.metaKey) { - state.send('ZOOMED_OUT') - } - break - } - case '!': { - // Shift + 1 - if (e.shiftKey) { - state.send('ZOOMED_TO_FIT') - } - break - } - case '@': { - // Shift + 2 - if (e.shiftKey) { - state.send('ZOOMED_TO_SELECTION') - } - break - } - case ')': { - // Shift + 0 - if (e.shiftKey) { - state.send('ZOOMED_TO_ACTUAL') - } - break - } - case 'Escape': { - state.send('CANCELLED') - break - } - case 'z': { - if (meta) { - if (e.shiftKey) { - state.send('REDO', info) - } else { - state.send('UNDO', info) - } - } - break - } - case '‘': { - if (meta) { - state.send('MOVED', { - ...info, - type: MoveType.ToFront, - }) - } - break - } - case '“': { - if (meta) { - state.send('MOVED', { - ...info, - type: MoveType.ToBack, - }) - } - break - } - case ']': { - if (meta) { - state.send('MOVED', { - ...info, - type: MoveType.Forward, - }) - } - break - } - case '[': { - if (meta) { - state.send('MOVED', { - ...info, - type: MoveType.Backward, - }) - } - break - } - case 'Shift': { - state.send('PRESSED_SHIFT_KEY', info) - break - } - case 'Alt': { - state.send('PRESSED_ALT_KEY', info) - break - } - case 'Backspace': { - if (meta) { - if (e.shiftKey) { - if (window.confirm('Reset document and state?')) { - state.send('RESET_DOCUMENT_STATE', info) - } - } else { - state.send('FORCE_CLEARED_PAGE', info) - } - } else { - state.send('DELETED', info) - } - break - } - case 'g': { - if (meta) { - if (e.shiftKey) { - state.send('UNGROUPED', info) - } else { - state.send('GROUPED', info) - } - } - break - } - case 's': { - if (meta) { - if (e.shiftKey) { - state.send('SAVED_AS_TO_FILESYSTEM', info) - } else { - state.send('SAVED', info) - } - } - break - } - case 'o': { - if (meta) { - break - } else { - state.send('SELECTED_DOT_TOOL', info) - } - break - } - case 'v': { - if (meta) { - state.send('PASTED', info) - } else { - state.send('SELECTED_SELECT_TOOL', info) - } - break - } - case 'a': { - if (meta) { - state.send('SELECTED_ALL', info) - } else { - state.send('SELECTED_ARROW_TOOL', info) - } - break - } - case 'd': { - if (meta) { - state.send('DUPLICATED', info) - } else { - state.send('SELECTED_DRAW_TOOL', info) - } - break - } - case 't': { - state.send('SELECTED_TEXT_TOOL', info) - break - } - case 'c': { - if (meta) { - if (e.shiftKey) { - state.send('COPIED_TO_SVG', info) - } else { - state.send('COPIED', info) - } - } else { - state.send('SELECTED_ELLIPSE_TOOL', info) - } - break - } - case 'i': { - if (meta) { - break - } else { - state.send('SELECTED_CIRCLE_TOOL', info) - } - break - } - case 'l': { - if (meta) { - if (e.shiftKey) { - state.send('TOGGLED_LOGGER') - } else { - state.send('LOADED_FROM_FILE_STSTEM', info) - } - } else { - state.send('SELECTED_LINE_TOOL', info) - } - break - } - case 'y': { - if (meta) { - break - } else { - state.send('SELECTED_RAY_TOOL', info) - } - break - } - case 'p': { - if (meta) { - break - } else { - state.send('SELECTED_POLYLINE_TOOL', info) - } - break - } - case 'r': { - if (meta) { - break - } else { - state.send('SELECTED_RECTANGLE_TOOL', info) - } - break - } - case '|': { - state.send('COPIED_STATE_TO_CLIPBOARD') - break - } - default: { - null - } - } - } - - function handleKeyUp(e: KeyboardEvent) { - const info = inputs.keyup(e) - - if (e.key === 'Shift') { - state.send('RELEASED_SHIFT_KEY', info) - } - - if (e.key === 'Alt') { - state.send('RELEASED_ALT_KEY', info) - } - } - - window.addEventListener('keydown', handleKeyDown) - window.addEventListener('keyup', handleKeyUp) - return () => { - window.removeEventListener('keydown', handleKeyDown) - window.removeEventListener('keyup', handleKeyUp) - } - }, []) -} diff --git a/hooks/useLoadOnMount.ts b/hooks/useLoadOnMount.ts deleted file mode 100644 index 094278b98..000000000 --- a/hooks/useLoadOnMount.ts +++ /dev/null @@ -1,27 +0,0 @@ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import { useEffect } from 'react' -import state from 'state' -// import coopState from 'state/coop/coop-state' - -export default function useLoadOnMount(roomId?: string) { - useEffect(() => { - if ('fonts' in document) { - const fonts = (document as any).fonts - fonts.load('12px Verveine Regular', 'Fonts are loaded!').then(() => { - state.send('MOUNTED', { roomId }) - - // if (roomId !== undefined) { - // state.send('RT_LOADED_ROOM', { id: roomId }) - // coopState.send('JOINED_ROOM', { id: roomId }) - // } - }) - } else { - setTimeout(() => state.send('MOUNTED'), 1000) - } - - return () => { - state.send('UNMOUNTED', { roomId }) - // coopState.send('LEFT_ROOM', { id: roomId }) - } - }, [roomId]) -} diff --git a/hooks/usePageShapes.ts b/hooks/usePageShapes.ts deleted file mode 100644 index 6b074da88..000000000 --- a/hooks/usePageShapes.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { useEffect } from 'react' -import state, { useSelector } from 'state' -import { getShapeUtils } from 'state/shape-utils' -import { PageState, Bounds, ShapeType, Shape } from 'types' -import { - boundsCollide, - boundsContain, - debounce, - deepCompareArrays, -} from 'utils' -import tld from 'utils/tld' - -const viewportCache = new WeakMap() - -export default function usePageShapes(): Shape[] { - // Reset the viewport cache when the window resizes - useEffect(() => { - const handleResize = debounce(() => state.send('RESIZED_WINDOW'), 32) - - window.addEventListener('resize', handleResize) - - return () => { - window.removeEventListener('resize', handleResize) - } - }, []) - - // Get the shapes that fit into the current window - const visiblePageShapeIds = useSelector((s) => { - const pageState = tld.getPageState(s.data) - - if (!viewportCache.has(pageState)) { - const viewport = tld.getViewport(s.data) - viewportCache.set(pageState, viewport) - } - - const viewport = viewportCache.get(pageState) - - const shapesToShow = s.values.currentShapes.filter((shape) => { - if (shape.type === ShapeType.Ray || shape.type === ShapeType.Line) { - return true - } - - const shapeBounds = getShapeUtils(shape).getBounds(shape) - return ( - boundsContain(viewport, shapeBounds) || - boundsCollide(viewport, shapeBounds) - ) - }) - - return shapesToShow - }, deepCompareArrays) - - return visiblePageShapeIds -} diff --git a/hooks/useSafariFocusOutFix.ts b/hooks/useSafariFocusOutFix.ts deleted file mode 100644 index 4058e8576..000000000 --- a/hooks/useSafariFocusOutFix.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { isMobile } from 'utils' -import { useEffect } from 'react' -import state from 'state' - -// Send event on iOS when a user presses the "Done" key while editing -// a text element. - -function handleFocusOut() { - state.send('BLURRED_EDITING_SHAPE') -} - -export default function useSafariFocusOutFix(): void { - useEffect(() => { - if (isMobile()) { - document.addEventListener('focusout', handleFocusOut) - - return () => { - document.removeEventListener('focusout', handleFocusOut) - } - } - }, []) -} diff --git a/hooks/useShape.ts b/hooks/useShape.ts deleted file mode 100644 index a3ac20d47..000000000 --- a/hooks/useShape.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import { useSelector } from 'state' -import { getShapeUtils } from 'state/shape-utils' -import tld from 'utils/tld' - -export default function useShape(id: string) { - return useSelector( - (s) => tld.getShape(s.data, id), - (prev, next) => - !( - prev && - next && - next !== prev && - getShapeUtils(next).shouldRender(next, prev) - ) - ) -} diff --git a/hooks/useShapeEvents.ts b/hooks/useShapeEvents.ts deleted file mode 100644 index 515f46bc5..000000000 --- a/hooks/useShapeEvents.ts +++ /dev/null @@ -1,111 +0,0 @@ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import React, { MutableRefObject, useCallback } from 'react' -import state from 'state' -import inputs from 'state/inputs' -import Vec from 'utils/vec' - -export default function useShapeEvents( - id: string, - isCurrentParent: boolean, - rGroup: MutableRefObject -) { - const handlePointerDown = useCallback( - (e: React.PointerEvent) => { - if (isCurrentParent) return - if (!inputs.canAccept(e.pointerId)) return - e.stopPropagation() - - rGroup.current.setPointerCapture(e.pointerId) - - const info = inputs.pointerDown(e, id) - - if (e.button === 0) { - if (inputs.isDoubleClick() && !(info.altKey || info.metaKey)) { - state.send('DOUBLE_POINTED_SHAPE', info) - } - - state.send('POINTED_SHAPE', info) - } else { - state.send('RIGHT_POINTED', info) - } - }, - [id, isCurrentParent] - ) - - const handlePointerUp = useCallback( - (e: React.PointerEvent) => { - if (isCurrentParent) return - if (!inputs.canAccept(e.pointerId)) return - e.stopPropagation() - - rGroup.current.releasePointerCapture(e.pointerId) - state.send('STOPPED_POINTING', inputs.pointerUp(e, id)) - }, - [id, isCurrentParent] - ) - - const handlePointerEnter = useCallback( - (e: React.PointerEvent) => { - if (isCurrentParent) return - if (!inputs.canAccept(e.pointerId)) return - e.stopPropagation() - - state.send('HOVERED_SHAPE', inputs.pointerEnter(e, id)) - }, - [id, isCurrentParent] - ) - - const handlePointerMove = useCallback( - (e: React.PointerEvent) => { - if (!inputs.canAccept(e.pointerId)) return - - const prev = inputs.pointer?.point - const info = inputs.pointerMove(e) - - if (prev && state.isIn('selecting') && inputs.keys[' ']) { - if (!e.currentTarget.hasPointerCapture(e.pointerId)) { - e.currentTarget.setPointerCapture(e.pointerId) - } - - state.send('KEYBOARD_PANNED_CAMERA', { - delta: Vec.sub(prev, info.point), - }) - return - } - - if (isCurrentParent) return - - state.send('MOVED_OVER_SHAPE', inputs.pointerEnter(e, id)) - }, - [id, isCurrentParent] - ) - - const handlePointerLeave = useCallback( - (e: React.PointerEvent) => { - if (isCurrentParent) return - if (!inputs.canAccept(e.pointerId)) return - e.stopPropagation() - - state.send('UNHOVERED_SHAPE', { target: id }) - }, - [id, isCurrentParent] - ) - - const handleTouchStart = useCallback((e: React.TouchEvent) => { - e.preventDefault() - }, []) - - const handleTouchEnd = useCallback((e: React.TouchEvent) => { - e.preventDefault() - }, []) - - return { - onPointerDown: handlePointerDown, - onPointerUp: handlePointerUp, - onPointerEnter: handlePointerEnter, - onPointerMove: handlePointerMove, - onPointerLeave: handlePointerLeave, - onTouchStart: handleTouchStart, - onTouchEnd: handleTouchEnd, - } -} diff --git a/hooks/useShapesToRender.ts b/hooks/useShapesToRender.ts deleted file mode 100644 index 164d4c6a3..000000000 --- a/hooks/useShapesToRender.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { useSelector } from 'state' -import { getShapeUtils } from 'state/shape-utils' -import { deepCompareArrays } from 'utils' -import tld from 'utils/tld' - -export default function useShapesToRender(): string[] { - return useSelector( - (s) => - Object.values(tld.getPage(s.data).shapes) - .filter((shape) => shape && !getShapeUtils(shape).isForeignObject) - .map((shape) => shape.id), - deepCompareArrays - ) -} diff --git a/hooks/useStateTheme.ts b/hooks/useStateTheme.ts deleted file mode 100644 index 5ef0c1f4f..000000000 --- a/hooks/useStateTheme.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { useTheme } from 'next-themes' -import { useEffect } from 'react' -import state from 'state' - -export default function useStateTheme(): void { - const { theme } = useTheme() - - useEffect(() => { - state.send('CHANGED_DARK_MODE', { isDarkMode: theme === 'dark' }) - }, [theme]) -} diff --git a/hooks/useZoomEvents.ts b/hooks/useZoomEvents.ts deleted file mode 100644 index 836a23c1a..000000000 --- a/hooks/useZoomEvents.ts +++ /dev/null @@ -1,85 +0,0 @@ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -import { useRef } from 'react' -import state from 'state' -import inputs from 'state/inputs' -import vec from 'utils/vec' -import { useGesture } from 'react-use-gesture' -import { - fastBrushSelect, - fastDrawUpdate, - fastPanUpdate, - fastPinchCamera, - fastTransform, - fastTranslate, - fastZoomUpdate, -} from 'state/hacks' - -/** - * Capture zoom gestures (pinches, wheels and pans) and send to the state. - * @param ref - * @returns - */ -export default function useZoomEvents() { - const rPinchDa = useRef(undefined) - const rPinchPoint = useRef(undefined) - - useGesture( - { - onWheel: ({ event, delta }) => { - if (event.ctrlKey) { - const { point } = inputs.wheel(event as WheelEvent) - fastZoomUpdate(point, delta[1]) - return - } - - fastPanUpdate(delta) - - const info = inputs.pointer - - if (state.isIn('draw.editing')) { - fastDrawUpdate(info) - } else if (state.isIn('brushSelecting')) { - fastBrushSelect(info.point) - } else if (state.isIn('translatingSelection')) { - fastTranslate(info) - } else if (state.isIn('transformingSelection')) { - fastTransform(info) - } - - state.send('PANNED_CAMERA', { - delta, - ...inputs.wheel(event as WheelEvent), - }) - }, - onPinch: ({ pinching, da, origin }) => { - if (!pinching) { - state.send('STOPPED_PINCHING') - rPinchDa.current = undefined - rPinchPoint.current = undefined - return - } - - if (rPinchPoint.current === undefined) { - state.send('STARTED_PINCHING') - rPinchDa.current = da - rPinchPoint.current = origin - } - - const [distanceDelta] = vec.sub(rPinchDa.current, da) - - fastPinchCamera( - origin, - vec.sub(rPinchPoint.current, origin), - distanceDelta - ) - - rPinchDa.current = da - rPinchPoint.current = origin - }, - }, - { - domTarget: document.body, - eventOptions: { passive: false }, - } - ) -} diff --git a/jest.config.js b/jest.config.js deleted file mode 100644 index 40de27f38..000000000 --- a/jest.config.js +++ /dev/null @@ -1,20 +0,0 @@ -module.exports = { - testEnvironment: 'jsdom', - testPathIgnorePatterns: ['node_modules', '.next'], - transformIgnorePatterns: [ - 'node_modules/(?!(sucrase|@state-designer/core|@state-designer/react|browser-fs-access)/)', - ], - transform: { - '^.+\\.(ts|tsx|mjs)$': 'babel-jest', - }, - modulePaths: ['', 'node_modules'], - testMatch: ['**/__tests__/**/*test.[t]s?(x)'], - watchPlugins: [ - 'jest-watch-typeahead/filename', - 'jest-watch-typeahead/testname', - ], - moduleNameMapper: { - '\\.(css|less|sass|scss)$': 'identity-obj-proxy', - '\\.(gif|ttf|eot|svg|png)$': '/test/__mocks__/fileMock.js', - }, -} diff --git a/lerna.json b/lerna.json new file mode 100644 index 000000000..8d4d2a01d --- /dev/null +++ b/lerna.json @@ -0,0 +1,9 @@ +{ + "version": "0.0.59", + "registry": "https://registry.npmjs.org/", + "publishConfig": { + "access": "public" + }, + "npmClient": "yarn", + "useWorkspaces": true +} diff --git a/next.config.js b/next.config.js deleted file mode 100644 index 49de7e833..000000000 --- a/next.config.js +++ /dev/null @@ -1,76 +0,0 @@ -/* eslint-disable @typescript-eslint/no-var-requires */ -const withPWA = require('next-pwa') - -const { - GITHUB_ID, - GITHUB_SECRET, - GITHUB_API_SECRET, - NEXT_PUBLIC_SENTRY_DSN: SENTRY_DSN, - SENTRY_ORG, - SENTRY_PROJECT, - SENTRY_AUTH_TOKEN, - NODE_ENV, - VERCEL_GIT_COMMIT_SHA, - GA_MEASUREMENT_ID, -} = process.env - -process.env.SENTRY_DSN = SENTRY_DSN - -const isProduction = NODE_ENV === 'production' - -module.exports = withPWA({ - pwa: { - disable: !isProduction, - dest: 'public', - }, -}) - -const basePath = '' - -module.exports = withPWA({ - productionBrowserSourceMaps: true, - env: { - NEXT_PUBLIC_COMMIT_SHA: VERCEL_GIT_COMMIT_SHA, - GA_MEASUREMENT_ID, - GITHUB_ID, - GITHUB_SECRET, - GITHUB_API_SECRET, - }, - webpack: (config, options) => { - if (!options.isServer) { - config.resolve.alias['@sentry/node'] = '@sentry/browser' - } - - config.plugins.push( - new options.webpack.DefinePlugin({ - 'process.env.NEXT_IS_SERVER': JSON.stringify( - options.isServer.toString() - ), - }) - ) - - if ( - SENTRY_DSN && - SENTRY_ORG && - SENTRY_PROJECT && - SENTRY_AUTH_TOKEN && - VERCEL_GIT_COMMIT_SHA && - isProduction - ) { - config.plugins.push( - new SentryWebpackPlugin({ - include: '.next', - ignore: ['node_modules'], - stripPrefix: ['webpack://_N_E/'], - urlPrefix: `~${basePath}/_next`, - release: VERCEL_GIT_COMMIT_SHA, - authToken: SENTRY_AUTH_TOKEN, - org: SENTRY_PROJECT, - project: SENTRY_ORG, - }) - ) - } - return config - }, - basePath, -}) diff --git a/package.json b/package.json index 2be058e76..46f4482fd 100644 --- a/package.json +++ b/package.json @@ -1,99 +1,116 @@ { - "name": "with-typescript-eslint-jest", - "author": "@erikdstock", + "name": "tldraw", + "private": true, + "author": "@steveruizok", + "description": "A tiny little drawing app.", + "repository": { + "type": "git", + "url": "git+https://github.com/tldraw/tldraw.git" + }, "license": "MIT", - "version": "1.0.0", + "version": "0.0.36", + "workspaces": [ + "packages/core", + "packages/tldraw", + "packages/dev", + "packages/www" + ], "scripts": { - "build": "next build", - "dev": "next dev", - "format": "prettier --write .", - "lint": "eslint . --ext ts --ext tsx --ext js", - "scripts": "prettier --write './state/code/docs.md' && node scripts/type-gen && node scripts/docs-gen && prettier --write './components/code-panel/*'", - "start": "next start", - "test-all": "yarn lint && yarn type-check && yarn test", - "test:update": "jest --updateSnapshot", + "test": "jest", "test:watch": "jest --watchAll", - "test": "jest --watchAll=false", - "type-check": "tsc --pretty --noEmit" - }, - "husky": { - "hooks": { - "pre-commit": "lint-staged", - "pre-push": "yarn lint && yarn format && yarn type-check" - } - }, - "lint-staged": { - "*.@(ts|tsx)": [ - "yarn format", - "yarn lint" - ] - }, - "dependencies": { - "@liveblocks/client": "^0.8.1", - "@liveblocks/node": "^0.3.0", - "@liveblocks/react": "^0.8.0", - "@monaco-editor/react": "^4.2.1", - "@radix-ui/react-alert-dialog": "^0.0.19", - "@radix-ui/react-checkbox": "^0.0.16", - "@radix-ui/react-context-menu": "^0.0.23", - "@radix-ui/react-dialog": "^0.0.19", - "@radix-ui/react-dropdown-menu": "^0.0.21", - "@radix-ui/react-hover-card": "^0.0.3", - "@radix-ui/react-icons": "^1.0.3", - "@radix-ui/react-radio-group": "^0.0.17", - "@radix-ui/react-tooltip": "^0.0.19", - "@sentry/integrations": "^6.8.0", - "@sentry/node": "^6.8.0", - "@sentry/react": "^6.8.0", - "@sentry/tracing": "^6.8.0", - "@sentry/webpack-plugin": "^1.15.1", - "@state-designer/react": "^2.0.3", - "@stitches/react": "^0.2.2", - "browser-fs-access": "^0.17.3", - "framer-motion": "^4.1.17", - "gtag": "^1.0.1", - "idb-keyval": "^5.0.6", - "immer": "^9.0.5", - "ismobilejs": "^1.1.1", - "next": "^11.0.1", - "next-auth": "^3.27.3", - "next-pwa": "^5.2.23", - "next-themes": "^0.0.15", - "perfect-freehand": "^0.4.10", - "react": "^17.0.2", - "react-dom": "^17.0.2", - "react-error-boundary": "^3.1.3", - "react-feather": "^2.0.9", - "react-markdown": "^6.0.2", - "react-use-gesture": "^9.1.3", - "sucrase": "^3.19.0" + "lerna": "lerna", + "start": "lerna run start:pre && lerna run start --stream --parallel", + "start:www": "yarn build:packages && lerna run start --parallel & cd packages/www && yarn dev", + "build": "yarn build:packages && cd packages/www && yarn build", + "build:packages": "cd packages/core && yarn build && cd ../tldraw && yarn build", + "publish:patch": "yarn build:packages && lerna publish patch", + "docs": "lerna run docs --stream" }, "devDependencies": { - "@babel/core": "^7.14.6", - "@types/jest": "^26.0.23", - "@types/node": "^14.14.25", - "@types/react": "^17.0.1", - "@typescript-eslint/eslint-plugin": "^4.14.2", - "@typescript-eslint/parser": "^4.14.2", - "babel-jest": "^27.0.5", - "eslint": "^7.19.0", - "eslint-config-next": "^11.0.0", - "eslint-config-prettier": "^7.2.0", - "eslint-plugin-react": "^7.19.0", - "husky": "^4.2.3", - "identity-obj-proxy": "^3.0.0", - "jest": "^27.0.5", - "jest-esm-transformer": "^1.0.0", - "jest-watch-typeahead": "^0.6.1", - "lint-staged": "^10.0.10", - "monaco-editor": "^0.25.2", - "prettier": "^2.3.1", - "typescript": "^4.1.3" + "@babel/core": "^7.15.0", + "@babel/plugin-syntax-import-meta": "^7.10.4", + "@babel/preset-env": "^7.15.0", + "@babel/preset-react": "^7.14.5", + "@babel/preset-typescript": "^7.15.0", + "@testing-library/jest-dom": "^5.14.1", + "@testing-library/react": "^12.0.0", + "@types/jest": "^27.0.1", + "@types/node": "^15.0.1", + "@types/react": "^17.0.19", + "@types/react-dom": "^17.0.9", + "@typescript-eslint/eslint-plugin": "^4.19.0", + "@typescript-eslint/parser": "^4.19.0", + "babel-jest": "^27.1.0", + "eslint": "^7.32.0", + "fake-indexeddb": "^3.1.3", + "jest": "^27.1.0", + "lerna": "^3.15.0", + "react": "^17.0.2", + "react-dom": "^17.0.2", + "ts-jest": "^27.0.5", + "tslib": "^2.3.0", + "typedoc": "^0.21.9", + "typescript": "^4.4.2" }, + "dependencies": {}, "prettier": { - "semi": false, + "trailingComma": "es5", "singleQuote": true, - "tabWidth": 2, - "useTabs": false + "semi": false, + "printWidth": 100 + }, + "jest": { + "preset": "ts-jest", + "setupFilesAfterEnv": [ + "/setupTests.ts" + ], + "transform": { + "^.+\\.(tsx|jsx|ts|js|mjs)?$": "ts-jest" + }, + "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", + "moduleFileExtensions": [ + "ts", + "tsx", + "js", + "jsx", + "json", + "node" + ], + "globals": { + "ts-jest": { + "tsconfig": "tsconfig.json", + "babelConfig": { + "presets": [ + [ + "@babel/preset-env", + { + "targets": { + "esmodules": true + } + } + ], + [ + "@babel/preset-react" + ], + "@babel/preset-typescript" + ], + "plugins": [ + "@babel/plugin-syntax-import-meta" + ] + } + } + }, + "testEnvironment": "jsdom", + "modulePathIgnorePatterns": [ + "/packages/core/dist/", + "/packages/tldraw/dist/", + "/packages/tldraw/test-utils/" + ], + "moduleNameMapper": { + "@tldraw/core": "/packages/core/src", + "@tldraw/tldraw": "/packages/tldraw/src", + "\\~(.*)": "/packages/tldraw/src/$1", + "\\+(.*)": "/packages/core/src/$1" + } } -} +} \ No newline at end of file diff --git a/packages/core/README.md b/packages/core/README.md new file mode 100644 index 000000000..6594872ae --- /dev/null +++ b/packages/core/README.md @@ -0,0 +1,273 @@ +# @tldraw/core + +This package contains the core of the [tldraw](https://tldraw.com) library. It includes: + +- [`Renderer`](#renderer) - a React component +- [`TLShapeUtility`](#tlshapeutility) - an abstract class for custom shape utilities +- the library's TypeScript [`types`](#types) +- several utility classes: + - [`Utils`](#utils) + - [`Vec`](#vec) + - [`Svg`](#svg) + - [`brushUpdater`](#brushupdater) + - [`Intersect`](#intersect) + +## Installation + +```bash +yarn add @tldraw/core --peer +``` + +## Usage + +Import the `Renderer` React component and pass it the required props. + +- [Example](#example) +- [Guide: Create a Custom Shape](#create-a-custom-shape) + +## Documentation + +### `Renderer` + +| Prop | Type | Description | +| ------------ | --------------------------------- | ---------------------------------------------------------------------- | +| `page` | [`TLPage`](#tlpage) | The current page object. | +| `pageState` | [`TLPageState`](#tlpagestate) | The current page's state. | +| `shapeUtils` | [`TLShapeUtils`](#tlshapeutils){} | The shape utilities used to render the shapes. | +| `theme` | `object` | (optional) an object with overrides for the Renderer's default colors. | + +The theme object accepts valid CSS colors for the following properties: + +| Property | Description | +| -------------- | --------------------------------------------------------------- | +| `foreground` | (optional) The primary (usually "text") color | +| `background` | (optional) The default page's background color | +| `brushFill` | (optional) The fill color of the brush selection box | +| `brushStroke` | (optional) The stroke color of the brush selection box | +| `selectFill` | (optional) The fill color of the selection bounds | +| `selectStroke` | (optional) The stroke color of the selection bounds and handles | + +> Tip: If providing an object for the `theme` prop, either define the object outside of the parent component or memoize it with `React.useMemo`. + +The renderer also accepts many (optional) event callbacks. + +| Prop | Description | +| --------------------------- | --------------------------------------------------------- | +| `onPan` | The user panned with the mouse wheel | +| `onZoom` | The user zoomed with the mouse wheel | +| `onPinch` | The user moved their pointers during a pinch | +| `onPinchEnd` | The user stopped a two-pointer pinch | +| `onPinchStart` | The user began a two-pointer pinch | +| `onPointerMove` | The user moved their pointer | +| `onPointerUp` | The user ended a point | +| `onPointShape` | The user pointed a shape | +| `onDoubleClickShape` | The user double-pointed a shape | +| `onRightPointShape` | The user right-pointed a shape | +| `onMoveOverShape` | The user moved their pointer a shape | +| `onHoverShape` | The user moved their pointer onto a shape | +| `onUnhoverShape` | The user moved their pointer off of a shape | +| `onPointHandle` | The user pointed a shape handle | +| `onDoubleClickHandle` | The user double-pointed a shape handle | +| `onRightPointHandle`- | he user right-pointed a shape handle | +| `onMoveOverHandle` | The user moved their pointer over a shape handle | +| `onHoverHandle` | The user moved their pointer onto a shape handle | +| `onUnhoverHandle` | The user moved their pointer off of a shape handle | +| `onPointCanvas` | The user pointed the canvas | +| `onDoubleClickCanvas` | The user double-pointed the canvas | +| `onRightPointCanvas` | The user right-pointed the canvas | +| `onPointBounds` | The user pointed the selection bounds | +| `onDoubleClickBounds` | The user double-pointed the selection bounds | +| `onRightPointBounds` | The user right-pointed the selection bounds | +| `onPointBoundsHandle` | The user pointed a selection bounds edge or corner | +| `onDoubleClickBoundsHandle` | The user double-pointed a selection bounds edge or corner | +| `onBlurEditingShape` | The user blurred an editing (text) shape | +| `onError` | The renderer encountered an error | + +> Tip: If providing callbacks, either define the functions outside of the parent component or memoize them first with `React.useMemo`. + +### `TLPage` + +An object describing the current page. It contains: + +| Property | Type | Description | +| ----------------- | --------------------------- | --------------------------------------------------------------------------- | +| `id` | `string` | A unique id for the page. | +| `shapes` | [`TLShape{}`](#tlshape) | A table of shapes. | +| `bindings` | [`TLBinding{}`](#tlbinding) | A table of bindings. | +| `backgroundColor` | `string` | (optional) The page's background fill color. Will also overwrite the theme. | + +### `TLPageState` + +An object describing the current page. It contains: + +| Property | Type | Description | +| ------------------ | ---------- | --------------------------------------------------- | +| `id` | `string` | The corresponding page's id | +| `selectedIds` | `string[]` | An array of selected shape ids | +| `camera` | `object` | An object describing the camera state | +| `camera.point` | `number[]` | The camera's `[x, y]` coordinates | +| `camera.zoom` | `number` | The camera's zoom level | +| `currentParentId` | `string` | (optional) The current parent id for selection | +| `brush` | `TLBounds` | (optional) A `Bounds` for the current selection box | +| `pointedId` | `string` | (optional) The currently pointed shape id | +| `hoveredId` | `string` | (optional) The currently hovered shape id | +| `editingId` | `string` | (optional) The currently editing shape id | +| `editingBindingId` | `string` | (optional) The currently editing binding id | + +### `TLShape` + +An object that describes a shape on the page. The shapes in your document should extend this interface with other properties. See [Guide: Create a Custom Shape](#create-a-custom-shape). + +| Property | Type | Description | +| --------------------- | ------------------------- | -------------------------------------------------------------------------------------- | +| `id` | `string` | The shape's id. | +| `type` | `string` | The type of the shape, corresponding to the `type` of a [`TLShapeUtil`](#tlshapeutil). | +| `parentId` | `string` | The id of the shape's parent (either the current page or another shape). | +| `childIndex` | `number` | the order of the shape among its parent's children | +| `name` | `string` | the name of the shape | +| `point` | `number[]` | the shape's current `[x, y]` coordinates on the page | +| `rotation` | `number` | (optiona) The shape's current rotation in radians | +| `children` | `string[]` | (optional) An array containing the ids of this shape's children | +| `handles` | [`TLHandle{}`](#tlhandle) | (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 programatically | +| `isAspectRatioLocked` | `boolean` | (optional) True if the shape's aspect ratio is locked | + +### `TLHandle` + +An object that describes a relationship between two shapes on the page. + +| Property | Type | Description | +| -------- | ---------- | ---------------------------------------------- | +| `id` | `string` | An id for the handle. | +| `index` | `number` | The handle's order within the shape's handles. | +| `point` | `number[]` | The handle's `[x, y]` coordinates. | + +### `TLBinding` + +An object that describes a relationship between two shapes on the page. + +| Property | Type | Description | +| -------- | -------- | --------------------------------------------- | +| `id` | `string` | A unique id for the binding. | +| `type` | `string` | The binding's type. | +| `fromId` | `string` | The id of the shape where the binding begins. | +| `toId` | `string` | The id of the shape where the binding begins. | + +### `TLShapeUtil` + +The `TLShapeUtil` is an abstract class that you can extend to create utilities for your custom shapes. See [Guide: Create a Custom Shape](#create-a-custom-shape). + +### `brushUpdater` + +The `brushUpdater` is a special class instance that allows you to quickly update the selection brush rectangle. + +| Method | Description | +| ------- | --------------------------------------------------------------- | +| `set` | a method that accepts either a `TLBounds` object or `undefined` | +| `clear` | a method to hide the brush | + +Normally, the renderer's brush will update in response to changes to `pageState.brush`; however, calling `brushUpdater.set` will produce a faster change in the brush rectangle. Calling `brushUpdater.set` will prevent the brush from any future updates from `pageState.brush`. + +## `inputs` + +A class instance that stores the current pointer position and pressed keys. + +### `Utils` + +A general purpose utility class. + +### `Vec` + +A utility class for vector math and related methods. + +### `Svg` + +A utility class for creating SVG path data through imperative commands. + +### `Intersect` + +A utility class for finding intersections between various geometric shapes. + +## Guides + +### Create a Custom Shape + +... + +### Example + +```tsx +import * as React from "react" +import { Renderer, TLShape, TLShapeUtil, Vec } from '@tldraw/core' + +interface RectangleShape extends TLShape { + type: "rectangle", + size: number[] +} + +class Rectangle extends TLShapeUtil { + // See the "Create a Custom Shape" guide +} + +const myShapes = { rectangle: new Rectangle() } + +function App() { + const [page, setPage] = React.useState({ + id: "page1" + shapes: { + "rect1": { + id: 'rect1', + parentId: 'page1', + name: 'Rectangle', + childIndex: 0, + type: 'rectangle', + point: [0, 0], + rotation: 0, + size: [100, 100], + } + }, + bindings: {} + }) + + const [pageState, setPageState] = React.useState({ + id: "page1", + selectedIds: [], + camera: { + point: [0,0], + zoom: 1 + } + }) + + const handlePan = React.useCallback((delta: number[]) => { + setPageState(pageState => { + ...pageState, + camera: { + zoom, + point: Vec.sub(pageState.point, Vec.div(delta, pageState.zoom)), + }, + }) + }, []) + + return () +} +``` + +## Development + +Run `yarn` to install dependencies. + +Run `yarn start` to begin the monorepo's development server (`@tldraw/site`). + +Run `nx test core` to execute unit tests via [Jest](https://jestjs.io). + +## Contribution + +To contribute, visit the [Discord channel](https://discord.gg/s4FXZ6fppJ). diff --git a/packages/core/package.json b/packages/core/package.json new file mode 100644 index 000000000..fd7bed0f2 --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,58 @@ +{ + "name": "@tldraw/core", + "version": "0.0.59", + "private": false, + "description": "A tiny little drawing app (core).", + "author": "@steveruizok", + "repository": { + "type": "git", + "url": "git+https://github.com/tldraw/tldraw.git", + "directory": "packages/core" + }, + "license": "MIT", + "keywords": [], + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.js", + "types": "./dist/types/index.d.ts", + "typings": "./dist/types/index.d.ts", + "scripts": { + "start:pre": "node scripts/pre-dev && yarn types:pre", + "start": "node scripts/dev & yarn types:dev", + "build": "yarn clean && node scripts/build && yarn types:build", + "types:pre": "tsc ", + "types:dev": "tsc --watch ", + "types:build": "tsc --project tsconfig.build.json", + "lint": "eslint src/ --ext .ts,.tsx", + "clean": "rm -rf dist", + "ts-node": "ts-node", + "docs": "typedoc --entryPoints src/index.ts" + }, + "devDependencies": { + "@babel/core": "^7.15.5", + "@babel/preset-env": "^7.15.4", + "@types/jest": "^27.0.1", + "@types/node": "^16.7.10", + "@types/react": "^17.0.16", + "@types/react-dom": "^17.0.9", + "@typescript-eslint/eslint-plugin": "^4.30.0", + "@typescript-eslint/parser": "^4.30.0", + "esbuild": "^0.12.24", + "eslint": "^7.32.0", + "lerna": "^4.0.0", + "react": "^17.0.2", + "react-dom": "^17.0.2", + "ts-node": "^10.2.1", + "tslib": "^2.3.1", + "typedoc": "^0.21.9", + "typescript": "^4.4.2" + }, + "peerDependencies": { + "react": "^17.0.2", + "react-dom": "^17.0.2" + }, + "dependencies": { + "deepmerge": "^4.2.2", + "react-use-gesture": "^9.1.3" + }, + "gitHead": "838fabdbff1a66d4d7ee8aa5c5d117bc55acbff2" +} diff --git a/packages/core/scripts/build.js b/packages/core/scripts/build.js new file mode 100644 index 000000000..c0f5ce83d --- /dev/null +++ b/packages/core/scripts/build.js @@ -0,0 +1,52 @@ +/* eslint-disable */ +const fs = require('fs') +const esbuild = require('esbuild') + +const name = process.env.npm_package_name || '' + +async function main() { + if (!fs.existsSync('./dist')) { + fs.mkdirSync('./dist') + } + + try { + esbuild.buildSync({ + entryPoints: ['./src/index.ts'], + outdir: 'dist/cjs', + minify: true, + bundle: true, + format: 'cjs', + target: 'es6', + jsxFactory: 'React.createElement', + jsxFragment: 'React.Fragment', + tsconfig: './tsconfig.build.json', + external: ['react', 'react-dom'], + }) + + esbuild.buildSync({ + entryPoints: ['./src/index.ts'], + outdir: 'dist/esm', + minify: true, + bundle: true, + format: 'esm', + target: 'es6', + tsconfig: './tsconfig.build.json', + jsxFactory: 'React.createElement', + jsxFragment: 'React.Fragment', + external: ['react', 'react-dom'], + }) + + for (const file of ['package.json', 'README.md']) { + fs.copyFile(file, `dist/${file}`, fs.constants.COPYFILE_EXCL, (err) => { + if (err) throw err + }) + } + + console.log(`✔ ${name}: Built package.`) + } catch (e) { + console.log(`× ${name}: Build failed due to an error.`) + console.log(e) + } +} + +main() diff --git a/packages/core/scripts/dev.js b/packages/core/scripts/dev.js new file mode 100644 index 000000000..050de844d --- /dev/null +++ b/packages/core/scripts/dev.js @@ -0,0 +1,31 @@ +/* eslint-disable */ +const esbuild = require('esbuild') + +const name = process.env.npm_package_name || '' + +async function main() { + esbuild.build({ + entryPoints: ['./src/index.ts'], + outdir: 'dist/cjs', + minify: false, + bundle: true, + format: 'cjs', + target: 'es6', + jsxFactory: 'React.createElement', + jsxFragment: 'React.Fragment', + tsconfig: './tsconfig.json', + external: ['react', 'react-dom'], + incremental: true, + watch: { + onRebuild(error) { + if (error) { + console.log(`× ${name}: An error in prevented the rebuild.`) + return + } + console.log(`✔ ${name}: Rebuilt.`) + }, + }, + }) +} + +main() diff --git a/packages/core/scripts/pre-dev.js b/packages/core/scripts/pre-dev.js new file mode 100644 index 000000000..4fa81af38 --- /dev/null +++ b/packages/core/scripts/pre-dev.js @@ -0,0 +1,34 @@ +/* eslint-disable */ +const fs = require('fs') +const esbuild = require('esbuild') + +async function main() { + if (fs.existsSync('./dist')) { + fs.rmSync('./dist', { recursive: true }, (e) => { + if (e) { + throw e + } + }) + } + + fs.mkdir('./dist', (e) => { + if (e) { + throw e + } + }) + + esbuild.build({ + entryPoints: ['./src/index.ts'], + outdir: 'dist/cjs', + minify: false, + bundle: true, + format: 'cjs', + target: 'es6', + jsxFactory: 'React.createElement', + jsxFragment: 'React.Fragment', + tsconfig: './tsconfig.json', + external: ['react', 'react-dom'], + }) +} + +main() diff --git a/packages/core/src/components/binding/binding.test.tsx b/packages/core/src/components/binding/binding.test.tsx new file mode 100644 index 000000000..fc05a217b --- /dev/null +++ b/packages/core/src/components/binding/binding.test.tsx @@ -0,0 +1,11 @@ +import * as React from 'react' +import { renderWithSvg } from '+test' +import { Binding } from './binding' + +jest.spyOn(console, 'error').mockImplementation(() => void null) + +describe('binding', () => { + test('mounts component without crashing', () => { + renderWithSvg() + }) +}) diff --git a/packages/core/src/components/binding/binding.tsx b/packages/core/src/components/binding/binding.tsx new file mode 100644 index 000000000..3d128fdfa --- /dev/null +++ b/packages/core/src/components/binding/binding.tsx @@ -0,0 +1,16 @@ +import * as React from 'react' +import type { TLBinding } from '+types' + +interface BindingProps { + point: number[] + type: TLBinding['type'] +} + +export function Binding({ point: [x, y], type }: BindingProps): JSX.Element { + return ( + + {type === 'center' && } + {type !== 'pin' && } + + ) +} diff --git a/packages/core/src/components/binding/index.ts b/packages/core/src/components/binding/index.ts new file mode 100644 index 000000000..c29c543cd --- /dev/null +++ b/packages/core/src/components/binding/index.ts @@ -0,0 +1 @@ +export * from './binding' diff --git a/packages/core/src/components/bounds/bounds-bg.tsx b/packages/core/src/components/bounds/bounds-bg.tsx new file mode 100644 index 000000000..39f195bb1 --- /dev/null +++ b/packages/core/src/components/bounds/bounds-bg.tsx @@ -0,0 +1,30 @@ +import * as React from 'react' +import type { TLBounds } from '+types' +import { Utils } from '+utils' +import { useBoundsEvents } from '+hooks' + +interface BoundsBgProps { + bounds: TLBounds + rotation: number +} + +export function BoundsBg({ bounds, rotation }: BoundsBgProps): JSX.Element { + const events = useBoundsEvents() + + const { width, height } = bounds + + const center = Utils.getBoundsCenter(bounds) + + return ( + + ) +} diff --git a/packages/core/src/components/bounds/bounds.test.tsx b/packages/core/src/components/bounds/bounds.test.tsx new file mode 100644 index 000000000..8bcc03391 --- /dev/null +++ b/packages/core/src/components/bounds/bounds.test.tsx @@ -0,0 +1,16 @@ +import * as React from 'react' +import { renderWithSvg } from '+test' +import { Bounds } from './bounds' + +describe('bounds', () => { + test('mounts component without crashing', () => { + renderWithSvg( + + ) + }) +}) diff --git a/packages/core/src/components/bounds/bounds.tsx b/packages/core/src/components/bounds/bounds.tsx new file mode 100644 index 000000000..c6f914495 --- /dev/null +++ b/packages/core/src/components/bounds/bounds.tsx @@ -0,0 +1,44 @@ +import * as React from 'react' +import { TLBoundsEdge, TLBoundsCorner, TLBounds } from '+types' +import { Utils } from '+utils' +import { CenterHandle } from './center-handle' +import { RotateHandle } from './rotate-handle' +import { CornerHandle } from './corner-handle' +import { EdgeHandle } from './edge-handle' + +interface BoundsProps { + zoom: number + bounds: TLBounds + rotation: number + isLocked: boolean +} + +export function Bounds({ zoom, bounds, rotation, isLocked }: BoundsProps): JSX.Element { + const size = (Utils.isMobileSize() ? 10 : 8) / zoom // Touch target size + const center = Utils.getBoundsCenter(bounds) + + return ( + + + {!isLocked && ( + <> + + + + + + + + + + + )} + + ) +} diff --git a/packages/core/src/components/bounds/center-handle.tsx b/packages/core/src/components/bounds/center-handle.tsx new file mode 100644 index 000000000..46602fcc7 --- /dev/null +++ b/packages/core/src/components/bounds/center-handle.tsx @@ -0,0 +1,20 @@ +import * as React from 'react' +import type { TLBounds } from '+types' + +export interface CenterHandleProps { + bounds: TLBounds + isLocked: boolean +} + +export const CenterHandle = React.memo(({ bounds, isLocked }: CenterHandleProps): JSX.Element => { + return ( + + ) +}) diff --git a/packages/core/src/components/bounds/corner-handle.tsx b/packages/core/src/components/bounds/corner-handle.tsx new file mode 100644 index 000000000..6d35c9265 --- /dev/null +++ b/packages/core/src/components/bounds/corner-handle.tsx @@ -0,0 +1,49 @@ +import * as React from 'react' +import { useBoundsHandleEvents } from '+hooks' +import { TLBoundsCorner, TLBounds } from '+types' + +const cornerBgClassnames = { + [TLBoundsCorner.TopLeft]: 'tl-transparent tl-cursor-nwse', + [TLBoundsCorner.TopRight]: 'tl-transparent tl-cursor-nesw', + [TLBoundsCorner.BottomRight]: 'tl-transparent tl-cursor-nwse', + [TLBoundsCorner.BottomLeft]: 'tl-transparent tl-cursor-nesw', +} + +export const CornerHandle = React.memo( + ({ + size, + corner, + bounds, + }: { + size: number + bounds: TLBounds + corner: TLBoundsCorner + }): JSX.Element => { + const events = useBoundsHandleEvents(corner) + + const isTop = corner === TLBoundsCorner.TopLeft || corner === TLBoundsCorner.TopRight + const isLeft = corner === TLBoundsCorner.TopLeft || corner === TLBoundsCorner.BottomLeft + + return ( + + + + + ) + } +) diff --git a/packages/core/src/components/bounds/edge-handle.tsx b/packages/core/src/components/bounds/edge-handle.tsx new file mode 100644 index 000000000..175557b80 --- /dev/null +++ b/packages/core/src/components/bounds/edge-handle.tsx @@ -0,0 +1,32 @@ +import * as React from 'react' +import { useBoundsHandleEvents } from '+hooks' +import { TLBoundsEdge, TLBounds } from '+types' + +const edgeClassnames = { + [TLBoundsEdge.Top]: 'tl-transparent tl-cursor-ns', + [TLBoundsEdge.Right]: 'tl-transparent tl-cursor-ew', + [TLBoundsEdge.Bottom]: 'tl-transparent tl-cursor-ns', + [TLBoundsEdge.Left]: 'tl-transparent tl-cursor-ew', +} + +export const EdgeHandle = React.memo( + ({ size, bounds, edge }: { size: number; bounds: TLBounds; edge: TLBoundsEdge }): JSX.Element => { + const events = useBoundsHandleEvents(edge) + + const isHorizontal = edge === TLBoundsEdge.Top || edge === TLBoundsEdge.Bottom + const isFarEdge = edge === TLBoundsEdge.Right || edge === TLBoundsEdge.Bottom + + const { height, width } = bounds + + return ( + + ) + } +) diff --git a/packages/core/src/components/bounds/index.ts b/packages/core/src/components/bounds/index.ts new file mode 100644 index 000000000..3f5e39ea0 --- /dev/null +++ b/packages/core/src/components/bounds/index.ts @@ -0,0 +1 @@ +export * from './bounds' diff --git a/packages/core/src/components/bounds/rotate-handle.tsx b/packages/core/src/components/bounds/rotate-handle.tsx new file mode 100644 index 000000000..42abe2a5e --- /dev/null +++ b/packages/core/src/components/bounds/rotate-handle.tsx @@ -0,0 +1,30 @@ +import * as React from 'react' +import { useBoundsHandleEvents } from '+hooks' +import type { TLBounds } from '+types' + +export const RotateHandle = React.memo( + ({ bounds, size }: { bounds: TLBounds; size: number }): JSX.Element => { + const events = useBoundsHandleEvents('rotate') + + return ( + + + + + ) + } +) diff --git a/packages/core/src/components/brush/BrushUpdater.ts b/packages/core/src/components/brush/BrushUpdater.ts new file mode 100644 index 000000000..24982ccc5 --- /dev/null +++ b/packages/core/src/components/brush/BrushUpdater.ts @@ -0,0 +1,34 @@ +import * as React from 'react' +import type { TLBounds } from '+types' + +export class BrushUpdater { + ref = React.createRef() + + isControlled = false + + set(bounds?: TLBounds) { + if (!this.isControlled) this.isControlled = true + + if (!bounds) { + this.clear() + return + } + + const elm = this.ref?.current + if (!elm) return + + elm.setAttribute('opacity', '1') + elm.setAttribute('x', bounds.minX.toString()) + elm.setAttribute('y', bounds.minY.toString()) + elm.setAttribute('width', bounds.width.toString()) + elm.setAttribute('height', bounds.height.toString()) + } + + clear() { + const elm = this.ref?.current + if (!elm) return + elm.setAttribute('opacity', '0') + elm.setAttribute('width', '0') + elm.setAttribute('height', '0') + } +} diff --git a/packages/core/src/components/brush/brush.test.tsx b/packages/core/src/components/brush/brush.test.tsx new file mode 100644 index 000000000..de0f3c7e2 --- /dev/null +++ b/packages/core/src/components/brush/brush.test.tsx @@ -0,0 +1,9 @@ +import * as React from 'react' +import { renderWithSvg } from '+test' +import { Brush } from './brush' + +describe('brush', () => { + test('mounts component without crashing', () => { + renderWithSvg() + }) +}) diff --git a/packages/core/src/components/brush/brush.tsx b/packages/core/src/components/brush/brush.tsx new file mode 100644 index 000000000..a8ba11b34 --- /dev/null +++ b/packages/core/src/components/brush/brush.tsx @@ -0,0 +1,8 @@ +import * as React from 'react' +import { BrushUpdater } from './BrushUpdater' + +export const brushUpdater = new BrushUpdater() + +export const Brush = React.memo((): JSX.Element | null => { + return +}) diff --git a/packages/core/src/components/brush/index.ts b/packages/core/src/components/brush/index.ts new file mode 100644 index 000000000..6931dc407 --- /dev/null +++ b/packages/core/src/components/brush/index.ts @@ -0,0 +1,2 @@ +export * from './brush' +export * from './BrushUpdater' diff --git a/packages/core/src/components/canvas/canvas.test.tsx b/packages/core/src/components/canvas/canvas.test.tsx new file mode 100644 index 000000000..836c9db1f --- /dev/null +++ b/packages/core/src/components/canvas/canvas.test.tsx @@ -0,0 +1,17 @@ +import * as React from 'react' +import { mockDocument, renderWithContext } from '+test' +import { Canvas } from './canvas' + +describe('page', () => { + test('mounts component without crashing', () => { + renderWithContext( + + ) + }) +}) diff --git a/packages/core/src/components/canvas/canvas.tsx b/packages/core/src/components/canvas/canvas.tsx new file mode 100644 index 000000000..39f1070b1 --- /dev/null +++ b/packages/core/src/components/canvas/canvas.tsx @@ -0,0 +1,69 @@ +import * as React from 'react' +import { + usePreventNavigation, + useZoomEvents, + useSafariFocusOutFix, + useCanvasEvents, + useCameraCss, +} from '+hooks' +import type { TLBinding, TLPage, TLPageState, TLShape } from '+types' +import { ErrorFallback } from '+components/error-fallback' +import { ErrorBoundary } from '+components/error-boundary' +import { Brush } from '+components/brush' +import { Defs } from '+components/defs' +import { Page } from '+components/page' + +function resetError() { + void null +} + +interface CanvasProps { + page: TLPage + pageState: TLPageState + hideBounds?: boolean + hideHandles?: boolean + hideIndicators?: boolean + meta?: Record +} + +export const Canvas = React.memo(function Canvas({ + page, + pageState, + meta, + hideHandles = false, + hideBounds = false, + hideIndicators = false, +}: CanvasProps): JSX.Element { + const rCanvas = React.useRef(null) + + const rGroup = useCameraCss(pageState) + + useZoomEvents() + + useSafariFocusOutFix() + + usePreventNavigation(rCanvas) + + const events = useCanvasEvents() + + return ( +
+ + + + + + + + + +
+ ) +}) diff --git a/packages/core/src/components/canvas/index.ts b/packages/core/src/components/canvas/index.ts new file mode 100644 index 000000000..ac905c9b3 --- /dev/null +++ b/packages/core/src/components/canvas/index.ts @@ -0,0 +1 @@ +export * from './canvas' diff --git a/packages/core/src/components/defs/defs.test.tsx b/packages/core/src/components/defs/defs.test.tsx new file mode 100644 index 000000000..b88ccdebb --- /dev/null +++ b/packages/core/src/components/defs/defs.test.tsx @@ -0,0 +1,9 @@ +import * as React from 'react' +import { renderWithSvg } from '+test' +import { Defs } from './defs' + +describe('defs', () => { + test('mounts component without crashing', () => { + renderWithSvg() + }) +}) diff --git a/packages/core/src/components/defs/defs.tsx b/packages/core/src/components/defs/defs.tsx new file mode 100644 index 000000000..fdcb6ff1f --- /dev/null +++ b/packages/core/src/components/defs/defs.tsx @@ -0,0 +1,22 @@ +import * as React from 'react' + +interface DefProps { + zoom: number +} + +export function Defs({ zoom }: DefProps): JSX.Element { + return ( + + + + + + + + + + + + + ) +} diff --git a/packages/core/src/components/defs/index.ts b/packages/core/src/components/defs/index.ts new file mode 100644 index 000000000..10e5cb1da --- /dev/null +++ b/packages/core/src/components/defs/index.ts @@ -0,0 +1 @@ +export * from './defs' diff --git a/packages/core/src/components/error-boundary/error-boundary.tsx b/packages/core/src/components/error-boundary/error-boundary.tsx new file mode 100644 index 000000000..5079dde8e --- /dev/null +++ b/packages/core/src/components/error-boundary/error-boundary.tsx @@ -0,0 +1,155 @@ +import * as React from 'react' + +// Copied from https://github.com/bvaughn/react-error-boundary/blob/master/src/index.tsx +// (There's an issue with esm builds of this library, so we can't use it directly.) +const changedArray = (a: Array = [], b: Array = []) => + a.length !== b.length || a.some((item, index) => !Object.is(item, b[index])) + +interface FallbackProps { + error: Error + resetErrorBoundary: (...args: Array) => void +} + +interface ErrorBoundaryPropsWithComponent { + onResetKeysChange?: ( + prevResetKeys: Array | undefined, + resetKeys: Array | undefined + ) => void + onReset?: (...args: Array) => void + onError?: (error: Error, info: { componentStack: string }) => void + resetKeys?: Array + fallback?: never + FallbackComponent: React.ComponentType + fallbackRender?: never +} + +declare function FallbackRender( + props: FallbackProps +): React.ReactElement | null + +interface ErrorBoundaryPropsWithRender { + onResetKeysChange?: ( + prevResetKeys: Array | undefined, + resetKeys: Array | undefined + ) => void + onReset?: (...args: Array) => void + onError?: (error: Error, info: { componentStack: string }) => void + resetKeys?: Array + fallback?: never + FallbackComponent?: never + fallbackRender: typeof FallbackRender +} + +interface ErrorBoundaryPropsWithFallback { + onResetKeysChange?: ( + prevResetKeys: Array | undefined, + resetKeys: Array | undefined + ) => void + onReset?: (...args: Array) => void + onError?: (error: Error, info: { componentStack: string }) => void + resetKeys?: Array + fallback: React.ReactElement< + unknown, + string | React.FunctionComponent | typeof React.Component + > | null + FallbackComponent?: never + fallbackRender?: never +} + +type ErrorBoundaryProps = + | ErrorBoundaryPropsWithFallback + | ErrorBoundaryPropsWithComponent + | ErrorBoundaryPropsWithRender + +type ErrorBoundaryState = { error: Error | null } + +const initialState: ErrorBoundaryState = { error: null } + +class ErrorBoundary extends React.Component< + React.PropsWithRef>, + ErrorBoundaryState +> { + static getDerivedStateFromError(error: Error) { + return { error } + } + + state = initialState + updatedWithError = false + resetErrorBoundary = (...args: Array) => { + this.props.onReset?.(...args) + this.reset() + } + + reset() { + this.updatedWithError = false + this.setState(initialState) + } + + componentDidCatch(error: Error, info: React.ErrorInfo) { + this.props.onError?.(error, info) + } + + componentDidMount() { + const { error } = this.state + + if (error !== null) { + this.updatedWithError = true + } + } + + componentDidUpdate(prevProps: ErrorBoundaryProps) { + const { error } = this.state + const { resetKeys } = this.props + + // There's an edge case where if the thing that triggered the error + // happens to *also* be in the resetKeys array, we'd end up resetting + // the error boundary immediately. This would likely trigger a second + // error to be thrown. + // So we make sure that we don't check the resetKeys on the first call + // of cDU after the error is set + if (error !== null && !this.updatedWithError) { + this.updatedWithError = true + return + } + + if (error !== null && changedArray(prevProps.resetKeys, resetKeys)) { + this.props.onResetKeysChange?.(prevProps.resetKeys, resetKeys) + this.reset() + } + } + + render() { + const { error } = this.state + + const { fallbackRender, FallbackComponent, fallback } = this.props + + if (error !== null) { + const props = { + error, + resetErrorBoundary: this.resetErrorBoundary, + } + if (React.isValidElement(fallback)) { + return fallback + } else if (typeof fallbackRender === 'function') { + return fallbackRender(props) + } else if (FallbackComponent) { + return + } else { + throw new Error( + 'react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop' + ) + } + } + + return this.props.children + } +} + +export { ErrorBoundary } +export type { + FallbackProps, + ErrorBoundaryPropsWithComponent, + ErrorBoundaryPropsWithRender, + ErrorBoundaryPropsWithFallback, + ErrorBoundaryProps, +} diff --git a/packages/core/src/components/error-boundary/index.ts b/packages/core/src/components/error-boundary/index.ts new file mode 100644 index 000000000..8b96c0703 --- /dev/null +++ b/packages/core/src/components/error-boundary/index.ts @@ -0,0 +1 @@ +export * from './error-boundary' diff --git a/packages/core/src/components/error-fallback/error-fallback.test.tsx b/packages/core/src/components/error-fallback/error-fallback.test.tsx new file mode 100644 index 000000000..be41db4f4 --- /dev/null +++ b/packages/core/src/components/error-fallback/error-fallback.test.tsx @@ -0,0 +1,9 @@ +import * as React from 'react' +import { renderWithContext } from '+test' +import { ErrorFallback } from './error-fallback' + +describe('error fallback', () => { + test('mounts component without crashing', () => { + renderWithContext( void null} />) + }) +}) diff --git a/packages/core/src/components/error-fallback/error-fallback.tsx b/packages/core/src/components/error-fallback/error-fallback.tsx new file mode 100644 index 000000000..bbf72ae52 --- /dev/null +++ b/packages/core/src/components/error-fallback/error-fallback.tsx @@ -0,0 +1,17 @@ +import * as React from 'react' +import { useTLContext } from '+hooks' + +interface ErrorFallbackProps { + error: Error + resetErrorBoundary: () => void +} + +export const ErrorFallback = React.memo(({ error, resetErrorBoundary }: ErrorFallbackProps) => { + const { callbacks } = useTLContext() + + React.useEffect(() => { + callbacks.onError?.(error) + }, [error, resetErrorBoundary, callbacks]) + + return null +}) diff --git a/packages/core/src/components/error-fallback/index.ts b/packages/core/src/components/error-fallback/index.ts new file mode 100644 index 000000000..d8cfbf889 --- /dev/null +++ b/packages/core/src/components/error-fallback/index.ts @@ -0,0 +1 @@ +export * from './error-fallback' diff --git a/packages/core/src/components/handles/handle.tsx b/packages/core/src/components/handles/handle.tsx new file mode 100644 index 000000000..ef7c598a4 --- /dev/null +++ b/packages/core/src/components/handles/handle.tsx @@ -0,0 +1,24 @@ +import * as React from 'react' +import { useHandleEvents } from '+hooks' + +interface HandleProps { + id: string + point: number[] + zoom: number +} + +export const Handle = React.memo(({ id, point, zoom }: HandleProps) => { + const events = useHandleEvents(id) + + return ( + + + + + ) +}) diff --git a/packages/core/src/components/handles/handles.test.tsx b/packages/core/src/components/handles/handles.test.tsx new file mode 100644 index 000000000..5be665bf8 --- /dev/null +++ b/packages/core/src/components/handles/handles.test.tsx @@ -0,0 +1,9 @@ +import * as React from 'react' +import { mockUtils, renderWithContext } from '+test' +import { Handles } from './handles' + +describe('handles', () => { + test('mounts component without crashing', () => { + renderWithContext() + }) +}) diff --git a/packages/core/src/components/handles/handles.tsx b/packages/core/src/components/handles/handles.tsx new file mode 100644 index 000000000..8d9cd1116 --- /dev/null +++ b/packages/core/src/components/handles/handles.tsx @@ -0,0 +1,35 @@ +import * as React from 'react' +import { Vec } from '+utils' +import type { TLShape } from '+types' +import { useTLContext } from '+hooks' +import { Handle } from './handle' + +interface HandlesProps { + shape: TLShape + zoom: number +} + +const toAngle = 180 / Math.PI + +export const Handles = React.memo(({ shape, zoom }: HandlesProps): JSX.Element | null => { + const { shapeUtils } = useTLContext() + + const center = shapeUtils[shape.type].getCenter(shape) + + if (shape.handles === undefined) { + return null + } + + return ( + + {Object.values(shape.handles).map((handle) => ( + + ))} + + ) +}) diff --git a/packages/core/src/components/handles/index.ts b/packages/core/src/components/handles/index.ts new file mode 100644 index 000000000..43453ba8c --- /dev/null +++ b/packages/core/src/components/handles/index.ts @@ -0,0 +1 @@ +export * from './handles' diff --git a/packages/core/src/components/index.tsx b/packages/core/src/components/index.tsx new file mode 100644 index 000000000..d56c8b760 --- /dev/null +++ b/packages/core/src/components/index.tsx @@ -0,0 +1,2 @@ +export * from './renderer' +export { brushUpdater } from './brush' diff --git a/packages/core/src/components/page/index.ts b/packages/core/src/components/page/index.ts new file mode 100644 index 000000000..feed53c7e --- /dev/null +++ b/packages/core/src/components/page/index.ts @@ -0,0 +1 @@ +export * from './page' diff --git a/packages/core/src/components/page/page.test.tsx b/packages/core/src/components/page/page.test.tsx new file mode 100644 index 000000000..a380d5437 --- /dev/null +++ b/packages/core/src/components/page/page.test.tsx @@ -0,0 +1,17 @@ +import * as React from 'react' +import { mockDocument, renderWithContext } from '+test' +import { Page } from './page' + +describe('page', () => { + test('mounts component without crashing', () => { + renderWithContext( + + ) + }) +}) diff --git a/packages/core/src/components/page/page.tsx b/packages/core/src/components/page/page.tsx new file mode 100644 index 000000000..732afc802 --- /dev/null +++ b/packages/core/src/components/page/page.tsx @@ -0,0 +1,76 @@ +import * as React from 'react' +import type { TLBinding, TLPage, TLPageState, TLShape } from '+types' +import { useSelection, useShapeTree, useHandles, useRenderOnResize, useTLContext } from '+hooks' +import { Bounds } from '+components/bounds' +import { BoundsBg } from '+components/bounds/bounds-bg' +import { Handles } from '+components/handles' +import { ShapeNode } from '+components/shape' +import { ShapeIndicator } from '+components/shape-indicator' + +interface PageProps { + page: TLPage + pageState: TLPageState + hideBounds: boolean + hideHandles: boolean + hideIndicators: boolean + meta?: Record +} + +/** + * The Page component renders the current page. + * + * ### Example + * + *```ts + * example + *``` */ +export function Page({ + page, + pageState, + hideBounds, + hideHandles, + hideIndicators, + meta, +}: PageProps): JSX.Element { + const { callbacks, shapeUtils } = useTLContext() + + useRenderOnResize() + + const shapeTree = useShapeTree(page, pageState, shapeUtils, meta, callbacks.onChange) + + const { shapeWithHandles } = useHandles(page, pageState) + + const { bounds, isLocked, rotation } = useSelection(page, pageState, shapeUtils) + + const { + selectedIds, + hoveredId, + camera: { zoom }, + } = pageState + + return ( + <> + {bounds && !hideBounds && } + {shapeTree.map((node) => ( + + ))} + {bounds && !hideBounds && ( + + )} + {!hideIndicators && + selectedIds + .filter(Boolean) + .map((id) => ( + + ))} + {!hideIndicators && hoveredId && ( + + )} + {!hideHandles && shapeWithHandles && } + + ) +} diff --git a/packages/core/src/components/renderer/index.tsx b/packages/core/src/components/renderer/index.tsx new file mode 100644 index 000000000..02d59c968 --- /dev/null +++ b/packages/core/src/components/renderer/index.tsx @@ -0,0 +1 @@ +export * from './renderer' diff --git a/packages/core/src/components/renderer/renderer.test.tsx b/packages/core/src/components/renderer/renderer.test.tsx new file mode 100644 index 000000000..4e3eec61f --- /dev/null +++ b/packages/core/src/components/renderer/renderer.test.tsx @@ -0,0 +1,16 @@ +import * as React from 'react' +import { mockDocument, mockUtils } from '+test' +import { render } from '@testing-library/react' +import { Renderer } from './renderer' + +describe('renderer', () => { + test('mounts component without crashing', () => { + render( + + ) + }) +}) diff --git a/packages/core/src/components/renderer/renderer.tsx b/packages/core/src/components/renderer/renderer.tsx new file mode 100644 index 000000000..f26092dbb --- /dev/null +++ b/packages/core/src/components/renderer/renderer.tsx @@ -0,0 +1,104 @@ +import * as React from 'react' +import type { + TLShape, + TLPage, + TLPageState, + TLCallbacks, + TLShapeUtils, + TLTheme, + TLBounds, + TLBinding, +} from '../../types' +import { Canvas } from '../canvas' +import { useTLTheme, TLContext } from '../../hooks' + +export interface RendererProps> + extends Partial { + /** + * An object containing instances of your shape classes. + */ + shapeUtils: TLShapeUtils + /** + * The current page, containing shapes and bindings. + */ + page: TLPage + /** + * The current page state. + */ + pageState: TLPageState + /** + * An object of custom theme colors. + */ + theme?: Partial + /** + * When true, the renderer will not show the bounds for selected objects. + */ + hideBounds?: boolean + /** + * When true, the renderer will not show the handles of shapes with handles. + */ + hideHandles?: boolean + /** + * When true, the renderer will not show indicators for selected or + * hovered objects, + */ + hideIndicators?: boolean + /** + * When true, the renderer will ignore all inputs that were not made + * by a stylus or pen-type device. + */ + isPenMode?: boolean + /** + * An object of custom options that should be passed to rendered shapes. + */ + meta?: M +} + +/** + * The Renderer component is the main component of the library. It + * accepts the current `page`, the `shapeUtils` needed to interpret + * and render the shapes and bindings on the `page`, and the current + * `pageState`. + * @param props + * @returns + */ +export function Renderer>({ + shapeUtils, + page, + pageState, + theme, + meta, + hideHandles = false, + hideIndicators = false, + hideBounds = false, + ...rest +}: RendererProps): JSX.Element { + useTLTheme(theme) + + const rScreenBounds = React.useRef(null) + const rPageState = React.useRef(pageState) + + React.useEffect(() => { + rPageState.current = pageState + }, [pageState]) + + const [context] = React.useState(() => ({ + callbacks: rest, + shapeUtils, + rScreenBounds, + rPageState, + })) + + return ( + + + + ) +} diff --git a/packages/core/src/components/shape-indicator/index.ts b/packages/core/src/components/shape-indicator/index.ts new file mode 100644 index 000000000..a47ed95e9 --- /dev/null +++ b/packages/core/src/components/shape-indicator/index.ts @@ -0,0 +1 @@ +export * from './shape-indicator' diff --git a/packages/core/src/components/shape-indicator/shape-indicator.test.tsx b/packages/core/src/components/shape-indicator/shape-indicator.test.tsx new file mode 100644 index 000000000..4773bb229 --- /dev/null +++ b/packages/core/src/components/shape-indicator/shape-indicator.test.tsx @@ -0,0 +1,9 @@ +import * as React from 'react' +import { mockUtils, renderWithSvg } from '+test' +import { ShapeIndicator } from './shape-indicator' + +describe('shape indicator', () => { + test('mounts component without crashing', () => { + renderWithSvg() + }) +}) diff --git a/packages/core/src/components/shape-indicator/shape-indicator.tsx b/packages/core/src/components/shape-indicator/shape-indicator.tsx new file mode 100644 index 000000000..9f5501de4 --- /dev/null +++ b/packages/core/src/components/shape-indicator/shape-indicator.tsx @@ -0,0 +1,20 @@ +import * as React from 'react' +import type { TLShape } from '+types' +import { useTLContext } from '+hooks' + +export const ShapeIndicator = React.memo( + ({ shape, variant }: { shape: TLShape; variant: 'selected' | 'hovered' }) => { + const { shapeUtils } = useTLContext() + const utils = shapeUtils[shape.type] + + const center = utils.getCenter(shape) + const rotation = (shape.rotation || 0) * (180 / Math.PI) + const transform = `rotate(${rotation}, ${center}) translate(${shape.point})` + + return ( + + {shapeUtils[shape.type].renderIndicator(shape)} + + ) + } +) diff --git a/packages/core/src/components/shape/editing-text-shape.tsx b/packages/core/src/components/shape/editing-text-shape.tsx new file mode 100644 index 000000000..c8694f75b --- /dev/null +++ b/packages/core/src/components/shape/editing-text-shape.tsx @@ -0,0 +1,49 @@ +import { useTLContext } from '+hooks' +import * as React from 'react' +import type { TLShapeUtil, TLRenderInfo, TLShape } from '+types' + +interface EditingShapeProps extends TLRenderInfo { + shape: T + utils: TLShapeUtil +} + +export function EditingTextShape({ + shape, + utils, + isEditing, + isBinding, + isHovered, + isSelected, + isCurrentParent, + meta, +}: EditingShapeProps) { + const { + callbacks: { onTextChange, onTextBlur, onTextFocus, onTextKeyDown, onTextKeyUp }, + } = useTLContext() + + const ref = React.useRef(null) + + React.useEffect(() => { + // Firefox fix? + setTimeout(() => { + if (document.activeElement !== ref.current) { + ref.current?.focus() + } + }, 0) + }, [shape.id]) + + return utils.render(shape, { + ref, + isEditing, + isHovered, + isSelected, + isCurrentParent, + isBinding, + onTextChange, + onTextBlur, + onTextFocus, + onTextKeyDown, + onTextKeyUp, + meta, + }) +} diff --git a/packages/core/src/components/shape/index.ts b/packages/core/src/components/shape/index.ts new file mode 100644 index 000000000..f6b6111bd --- /dev/null +++ b/packages/core/src/components/shape/index.ts @@ -0,0 +1 @@ +export * from './shape-node' diff --git a/packages/core/src/components/shape/rendered-shape.tsx b/packages/core/src/components/shape/rendered-shape.tsx new file mode 100644 index 000000000..5c88b6dda --- /dev/null +++ b/packages/core/src/components/shape/rendered-shape.tsx @@ -0,0 +1,50 @@ +import * as React from 'react' +import type { TLShapeUtil, TLRenderInfo, TLShape } from '+types' + +interface RenderedShapeProps extends TLRenderInfo { + shape: T + utils: TLShapeUtil +} + +export const RenderedShape = React.memo( + function RenderedShape({ + shape, + utils, + isEditing, + isBinding, + isHovered, + isSelected, + isCurrentParent, + meta, + }: RenderedShapeProps) { + return utils.render(shape, { + isEditing, + isBinding, + isHovered, + isSelected, + isCurrentParent, + meta, + }) + }, + (prev, next) => { + // If these have changed, then definitely render + if ( + prev.isHovered !== next.isHovered || + prev.isSelected !== next.isSelected || + prev.isEditing !== next.isEditing || + prev.isBinding !== next.isBinding || + prev.meta !== next.meta || + prev.isCurrentParent !== next.isCurrentParent + ) { + return false + } + + // If not, and if the shape has changed, ask the shape's class + // whether it should render + if (next.shape !== prev.shape) { + return !next.utils.shouldRender(next.shape, prev.shape) + } + + return true + } +) diff --git a/packages/core/src/components/shape/shape-node.tsx b/packages/core/src/components/shape/shape-node.tsx new file mode 100644 index 000000000..d70a813da --- /dev/null +++ b/packages/core/src/components/shape/shape-node.tsx @@ -0,0 +1,32 @@ +import * as React from 'react' +import type { IShapeTreeNode } from '+types' +import { Shape } from './shape' + +export const ShapeNode = React.memo( + >({ + shape, + children, + isEditing, + isBinding, + isHovered, + isSelected, + isCurrentParent, + meta, + }: IShapeTreeNode) => { + return ( + <> + + {children && + children.map((childNode) => )} + + ) + } +) diff --git a/packages/core/src/components/shape/shape.test.tsx b/packages/core/src/components/shape/shape.test.tsx new file mode 100644 index 000000000..a8c3462a9 --- /dev/null +++ b/packages/core/src/components/shape/shape.test.tsx @@ -0,0 +1,18 @@ +import * as React from 'react' +import { mockUtils, renderWithSvg } from '+test' +import { Shape } from './shape' + +describe('shape', () => { + test('mounts component without crashing', () => { + renderWithSvg( + + ) + }) +}) diff --git a/packages/core/src/components/shape/shape.tsx b/packages/core/src/components/shape/shape.tsx new file mode 100644 index 000000000..593bf90ed --- /dev/null +++ b/packages/core/src/components/shape/shape.tsx @@ -0,0 +1,58 @@ +import * as React from 'react' +import { useShapeEvents, useTLContext } from '+hooks' +import type { IShapeTreeNode } from '+types' +import { RenderedShape } from './rendered-shape' +import { EditingTextShape } from './editing-text-shape' + +export const Shape = React.memo( + >({ + shape, + isEditing, + isBinding, + isHovered, + isSelected, + isCurrentParent, + meta, + }: IShapeTreeNode) => { + const { shapeUtils } = useTLContext() + const events = useShapeEvents(shape.id, isCurrentParent) + const utils = shapeUtils[shape.type] + + const center = utils.getCenter(shape) + const rotation = (shape.rotation || 0) * (180 / Math.PI) + const transform = `rotate(${rotation}, ${center}) translate(${shape.point})` + + return ( + + {isEditing && utils.isEditableText ? ( + + ) : ( + + )} + + ) + } +) diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts new file mode 100644 index 000000000..52101db5c --- /dev/null +++ b/packages/core/src/hooks/index.ts @@ -0,0 +1,16 @@ +export * from './useTLContext' +export * from './useZoomEvents' +export * from './useSafariFocusOutFix' +export * from './useCanvasEvents' +export * from './useShapeEvents' +export * from './useShapeTree' +export * from './useStyle' +export * from './useCanvasEvents' +export * from './useBoundsHandleEvents' +export * from './useCameraCss' +export * from './useRenderOnResize' +export * from './useSelection' +export * from './useHandleEvents' +export * from './useHandles' +export * from './usePreventNavigation' +export * from './useBoundsEvents' diff --git a/packages/core/src/hooks/useBoundsEvents.tsx b/packages/core/src/hooks/useBoundsEvents.tsx new file mode 100644 index 000000000..17a14d0af --- /dev/null +++ b/packages/core/src/hooks/useBoundsEvents.tsx @@ -0,0 +1,86 @@ +import * as React from 'react' +import { inputs } from '+inputs' +import { useTLContext } from './useTLContext' + +export function useBoundsEvents() { + const { callbacks } = useTLContext() + + const onPointerDown = React.useCallback( + (e: React.PointerEvent) => { + if (e.button !== 0) return + e.stopPropagation() + e.currentTarget?.setPointerCapture(e.pointerId) + const info = inputs.pointerDown(e, 'bounds') + + callbacks.onPointBounds?.(info, e) + callbacks.onPointerDown?.(info, e) + }, + [callbacks] + ) + + const onPointerUp = React.useCallback( + (e: React.PointerEvent) => { + if (e.button !== 0) return + e.stopPropagation() + const isDoubleClick = inputs.isDoubleClick() + const info = inputs.pointerUp(e, 'bounds') + + if (e.currentTarget.hasPointerCapture(e.pointerId)) { + e.currentTarget?.releasePointerCapture(e.pointerId) + } + + if (isDoubleClick && !(info.altKey || info.metaKey)) { + callbacks.onDoubleClickBounds?.(info, e) + } + + callbacks.onReleaseBounds?.(info, e) + callbacks.onPointerUp?.(info, e) + }, + [callbacks] + ) + + const onPointerMove = React.useCallback( + (e: React.PointerEvent) => { + if (inputs.pointer && e.pointerId !== inputs.pointer.pointerId) return + + if (e.currentTarget.hasPointerCapture(e.pointerId)) { + callbacks.onDragBounds?.(inputs.pointerMove(e, 'bounds'), e) + } + const info = inputs.pointerMove(e, 'bounds') + callbacks.onPointerMove?.(info, e) + }, + [callbacks] + ) + + const onPointerEnter = React.useCallback( + (e: React.PointerEvent) => { + callbacks.onHoverBounds?.(inputs.pointerEnter(e, 'bounds'), e) + }, + [callbacks] + ) + + const onPointerLeave = React.useCallback( + (e: React.PointerEvent) => { + callbacks.onUnhoverBounds?.(inputs.pointerEnter(e, 'bounds'), e) + }, + [callbacks] + ) + + const onTouchStart = React.useCallback((e: React.TouchEvent) => { + e.preventDefault() + }, []) + + const onTouchEnd = React.useCallback((e: React.TouchEvent) => { + e.preventDefault() + }, []) + + return { + onPointerDown, + onPointerUp, + onPointerEnter, + onPointerMove, + onPointerLeave, + onTouchStart, + onTouchEnd, + } +} diff --git a/packages/core/src/hooks/useBoundsHandleEvents.tsx b/packages/core/src/hooks/useBoundsHandleEvents.tsx new file mode 100644 index 000000000..676511eb8 --- /dev/null +++ b/packages/core/src/hooks/useBoundsHandleEvents.tsx @@ -0,0 +1,85 @@ +import * as React from 'react' +import { inputs } from '+inputs' +import type { TLBoundsEdge, TLBoundsCorner } from '+types' +import { useTLContext } from './useTLContext' + +export function useBoundsHandleEvents(id: TLBoundsCorner | TLBoundsEdge | 'rotate') { + const { callbacks } = useTLContext() + + const onPointerDown = React.useCallback( + (e: React.PointerEvent) => { + if (e.button !== 0) return + e.stopPropagation() + e.currentTarget?.setPointerCapture(e.pointerId) + const info = inputs.pointerDown(e, id) + + callbacks.onPointBoundsHandle?.(info, e) + callbacks.onPointerDown?.(info, e) + }, + [callbacks, id] + ) + + const onPointerUp = React.useCallback( + (e: React.PointerEvent) => { + if (e.button !== 0) return + e.stopPropagation() + const isDoubleClick = inputs.isDoubleClick() + const info = inputs.pointerUp(e, id) + + if (e.currentTarget.hasPointerCapture(e.pointerId)) { + e.currentTarget?.releasePointerCapture(e.pointerId) + } + + if (isDoubleClick && !(info.altKey || info.metaKey)) { + callbacks.onDoubleClickBoundsHandle?.(info, e) + } + + callbacks.onReleaseBoundsHandle?.(info, e) + callbacks.onPointerUp?.(info, e) + }, + [callbacks, id] + ) + + const onPointerMove = React.useCallback( + (e: React.PointerEvent) => { + if (e.currentTarget.hasPointerCapture(e.pointerId)) { + callbacks.onDragBoundsHandle?.(inputs.pointerMove(e, id), e) + } + const info = inputs.pointerMove(e, id) + callbacks.onPointerMove?.(info, e) + }, + [callbacks, id] + ) + + const onPointerEnter = React.useCallback( + (e: React.PointerEvent) => { + callbacks.onHoverBoundsHandle?.(inputs.pointerEnter(e, id), e) + }, + [callbacks, id] + ) + + const onPointerLeave = React.useCallback( + (e: React.PointerEvent) => { + callbacks.onUnhoverBoundsHandle?.(inputs.pointerEnter(e, id), e) + }, + [callbacks, id] + ) + + const onTouchStart = React.useCallback((e: React.TouchEvent) => { + e.preventDefault() + }, []) + + const onTouchEnd = React.useCallback((e: React.TouchEvent) => { + e.preventDefault() + }, []) + + return { + onPointerDown, + onPointerUp, + onPointerEnter, + onPointerMove, + onPointerLeave, + onTouchStart, + onTouchEnd, + } +} diff --git a/packages/core/src/hooks/useCameraCss.tsx b/packages/core/src/hooks/useCameraCss.tsx new file mode 100644 index 000000000..55e00a4f8 --- /dev/null +++ b/packages/core/src/hooks/useCameraCss.tsx @@ -0,0 +1,22 @@ +import * as React from 'react' +import type { TLPageState } from '+types' + +export function useCameraCss(pageState: TLPageState) { + const rGroup = React.useRef(null) + + // Update the tl-zoom CSS variable when the zoom changes + React.useEffect(() => { + document.documentElement.style.setProperty('--tl-zoom', pageState.camera.zoom.toString()) + }, [pageState.camera.zoom]) + + // Update the group's position when the camera moves or zooms + React.useEffect(() => { + const { + zoom, + point: [x = 0, y = 0], + } = pageState.camera + rGroup.current?.setAttribute('transform', `scale(${zoom}) translate(${x} ${y})`) + }, [pageState.camera]) + + return rGroup +} diff --git a/packages/core/src/hooks/useCanvasEvents.tsx b/packages/core/src/hooks/useCanvasEvents.tsx new file mode 100644 index 000000000..b49c2ec0a --- /dev/null +++ b/packages/core/src/hooks/useCanvasEvents.tsx @@ -0,0 +1,58 @@ +import * as React from 'react' +import { useTLContext } from './useTLContext' +import { inputs } from '+inputs' + +export function useCanvasEvents() { + const { callbacks } = useTLContext() + + const onPointerDown = React.useCallback( + (e: React.PointerEvent) => { + if (e.button !== 0) return + e.currentTarget.setPointerCapture(e.pointerId) + + if (e.button === 0) { + const info = inputs.pointerDown(e, 'canvas') + callbacks.onPointCanvas?.(info, e) + callbacks.onPointerDown?.(info, e) + } + }, + [callbacks] + ) + + const onPointerMove = React.useCallback( + (e: React.PointerEvent) => { + if (e.currentTarget.hasPointerCapture(e.pointerId)) { + const info = inputs.pointerMove(e, 'canvas') + callbacks.onDragCanvas?.(info, e) + } + const info = inputs.pointerMove(e, 'canvas') + callbacks.onPointerMove?.(info, e) + }, + [callbacks] + ) + + const onPointerUp = React.useCallback( + (e: React.PointerEvent) => { + if (e.button !== 0) return + const isDoubleClick = inputs.isDoubleClick() + const info = inputs.pointerUp(e, 'canvas') + + if (e.currentTarget.hasPointerCapture(e.pointerId)) { + e.currentTarget?.releasePointerCapture(e.pointerId) + } + if (isDoubleClick && !(info.altKey || info.metaKey)) { + callbacks.onDoubleClickCanvas?.(info, e) + } + + callbacks.onReleaseCanvas?.(info, e) + callbacks.onPointerUp?.(info, e) + }, + [callbacks] + ) + + return { + onPointerDown, + onPointerMove, + onPointerUp, + } +} diff --git a/packages/core/src/hooks/useHandleEvents.tsx b/packages/core/src/hooks/useHandleEvents.tsx new file mode 100644 index 000000000..5b67cd754 --- /dev/null +++ b/packages/core/src/hooks/useHandleEvents.tsx @@ -0,0 +1,87 @@ +import * as React from 'react' +import { inputs } from '+inputs' +import { useTLContext } from './useTLContext' + +export function useHandleEvents(id: string) { + const { callbacks } = useTLContext() + + const onPointerDown = React.useCallback( + (e: React.PointerEvent) => { + if (e.button !== 0) return + e.stopPropagation() + e.currentTarget?.setPointerCapture(e.pointerId) + + const info = inputs.pointerDown(e, id) + callbacks.onPointHandle?.(info, e) + callbacks.onPointerDown?.(info, e) + }, + [callbacks, id] + ) + + const onPointerUp = React.useCallback( + (e: React.PointerEvent) => { + if (e.button !== 0) return + e.stopPropagation() + const isDoubleClick = inputs.isDoubleClick() + const info = inputs.pointerUp(e, id) + + if (e.currentTarget.hasPointerCapture(e.pointerId)) { + e.currentTarget?.releasePointerCapture(e.pointerId) + + if (isDoubleClick && !(info.altKey || info.metaKey)) { + callbacks.onDoubleClickHandle?.(info, e) + } + + callbacks.onReleaseHandle?.(info, e) + } + callbacks.onPointerUp?.(info, e) + }, + [callbacks] + ) + + const onPointerMove = React.useCallback( + (e: React.PointerEvent) => { + if (e.currentTarget.hasPointerCapture(e.pointerId)) { + const info = inputs.pointerMove(e, id) + callbacks.onDragHandle?.(info, e) + } + const info = inputs.pointerMove(e, id) + callbacks.onPointerMove?.(info, e) + }, + [callbacks, id] + ) + + const onPointerEnter = React.useCallback( + (e: React.PointerEvent) => { + const info = inputs.pointerEnter(e, id) + callbacks.onHoverHandle?.(info, e) + }, + [callbacks, id] + ) + + const onPointerLeave = React.useCallback( + (e: React.PointerEvent) => { + const info = inputs.pointerEnter(e, id) + callbacks.onUnhoverHandle?.(info, e) + }, + [callbacks, id] + ) + + const onTouchStart = React.useCallback((e: React.TouchEvent) => { + e.preventDefault() + }, []) + + const onTouchEnd = React.useCallback((e: React.TouchEvent) => { + e.preventDefault() + }, []) + + return { + onPointerDown, + onPointerUp, + onPointerEnter, + onPointerMove, + onPointerLeave, + onTouchStart, + onTouchEnd, + } +} diff --git a/packages/core/src/hooks/useHandles.ts b/packages/core/src/hooks/useHandles.ts new file mode 100644 index 000000000..482ea3cd7 --- /dev/null +++ b/packages/core/src/hooks/useHandles.ts @@ -0,0 +1,19 @@ +import type { TLBinding, TLPage, TLPageState, TLShape } from '+types' + +export function useHandles(page: TLPage, pageState: TLPageState) { + const { selectedIds } = pageState + + let shapeWithHandles: TLShape | undefined = undefined + + if (selectedIds.length === 1) { + const id = selectedIds[0] + + const shape = page.shapes[id] + + if (shape.handles !== undefined) { + shapeWithHandles = shape + } + } + + return { shapeWithHandles } +} diff --git a/packages/core/src/hooks/usePreventNavigation.tsx b/packages/core/src/hooks/usePreventNavigation.tsx new file mode 100644 index 000000000..c22311aff --- /dev/null +++ b/packages/core/src/hooks/usePreventNavigation.tsx @@ -0,0 +1,60 @@ +/* eslint-disable @typescript-eslint/ban-ts-comment */ +import * as React from 'react' + +export function usePreventNavigation(rCanvas: React.RefObject): void { + React.useEffect(() => { + const preventGestureNavigation = (event: TouchEvent) => { + event.preventDefault() + } + + const preventNavigation = (event: TouchEvent) => { + // Center point of the touch area + const touchXPosition = event.touches[0].pageX + // Size of the touch area + const touchXRadius = event.touches[0].radiusX || 0 + + // We set a threshold (10px) on both sizes of the screen, + // if the touch area overlaps with the screen edges + // it's likely to trigger the navigation. We prevent the + // touchstart event in that case. + if ( + touchXPosition - touchXRadius < 10 || + touchXPosition + touchXRadius > window.innerWidth - 10 + ) { + event.preventDefault() + } + } + + const elm = rCanvas.current + + if (!elm) return () => void null + + elm.addEventListener('touchstart', preventGestureNavigation) + + // @ts-ignore + elm.addEventListener('gestureend', preventGestureNavigation) + + // @ts-ignore + elm.addEventListener('gesturechange', preventGestureNavigation) + + // @ts-ignore + elm.addEventListener('gesturestart', preventGestureNavigation) + + // @ts-ignore + elm.addEventListener('touchstart', preventNavigation) + + return () => { + if (elm) { + elm.removeEventListener('touchstart', preventGestureNavigation) + // @ts-ignore + elm.removeEventListener('gestureend', preventGestureNavigation) + // @ts-ignore + elm.removeEventListener('gesturechange', preventGestureNavigation) + // @ts-ignore + elm.removeEventListener('gesturestart', preventGestureNavigation) + // @ts-ignore + elm.removeEventListener('touchstart', preventNavigation) + } + } + }, [rCanvas]) +} diff --git a/packages/core/src/hooks/useRenderOnResize.tsx b/packages/core/src/hooks/useRenderOnResize.tsx new file mode 100644 index 000000000..586971b7f --- /dev/null +++ b/packages/core/src/hooks/useRenderOnResize.tsx @@ -0,0 +1,14 @@ +import * as React from 'react' +import Utils from '+utils' + +export function useRenderOnResize() { + const forceUpdate = React.useReducer((x) => x + 1, 0)[1] + + React.useEffect(() => { + const debouncedUpdate = Utils.debounce(forceUpdate, 96) + window.addEventListener('resize', debouncedUpdate) + return () => { + window.removeEventListener('resize', debouncedUpdate) + } + }, [forceUpdate]) +} diff --git a/packages/core/src/hooks/useSafariFocusOutFix.tsx b/packages/core/src/hooks/useSafariFocusOutFix.tsx new file mode 100644 index 000000000..580f8f92b --- /dev/null +++ b/packages/core/src/hooks/useSafariFocusOutFix.tsx @@ -0,0 +1,22 @@ +import { useEffect } from 'react' +import Utils from '+utils' +import { useTLContext } from './useTLContext' + +// Send event on iOS when a user presses the "Done" key while editing a text element. + +export function useSafariFocusOutFix(): void { + const { callbacks } = useTLContext() + + useEffect(() => { + function handleFocusOut() { + callbacks.onBlurEditingShape?.() + } + + if (Utils.isMobileSafari()) { + document.addEventListener('focusout', handleFocusOut) + return () => document.removeEventListener('focusout', handleFocusOut) + } + + return () => null + }, [callbacks]) +} diff --git a/packages/core/src/hooks/useSelection.tsx b/packages/core/src/hooks/useSelection.tsx new file mode 100644 index 000000000..040ccd112 --- /dev/null +++ b/packages/core/src/hooks/useSelection.tsx @@ -0,0 +1,66 @@ +import type { TLPage, TLPageState, TLShape, TLBounds, TLShapeUtils, TLBinding } from '+types' +import Utils from '+utils' +import { useTLContext } from '+hooks' + +function canvasToScreen(point: number[], camera: TLPageState['camera']): number[] { + return [(point[0] + camera.point[0]) * camera.zoom, (point[1] + camera.point[1]) * camera.zoom] +} + +export function useSelection( + page: TLPage, + pageState: TLPageState, + shapeUtils: TLShapeUtils +) { + const { rScreenBounds } = useTLContext() + const { selectedIds } = pageState + + let bounds: TLBounds | undefined = undefined + let rotation = 0 + let isLocked = false + + if (selectedIds.length === 1) { + const id = selectedIds[0] + + const shape = page.shapes[id] + + rotation = shape.rotation || 0 + + isLocked = shape.isLocked || false + + bounds = shapeUtils[shape.type as T['type']].getBounds(shape) + } else if (selectedIds.length > 1) { + const selectedShapes = selectedIds.map((id) => page.shapes[id]) + + rotation = 0 + + isLocked = selectedShapes.every((shape) => shape.isLocked) + + bounds = selectedShapes.reduce((acc, shape, i) => { + if (i === 0) { + return shapeUtils[shape.type as T['type']].getRotatedBounds(shape) + } + return Utils.getExpandedBounds( + acc, + shapeUtils[shape.type as T['type']].getRotatedBounds(shape) + ) + }, {} as TLBounds) + } + + if (bounds) { + const [minX, minY] = canvasToScreen([bounds.minX, bounds.minY], pageState.camera) + const [maxX, maxY] = canvasToScreen([bounds.maxX, bounds.maxY], pageState.camera) + + rScreenBounds.current = { + minX, + minY, + maxX, + maxY, + width: maxX - minX, + height: maxY - minY, + } + } else { + rScreenBounds.current = null + } + + return { bounds, rotation, isLocked } +} diff --git a/packages/core/src/hooks/useShapeEvents.tsx b/packages/core/src/hooks/useShapeEvents.tsx new file mode 100644 index 000000000..3b6bb5f40 --- /dev/null +++ b/packages/core/src/hooks/useShapeEvents.tsx @@ -0,0 +1,118 @@ +import * as React from 'react' +import { inputs } from '+inputs' +import { useTLContext } from './useTLContext' +import { Utils } from '+utils' + +export function useShapeEvents(id: string, disable = false) { + const { rPageState, rScreenBounds, callbacks } = useTLContext() + + const onPointerDown = React.useCallback( + (e: React.PointerEvent) => { + if (disable) return + + if (e.button === 2) { + callbacks.onRightPointShape?.(inputs.pointerDown(e, id), e) + return + } + + if (e.button !== 0) return + + const info = inputs.pointerDown(e, id) + + e.stopPropagation() + e.currentTarget?.setPointerCapture(e.pointerId) + + // If we click "through" the selection bounding box to hit a shape that isn't selected, + // treat the event as a bounding box click. Unfortunately there's no way I know to pipe + // the event to the actual bounds background element. + if ( + rScreenBounds.current && + Utils.pointInBounds(info.point, rScreenBounds.current) && + !rPageState.current.selectedIds.includes(id) + ) { + callbacks.onPointBounds?.(inputs.pointerDown(e, 'bounds'), e) + callbacks.onPointShape?.(info, e) + return + } + + callbacks.onPointShape?.(info, e) + callbacks.onPointerDown?.(info, e) + }, + [callbacks, id, disable] + ) + + const onPointerUp = React.useCallback( + (e: React.PointerEvent) => { + if (e.button !== 0) return + if (disable) return + e.stopPropagation() + const isDoubleClick = inputs.isDoubleClick() + const info = inputs.pointerUp(e, id) + + if (e.currentTarget.hasPointerCapture(e.pointerId)) { + e.currentTarget?.releasePointerCapture(e.pointerId) + } + + if (isDoubleClick && !(info.altKey || info.metaKey)) { + callbacks.onDoubleClickShape?.(info, e) + } + + callbacks.onReleaseShape?.(info, e) + callbacks.onPointerUp?.(info, e) + }, + [callbacks, id, disable] + ) + + const onPointerMove = React.useCallback( + (e: React.PointerEvent) => { + if (disable) return + + if (inputs.pointer && e.pointerId !== inputs.pointer.pointerId) return + + const info = inputs.pointerMove(e, id) + + if (e.currentTarget.hasPointerCapture(e.pointerId)) { + callbacks.onDragShape?.(info, e) + } + + callbacks.onPointerMove?.(info, e) + }, + [callbacks, id, disable] + ) + + const onPointerEnter = React.useCallback( + (e: React.PointerEvent) => { + if (disable) return + const info = inputs.pointerEnter(e, id) + callbacks.onHoverShape?.(info, e) + }, + [callbacks, id, disable] + ) + + const onPointerLeave = React.useCallback( + (e: React.PointerEvent) => { + if (disable) return + const info = inputs.pointerEnter(e, id) + callbacks.onUnhoverShape?.(info, e) + }, + [callbacks, id, disable] + ) + + const onTouchStart = React.useCallback((e: React.TouchEvent) => { + e.preventDefault() + }, []) + + const onTouchEnd = React.useCallback((e: React.TouchEvent) => { + e.preventDefault() + }, []) + + return { + onPointerDown, + onPointerUp, + onPointerEnter, + onPointerMove, + onPointerLeave, + onTouchStart, + onTouchEnd, + } +} diff --git a/packages/core/src/hooks/useShapeTree.tsx b/packages/core/src/hooks/useShapeTree.tsx new file mode 100644 index 000000000..ed347fc7a --- /dev/null +++ b/packages/core/src/hooks/useShapeTree.tsx @@ -0,0 +1,123 @@ +import * as React from 'react' +import type { + IShapeTreeNode, + TLPage, + TLPageState, + TLShape, + TLShapeUtils, + TLCallbacks, + TLBinding, +} from '+types' +import { Utils, Vec } from '+utils' + +function addToShapeTree>( + shape: TLShape, + branch: IShapeTreeNode[], + shapes: TLPage['shapes'], + pageState: { + bindingTargetId?: string + bindingId?: string + hoveredId?: string + selectedIds: string[] + currentParentId?: string + editingId?: string + editingBindingId?: string + }, + meta?: M +) { + const node: IShapeTreeNode = { + shape, + isCurrentParent: pageState.currentParentId === shape.id, + isEditing: pageState.editingId === shape.id, + isSelected: pageState.selectedIds.includes(shape.id), + isHovered: pageState.hoveredId + ? pageState.hoveredId === shape.id || + (shape.children ? shape.children.includes(pageState.hoveredId) : false) + : false, + isBinding: pageState.bindingTargetId === shape.id, + meta, + } + + branch.push(node) + + if (shape.children) { + node.children = [] + shape.children + .map((id) => shapes[id]) + .sort((a, b) => a.childIndex - b.childIndex) + .forEach((childShape) => + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + addToShapeTree(childShape, node.children!, shapes, pageState, meta) + ) + } +} + +export function useShapeTree>( + page: TLPage, + pageState: TLPageState, + shapeUtils: TLShapeUtils, + meta?: M, + onChange?: TLCallbacks['onChange'] +) { + const rPreviousCount = React.useRef(0) + + if (typeof window === 'undefined') return [] + + const { selectedIds, camera } = pageState + + // Find viewport + + const [minX, minY] = Vec.sub(Vec.div([0, 0], camera.zoom), camera.point) + + const [maxX, maxY] = Vec.sub( + Vec.div([window.innerWidth, window.innerHeight], camera.zoom), + camera.point + ) + + const viewport = { + minX, + minY, + maxX, + maxY, + height: maxX - minX, + width: maxY - minY, + } + + // Filter shapes that are in view, and that are the direct child of + // the page. Other shapes are not visible, or will be rendered as + // the children of groups. + + const shapesToRender = Object.values(page.shapes).filter((shape) => { + if (shape.parentId !== page.id) return false + + // Don't hide selected shapes (this breaks certain drag interactions) + if (selectedIds.includes(shape.id)) return true + + const shapeBounds = shapeUtils[shape.type as T['type']].getBounds(shape) + + return Utils.boundsContain(viewport, shapeBounds) || Utils.boundsCollide(viewport, shapeBounds) + }) + + // Call onChange callback when number of rendering shapes changes + + if (shapesToRender.length !== rPreviousCount.current) { + // Use a timeout to clear call stack, in case the onChange handleer + // produces a new state change (React won't like that) + setTimeout(() => onChange?.(shapesToRender.map((shape) => shape.id)), 0) + rPreviousCount.current = shapesToRender.length + } + + const bindingTargetId = pageState.bindingId ? page.bindings[pageState.bindingId].toId : undefined + + // Populate the shape tree + + const tree: IShapeTreeNode[] = [] + + shapesToRender + .sort((a, b) => a.childIndex - b.childIndex) + .forEach((shape) => + addToShapeTree(shape, tree, page.shapes, { ...pageState, bindingTargetId }, meta) + ) + + return tree +} diff --git a/packages/core/src/hooks/useStyle.tsx b/packages/core/src/hooks/useStyle.tsx new file mode 100644 index 000000000..bbea327f7 --- /dev/null +++ b/packages/core/src/hooks/useStyle.tsx @@ -0,0 +1,279 @@ +import * as React from 'react' +import type { TLTheme } from '+types' + +const styles = new Map() + +type AnyTheme = Record + +function makeCssTheme(prefix: string, theme: T) { + return Object.keys(theme).reduce((acc, key) => { + const value = theme[key as keyof T] + if (value) { + return acc + `${`--${prefix}-${key}`}: ${value};\n` + } + return acc + }, '') +} + +function useTheme(prefix: string, theme: T, selector = ':root') { + React.useLayoutEffect(() => { + const style = document.createElement('style') + const cssTheme = makeCssTheme(prefix, theme) + + style.setAttribute('id', `${prefix}-theme`) + style.setAttribute('data-selector', selector) + style.innerHTML = ` + ${selector} { + ${cssTheme} + } + ` + + document.head.appendChild(style) + + return () => { + if (style && document.head.contains(style)) { + document.head.removeChild(style) + } + } + }, [prefix, theme, selector]) +} + +function useStyle(uid: string, rules: string) { + React.useLayoutEffect(() => { + if (styles.get(uid)) { + return () => void null + } + + const style = document.createElement('style') + style.innerHTML = rules + style.setAttribute('id', uid) + document.head.appendChild(style) + styles.set(uid, style) + + return () => { + if (style && document.head.contains(style)) { + document.head.removeChild(style) + styles.delete(uid) + } + } + }, [uid, rules]) +} + +const css = (strings: TemplateStringsArray, ...args: unknown[]) => + strings.reduce( + (acc, string, index) => acc + string + (index < args.length ? args[index] : ''), + '' + ) + +const defaultTheme: TLTheme = { + brushFill: 'rgba(0,0,0,.05)', + brushStroke: 'rgba(0,0,0,.25)', + selectStroke: 'rgb(66, 133, 244)', + selectFill: 'rgba(65, 132, 244, 0.05)', + background: 'rgb(248, 249, 250)', + foreground: 'rgb(51, 51, 51)', +} + +const tlcss = css` + @font-face { + font-family: 'Recursive'; + font-style: normal; + font-weight: 500; + font-display: swap; + src: url(https://fonts.gstatic.com/s/recursive/v23/8vI-7wMr0mhh-RQChyHEH06TlXhq_gukbYrFMk1QuAIcyEwG_X-dpEfaE5YaERmK-CImKsvxvU-MXGX2fSqasNfUlTGZnI14ZeY.woff2) + format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, + U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; + } + + @font-face { + font-family: 'Recursive'; + font-style: normal; + font-weight: 700; + font-display: swap; + src: url(https://fonts.gstatic.com/s/recursive/v23/8vI-7wMr0mhh-RQChyHEH06TlXhq_gukbYrFMk1QuAIcyEwG_X-dpEfaE5YaERmK-CImKsvxvU-MXGX2fSqasNfUlTGZnI14ZeY.woff2) + format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, + U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; + } + + @font-face { + font-family: 'Recursive Mono'; + font-style: normal; + font-weight: 420; + font-display: swap; + src: url(https://fonts.gstatic.com/s/recursive/v23/8vI-7wMr0mhh-RQChyHEH06TlXhq_gukbYrFMk1QuAIcyEwG_X-dpEfaE5YaERmK-CImqvTxvU-MXGX2fSqasNfUlTGZnI14ZeY.woff2) + format('woff2'); + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, + U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; + } + + html, + * { + box-sizing: border-box; + } + + :root { + --tl-zoom: 1; + --tl-scale: calc(1 / var(--tl-zoom)); + } + .tl-counter-scaled { + transform: scale(var(--tl-scale)); + } + .tl-dashed { + stroke-dasharray: calc(2px * var(--tl-scale)), calc(2px * var(--tl-scale)); + } + .tl-transparent { + fill: transparent; + stroke: transparent; + } + .tl-cursor-ns { + cursor: ns-resize; + } + .tl-cursor-ew { + cursor: ew-resize; + } + .tl-cursor-nesw { + cursor: nesw-resize; + } + .tl-cursor-nwse { + cursor: nwse-resize; + } + .tl-corner-handle { + stroke: var(--tl-selectStroke); + fill: var(--tl-background); + stroke-width: calc(1.5px * var(--tl-scale)); + } + .tl-rotate-handle { + stroke: var(--tl-selectStroke); + fill: var(--tl-background); + stroke-width: calc(1.5px * var(--tl-scale)); + cursor: grab; + } + .tl-binding { + fill: var(--tl-selectFill); + stroke: var(--tl-selectStroke); + stroke-width: calc(1px * var(--tl-scale)); + pointer-events: none; + } + .tl-selected { + fill: transparent; + stroke: var(--tl-selectStroke); + stroke-width: calc(1.5px * var(--tl-scale)); + pointer-events: none; + } + .tl-hovered { + fill: transparent; + stroke: var(--tl-selectStroke); + stroke-width: calc(1.5px * var(--tl-scale)); + pointer-events: none; + } + .tl-bounds-center { + fill: transparent; + stroke: var(--tl-selectStroke); + stroke-width: calc(1.5px * var(--tl-scale)); + } + .tl-bounds-bg { + stroke: none; + fill: var(--tl-selectFill); + pointer-events: all; + } + .tl-brush { + fill: var(--tl-brushFill); + stroke: var(--tl-brushStroke); + stroke-width: calc(1px * var(--tl-scale)); + pointer-events: none; + } + .tl-canvas { + position: fixed; + overflow: hidden; + top: 0px; + left: 0px; + width: 100%; + height: 100%; + touch-action: none; + z-index: 100; + pointer-events: all; + } + .tl-container { + position: relative; + box-sizing: border-box; + width: 100%; + height: 100%; + padding: 0px; + margin: 0px; + overscroll-behavior: none; + overscroll-behavior-x: none; + background-color: var(--tl-background); + } + .tl-container * { + user-select: none; + } + .tl-dot { + fill: var(--tl-background); + stroke: var(--tl-foreground); + stroke-width: 2px; + } + .tl-handles { + pointer-events: all; + } + .tl-handles:hover > .tl-handle-bg { + fill: var(--tl-selectFill); + } + .tl-handles:hover > .tl-handle-bg > * { + stroke: var(--tl-selectFill); + } + .tl-handles:active > .tl-handle-bg { + fill: var(--tl-selectFill); + } + .tl-handles:active > .tl-handle-bg > * { + stroke: var(--tl-selectFill); + } + .tl-handle { + fill: var(--tl-background); + stroke: var(--tl-selectStroke); + stroke-width: 1.5px; + } + .tl-handle-bg { + fill: transparent; + stroke: none; + pointer-events: all; + } + .tl-binding-indicator { + stroke-width: calc(3px * var(--tl-scale)); + fill: var(--tl-selectFill); + stroke: var(--tl-selected); + } + .tl-shape-group { + outline: none; + } + .tl-shape-group > *[data-shy='true'] { + opacity: 0; + } + .tl-shape-group:hover > *[data-shy='true'] { + opacity: 1; + } + .tl-current-parent > *[data-shy='true'] { + opacity: 1; + } + + .tl-binding { + fill: none; + stroke: var(--tl-selectStroke); + stroke-width: calc(2px * var(--tl-scale)); + } +` + +export function useTLTheme(theme?: Partial) { + const tltheme = React.useMemo( + () => ({ + ...defaultTheme, + ...theme, + }), + [theme] + ) + + useTheme('tl', tltheme) + + useStyle('tl-canvas', tlcss) +} diff --git a/packages/core/src/hooks/useTLContext.tsx b/packages/core/src/hooks/useTLContext.tsx new file mode 100644 index 000000000..d32e394b4 --- /dev/null +++ b/packages/core/src/hooks/useTLContext.tsx @@ -0,0 +1,17 @@ +import * as React from 'react' +import type { TLCallbacks, TLShape, TLBounds, TLPageState, TLShapeUtils } from '+types' + +export interface TLContextType { + callbacks: Partial + shapeUtils: TLShapeUtils + rPageState: React.MutableRefObject + rScreenBounds: React.MutableRefObject +} + +export const TLContext = React.createContext({} as TLContextType) + +export function useTLContext() { + const context = React.useContext(TLContext) + + return context +} diff --git a/packages/core/src/hooks/useZoomEvents.ts b/packages/core/src/hooks/useZoomEvents.ts new file mode 100644 index 000000000..a31bc61cf --- /dev/null +++ b/packages/core/src/hooks/useZoomEvents.ts @@ -0,0 +1,82 @@ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +import { useRef } from 'react' +import { useTLContext } from './useTLContext' +import { Vec } from '+utils' +import { useWheel, usePinch } from 'react-use-gesture' +import { inputs } from '+inputs' + +// Capture zoom gestures (pinches, wheels and pans) +export function useZoomEvents() { + const rPinchDa = useRef(undefined) + const rOriginPoint = useRef(undefined) + const rPinchPoint = useRef(undefined) + + const { callbacks } = useTLContext() + + useWheel( + ({ event: e, delta }) => { + e.preventDefault() + + if (Vec.isEqual(delta, [0, 0])) return + + const info = inputs.pan(delta, e as WheelEvent) + + callbacks.onPan?.(info, e) + }, + { + domTarget: typeof document === 'undefined' ? undefined : document.body, + eventOptions: { passive: false }, + } + ) + + usePinch( + ({ pinching, da, origin, event: e }) => { + if (!pinching) { + const info = inputs.pinch(origin, origin) + callbacks.onPinchEnd?.( + info, + e as React.WheelEvent | WheelEvent | React.TouchEvent | TouchEvent + ) + rPinchDa.current = undefined + rPinchPoint.current = undefined + rOriginPoint.current = undefined + return + } + + if (rPinchPoint.current === undefined) { + const info = inputs.pinch(origin, origin) + callbacks.onPinchStart?.( + info, + e as React.WheelEvent | WheelEvent | React.TouchEvent | TouchEvent + ) + rPinchDa.current = da + rPinchPoint.current = origin + rOriginPoint.current = origin + } + + if (!rPinchDa.current) throw Error('No pinch direction!') + if (!rOriginPoint.current) throw Error('No origin point!') + + const [distanceDelta] = Vec.sub(rPinchDa.current, da) + + const info = inputs.pinch(rPinchPoint.current, origin) + + callbacks.onPinch?.( + { + ...info, + point: origin, + origin: rOriginPoint.current, + delta: [...info.delta, distanceDelta], + }, + e as React.WheelEvent | WheelEvent | React.TouchEvent | TouchEvent + ) + + rPinchDa.current = da + rPinchPoint.current = origin + }, + { + domTarget: typeof document === 'undefined' ? undefined : document.body, + eventOptions: { passive: false }, + } + ) +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 000000000..f28ce2b3a --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,4 @@ +export * from './components' +export * from './types' +export * from './utils' +export * from './inputs' diff --git a/packages/core/src/inputs.ts b/packages/core/src/inputs.ts new file mode 100644 index 000000000..09c21171d --- /dev/null +++ b/packages/core/src/inputs.ts @@ -0,0 +1,321 @@ +import type React from 'react' +import type { TLKeyboardInfo, TLPointerInfo } from './types' +import { Vec, Utils } from './utils' + +const DOUBLE_CLICK_DURATION = 250 + +class Inputs { + pointer?: TLPointerInfo + keyboard?: TLKeyboardInfo + keys: Record = {} + + pointerUpTime = 0 + + touchStart(e: TouchEvent | React.TouchEvent, target: T): TLPointerInfo { + const { shiftKey, ctrlKey, metaKey, altKey } = e + e.preventDefault() + + const touch = e.changedTouches[0] + + const info: TLPointerInfo = { + target, + pointerId: touch.identifier, + origin: Inputs.getPoint(touch), + delta: [0, 0], + point: Inputs.getPoint(touch), + pressure: Inputs.getPressure(touch), + shiftKey, + ctrlKey, + metaKey: Utils.isDarwin() ? metaKey : ctrlKey, + altKey, + } + + this.pointer = info + + return info + } + + touchMove(e: TouchEvent | React.TouchEvent, target: T): TLPointerInfo { + const { shiftKey, ctrlKey, metaKey, altKey } = e + e.preventDefault() + + const touch = e.changedTouches[0] + + const prev = this.pointer + + const point = Inputs.getPoint(touch) + + const delta = prev?.point ? Vec.sub(point, prev.point) : [0, 0] + + const info: TLPointerInfo = { + origin: point, + ...prev, + target, + pointerId: touch.identifier, + point, + delta, + pressure: Inputs.getPressure(touch), + shiftKey, + ctrlKey, + metaKey: Utils.isDarwin() ? metaKey : ctrlKey, + altKey, + } + + this.pointer = info + + return info + } + + pointerDown(e: PointerEvent | React.PointerEvent, target: T): TLPointerInfo { + const { shiftKey, ctrlKey, metaKey, altKey } = e + + const point = Inputs.getPoint(e) + + const info: TLPointerInfo = { + target, + pointerId: e.pointerId, + origin: point, + point: point, + delta: [0, 0], + pressure: Inputs.getPressure(e), + shiftKey, + ctrlKey, + metaKey: Utils.isDarwin() ? metaKey : ctrlKey, + altKey, + } + + this.pointer = info + + return info + } + + pointerEnter( + e: PointerEvent | React.PointerEvent, + target: T + ): TLPointerInfo { + const { shiftKey, ctrlKey, metaKey, altKey } = e + + const point = Inputs.getPoint(e) + + const info: TLPointerInfo = { + target, + pointerId: e.pointerId, + origin: point, + delta: [0, 0], + point: point, + pressure: Inputs.getPressure(e), + shiftKey, + ctrlKey, + metaKey: Utils.isDarwin() ? metaKey : ctrlKey, + altKey, + } + + this.pointer = info + + return info + } + + pointerMove(e: PointerEvent | React.PointerEvent, target: T): TLPointerInfo { + const { shiftKey, ctrlKey, metaKey, altKey } = e + + const prev = this.pointer + + const point = Inputs.getPoint(e) + + const delta = prev?.point ? Vec.sub(point, prev.point) : [0, 0] + + const info: TLPointerInfo = { + origin: point, + ...prev, + target, + pointerId: e.pointerId, + point, + delta, + pressure: Inputs.getPressure(e), + shiftKey, + ctrlKey, + metaKey: Utils.isDarwin() ? metaKey : ctrlKey, + altKey, + } + + this.pointer = info + + return info + } + + pointerUp(e: PointerEvent | React.PointerEvent, target: T): TLPointerInfo { + const { shiftKey, ctrlKey, metaKey, altKey } = e + + const prev = this.pointer + + const point = Inputs.getPoint(e) + + const delta = prev?.point ? Vec.sub(point, prev.point) : [0, 0] + + const info: TLPointerInfo = { + origin: point, + ...prev, + target, + pointerId: e.pointerId, + point, + delta, + pressure: Inputs.getPressure(e), + shiftKey, + ctrlKey, + metaKey: Utils.isDarwin() ? metaKey : ctrlKey, + altKey, + } + + this.pointer = info + + this.pointerUpTime = Date.now() + + return info + } + + panStart = (e: WheelEvent): TLPointerInfo<'wheel'> => { + const { shiftKey, ctrlKey, metaKey, altKey } = e + + const info: TLPointerInfo<'wheel'> = { + target: 'wheel', + pointerId: this.pointer?.pointerId || 0, + origin: this.pointer?.origin || [0, 0], + delta: [0, 0], + pressure: 0.5, + point: Inputs.getPoint(e), + shiftKey, + ctrlKey, + metaKey, + altKey, + } + + this.pointer = info + + return info + } + + pan = (delta: number[], e: WheelEvent): TLPointerInfo<'wheel'> => { + if (!this.pointer || this.pointer.target !== 'wheel') { + return this.panStart(e) + } + + const { shiftKey, ctrlKey, metaKey, altKey } = e + + const prev = this.pointer + + const point = Inputs.getPoint(e) + + const info: TLPointerInfo<'wheel'> = { + ...prev, + target: 'wheel', + delta, + point, + shiftKey, + ctrlKey, + metaKey, + altKey, + } + + this.pointer = info + + return info + } + + isDoubleClick() { + if (!this.pointer) return false + + const { origin, point } = this.pointer + + return Date.now() - this.pointerUpTime < DOUBLE_CLICK_DURATION && Vec.dist(origin, point) < 4 + } + + clear() { + this.pointer = undefined + } + + resetDoubleClick() { + this.pointerUpTime = 0 + } + + keydown = (e: KeyboardEvent | React.KeyboardEvent): TLKeyboardInfo => { + const { shiftKey, ctrlKey, metaKey, altKey } = e + + this.keys[e.key] = true + + return { + point: this.pointer?.point || [0, 0], + origin: this.pointer?.origin || [0, 0], + key: e.key, + keys: Object.keys(this.keys), + shiftKey, + ctrlKey, + metaKey: Utils.isDarwin() ? metaKey : ctrlKey, + altKey, + } + } + + keyup = (e: KeyboardEvent | React.KeyboardEvent): TLKeyboardInfo => { + const { shiftKey, ctrlKey, metaKey, altKey } = e + + delete this.keys[e.key] + + return { + point: this.pointer?.point || [0, 0], + origin: this.pointer?.origin || [0, 0], + key: e.key, + keys: Object.keys(this.keys), + shiftKey, + ctrlKey, + metaKey: Utils.isDarwin() ? metaKey : ctrlKey, + altKey, + } + } + + pinch(point: number[], origin: number[]) { + const { shiftKey, ctrlKey, metaKey, altKey } = this.keys + + const prev = this.pointer + + const delta = Vec.sub(origin, point) + + const info: TLPointerInfo<'pinch'> = { + pointerId: 0, + target: 'pinch', + origin: prev?.origin || Vec.round(point), + delta: delta, + point: Vec.round(point), + pressure: 0.5, + shiftKey, + ctrlKey, + metaKey: Utils.isDarwin() ? metaKey : ctrlKey, + altKey, + } + + this.pointer = info + + return info + } + + reset() { + this.pointerUpTime = 0 + this.pointer = undefined + this.keyboard = undefined + this.keys = {} + } + + static getPoint( + e: PointerEvent | React.PointerEvent | Touch | React.Touch | WheelEvent + ): number[] { + return [Number(e.clientX.toPrecision(5)), Number(e.clientY.toPrecision(5))] + } + + static getPressure(e: PointerEvent | React.PointerEvent | Touch | React.Touch | WheelEvent) { + return 'pressure' in e ? Number(e.pressure.toPrecision(5)) || 0.5 : 0.5 + } + + static commandKey(): string { + return Utils.isDarwin() ? '⌘' : 'Ctrl' + } +} + +export const inputs = new Inputs() diff --git a/packages/core/src/test/box.spec.tsx b/packages/core/src/test/box.spec.tsx new file mode 100644 index 000000000..63539991d --- /dev/null +++ b/packages/core/src/test/box.spec.tsx @@ -0,0 +1,7 @@ +import { Box } from './box' + +describe('example shape', () => { + it('should create an instance', () => { + expect(new Box()).toBeTruthy() + }) +}) diff --git a/packages/core/src/test/box.tsx b/packages/core/src/test/box.tsx new file mode 100644 index 000000000..42997c967 --- /dev/null +++ b/packages/core/src/test/box.tsx @@ -0,0 +1,79 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import * as React from 'react' +import { TLShapeUtil, TLShape, TLBounds, TLRenderInfo, TLTransformInfo } from '+types' +import Utils, { Intersect } from '+utils' + +export interface BoxShape extends TLShape { + size: number[] +} + +export class Box extends TLShapeUtil { + type = 'box' + + defaultProps = { + id: 'example1', + type: 'box', + parentId: 'page', + childIndex: 0, + name: 'Example Shape', + point: [0, 0], + size: [100, 100], + rotation: 0, + } + + create(props: Partial) { + return { ...this.defaultProps, ...props } + } + + render(shape: BoxShape, info: TLRenderInfo): JSX.Element { + return + } + + renderIndicator(shape: BoxShape) { + return + } + + shouldRender(prev: BoxShape, next: BoxShape): boolean { + return true + } + + getBounds(shape: BoxShape): TLBounds { + return Utils.getFromCache(this.boundsCache, shape, () => ({ + minX: 0, + minY: 0, + maxX: 0, + maxY: 0, + width: 100, + height: 100, + })) + } + + getRotatedBounds(shape: BoxShape) { + return Utils.getBoundsFromPoints(Utils.getRotatedCorners(this.getBounds(shape), shape.rotation)) + } + + getCenter(shape: BoxShape): number[] { + return Utils.getBoundsCenter(this.getBounds(shape)) + } + + hitTest(shape: BoxShape, point: number[]) { + return Utils.pointInBounds(point, this.getBounds(shape)) + } + + hitTestBounds(shape: BoxShape, bounds: TLBounds) { + const rotatedCorners = Utils.getRotatedCorners(this.getBounds(shape), shape.rotation) + + return ( + rotatedCorners.every((point) => Utils.pointInBounds(point, bounds)) || + Intersect.polyline.bounds(rotatedCorners, bounds).length > 0 + ) + } + + transform(shape: BoxShape, bounds: TLBounds, _info: TLTransformInfo): BoxShape { + return { ...shape, point: [bounds.minX, bounds.minY] } + } + + transformSingle(shape: BoxShape, bounds: TLBounds, info: TLTransformInfo): BoxShape { + return this.transform(shape, bounds, info) + } +} diff --git a/packages/core/src/test/context-wrapper.tsx b/packages/core/src/test/context-wrapper.tsx new file mode 100644 index 000000000..46644efdc --- /dev/null +++ b/packages/core/src/test/context-wrapper.tsx @@ -0,0 +1,20 @@ +import * as React from 'react' +import type { TLPageState, TLBounds } from '../types' +import { mockDocument } from './mockDocument' +import { mockUtils } from './mockUtils' +import { useTLTheme, TLContext } from '../hooks' + +export const ContextWrapper: React.FC = ({ children }) => { + useTLTheme() + const rScreenBounds = React.useRef(null) + const rPageState = React.useRef(mockDocument.pageState) + + const [context] = React.useState(() => ({ + callbacks: {}, + shapeUtils: mockUtils, + rScreenBounds, + rPageState, + })) + + return {children} +} diff --git a/packages/core/src/test/index.ts b/packages/core/src/test/index.ts new file mode 100644 index 000000000..ae2fa4f34 --- /dev/null +++ b/packages/core/src/test/index.ts @@ -0,0 +1,5 @@ +export * from './box' +export * from './mockDocument' +export * from './mockUtils' +export * from './renderWithContext' +export * from './renderWithSvg' diff --git a/packages/core/src/test/mockDocument.ts b/packages/core/src/test/mockDocument.ts new file mode 100644 index 000000000..6a8dc43a2 --- /dev/null +++ b/packages/core/src/test/mockDocument.ts @@ -0,0 +1,19 @@ +import type { TLBinding, TLPage, TLPageState } from '+types' +import type { BoxShape } from './box' + +export const mockDocument: { page: TLPage; pageState: TLPageState } = { + page: { + id: 'page1', + shapes: {}, + bindings: {}, + }, + pageState: { + id: 'page1', + selectedIds: [], + currentParentId: 'page1', + camera: { + point: [0, 0], + zoom: 1, + }, + }, +} diff --git a/packages/core/src/test/mockUtils.tsx b/packages/core/src/test/mockUtils.tsx new file mode 100644 index 000000000..79483abed --- /dev/null +++ b/packages/core/src/test/mockUtils.tsx @@ -0,0 +1,6 @@ +import type { TLShapeUtils } from '+types' +import { Box, BoxShape } from './box' + +export const mockUtils: TLShapeUtils = { + box: new Box(), +} diff --git a/packages/core/src/test/renderWithContext.tsx b/packages/core/src/test/renderWithContext.tsx new file mode 100644 index 000000000..fbd7ab26c --- /dev/null +++ b/packages/core/src/test/renderWithContext.tsx @@ -0,0 +1,7 @@ +import * as React from 'react' +import { render } from '@testing-library/react' +import { ContextWrapper } from './context-wrapper' + +export const renderWithContext = (children: JSX.Element) => { + return render({children}) +} diff --git a/packages/core/src/test/renderWithSvg.tsx b/packages/core/src/test/renderWithSvg.tsx new file mode 100644 index 000000000..d5a8176ab --- /dev/null +++ b/packages/core/src/test/renderWithSvg.tsx @@ -0,0 +1,11 @@ +import * as React from 'react' +import { render } from '@testing-library/react' +import { ContextWrapper } from './context-wrapper' + +export const renderWithSvg = (children: JSX.Element) => { + return render( + + {children} + + ) +} diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts new file mode 100644 index 000000000..8e2c3334e --- /dev/null +++ b/packages/core/src/types.ts @@ -0,0 +1,399 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* --------------------- Primary -------------------- */ + +export interface TLPage { + id: string + name?: string + childIndex?: number + shapes: Record + bindings: Record + backgroundColor?: string +} + +export interface TLPageState { + id: string + selectedIds: string[] + camera: { + point: number[] + zoom: number + } + brush?: TLBounds + pointedId?: string + hoveredId?: string + editingId?: string + bindingId?: string + boundsRotation?: number + currentParentId?: string +} + +export interface TLHandle { + id: string + index: number + point: number[] + canBind?: boolean + bindingId?: string +} + +export interface TLShape { + id: string + type: string + parentId: string + childIndex: number + name: string + point: number[] + rotation?: number + children?: string[] + handles?: Record + isLocked?: boolean + isHidden?: boolean + isEditing?: boolean + isGenerated?: boolean + isAspectRatioLocked?: boolean +} + +export type TLShapeUtils = Record> + +export interface TLRenderInfo { + ref?: React.RefObject + isEditing: boolean + isBinding: boolean + isHovered: boolean + isSelected: boolean + isCurrentParent: boolean + onTextChange?: TLCallbacks['onTextChange'] + onTextBlur?: TLCallbacks['onTextBlur'] + onTextFocus?: TLCallbacks['onTextFocus'] + onTextKeyDown?: TLCallbacks['onTextKeyDown'] + onTextKeyUp?: TLCallbacks['onTextKeyUp'] + meta: M extends any ? M : never +} + +export interface TLTool { + id: string + name: string +} + +export interface TLBinding { + id: string + type: string + toId: string + fromId: string +} + +export interface TLTheme { + brushFill?: string + brushStroke?: string + selectFill?: string + selectStroke?: string + background?: string + foreground?: string +} + +export type TLWheelEventHandler = ( + info: TLPointerInfo, + e: React.WheelEvent | WheelEvent +) => void +export type TLPinchEventHandler = ( + info: TLPointerInfo, + e: React.WheelEvent | WheelEvent | React.TouchEvent | TouchEvent +) => void +export type TLPointerEventHandler = (info: TLPointerInfo, e: React.PointerEvent) => void +export type TLCanvasEventHandler = (info: TLPointerInfo<'canvas'>, e: React.PointerEvent) => void +export type TLBoundsEventHandler = (info: TLPointerInfo<'bounds'>, e: React.PointerEvent) => void +export type TLBoundsHandleEventHandler = ( + info: TLPointerInfo, + e: React.PointerEvent +) => void + +export interface TLCallbacks { + onChange: (ids: string[]) => void + + // Camera events + onPinchStart: TLPinchEventHandler + onPinchEnd: TLPinchEventHandler + onPinch: TLPinchEventHandler + onPan: TLWheelEventHandler + onZoom: TLWheelEventHandler + + // Pointer Events + onPointerMove: TLPointerEventHandler + onPointerUp: TLPointerEventHandler + onPointerDown: TLPointerEventHandler + + // Canvas (background) + onPointCanvas: TLCanvasEventHandler + onDoubleClickCanvas: TLCanvasEventHandler + onRightPointCanvas: TLCanvasEventHandler + onDragCanvas: TLCanvasEventHandler + onReleaseCanvas: TLCanvasEventHandler + + // Shape + onPointShape: TLPointerEventHandler + onDoubleClickShape: TLPointerEventHandler + onRightPointShape: TLPointerEventHandler + onDragShape: TLPointerEventHandler + onHoverShape: TLPointerEventHandler + onUnhoverShape: TLPointerEventHandler + onReleaseShape: TLPointerEventHandler + + // Bounds (bounding box background) + onPointBounds: TLBoundsEventHandler + onDoubleClickBounds: TLBoundsEventHandler + onRightPointBounds: TLBoundsEventHandler + onDragBounds: TLBoundsEventHandler + onHoverBounds: TLBoundsEventHandler + onUnhoverBounds: TLBoundsEventHandler + onReleaseBounds: TLBoundsEventHandler + + // Bounds handles (corners, edges) + onPointBoundsHandle: TLBoundsHandleEventHandler + onDoubleClickBoundsHandle: TLBoundsHandleEventHandler + onRightPointBoundsHandle: TLBoundsHandleEventHandler + onDragBoundsHandle: TLBoundsHandleEventHandler + onHoverBoundsHandle: TLBoundsHandleEventHandler + onUnhoverBoundsHandle: TLBoundsHandleEventHandler + onReleaseBoundsHandle: TLBoundsHandleEventHandler + + // Handles (ie the handles of a selected arrow) + onPointHandle: TLPointerEventHandler + onDoubleClickHandle: TLPointerEventHandler + onRightPointHandle: TLPointerEventHandler + onDragHandle: TLPointerEventHandler + onHoverHandle: TLPointerEventHandler + onUnhoverHandle: TLPointerEventHandler + onReleaseHandle: TLPointerEventHandler + + // Text + onTextChange: (id: string, text: string) => void + onTextBlur: (id: string) => void + onTextFocus: (id: string) => void + onTextKeyDown: (id: string, key: string) => void + onTextKeyUp: (id: string, key: string) => void + + // Misc + onBlurEditingShape: () => void + onError: (error: Error) => void +} + +export interface TLBounds { + minX: number + minY: number + maxX: number + maxY: number + width: number + height: number + rotation?: number +} + +export type TLIntersection = { + didIntersect: boolean + message: string + points: number[][] +} + +export enum TLBoundsEdge { + Top = 'top_edge', + Right = 'right_edge', + Bottom = 'bottom_edge', + Left = 'left_edge', +} + +export enum TLBoundsCorner { + TopLeft = 'top_left_corner', + TopRight = 'top_right_corner', + BottomRight = 'bottom_right_corner', + BottomLeft = 'bottom_left_corner', +} + +export interface TLPointerInfo { + target: T + pointerId: number + origin: number[] + point: number[] + delta: number[] + pressure: number + shiftKey: boolean + ctrlKey: boolean + metaKey: boolean + altKey: boolean +} + +export interface TLKeyboardInfo { + origin: number[] + point: number[] + key: string + keys: string[] + shiftKey: boolean + ctrlKey: boolean + metaKey: boolean + altKey: boolean +} + +export interface TLTransformInfo { + type: TLBoundsEdge | TLBoundsCorner + initialShape: T + scaleX: number + scaleY: number + transformOrigin: number[] +} + +export interface TLBezierCurveSegment { + start: number[] + tangentStart: number[] + normalStart: number[] + pressureStart: number + end: number[] + tangentEnd: number[] + normalEnd: number[] + pressureEnd: number +} + +/* -------------------------------------------------- */ +/* Shape Utility */ +/* -------------------------------------------------- */ + +export abstract class TLShapeUtil { + boundsCache = new WeakMap() + isEditableText = false + isAspectRatioLocked = false + canEdit = false + canBind = false + + abstract type: T['type'] + + abstract defaultProps: T + + abstract render(shape: T, info: TLRenderInfo): JSX.Element | null + + abstract renderIndicator(shape: T): JSX.Element | null + + abstract getBounds(shape: T): TLBounds + + abstract getRotatedBounds(shape: T): TLBounds + + abstract hitTest(shape: T, point: number[]): boolean + + abstract hitTestBounds(shape: T, bounds: TLBounds): boolean + + abstract transform(shape: T, bounds: TLBounds, info: TLTransformInfo): Partial + + transformSingle(shape: T, bounds: TLBounds, info: TLTransformInfo): Partial { + return this.transform(shape, bounds, info) + } + + shouldRender(_prev: T, _next: T): boolean { + return true + } + + shouldDelete(_shape: T): boolean { + return false + } + + getCenter(shape: T): number[] { + const bounds = this.getBounds(shape) + return [bounds.width / 2, bounds.height / 2] + } + + getBindingPoint( + shape: T, + fromShape: TLShape, + point: number[], + origin: number[], + direction: number[], + padding: number, + anywhere: boolean + ): { point: number[]; distance: number } | undefined { + return undefined + } + + create(props: Partial): T { + return { ...this.defaultProps, ...props } + } + + mutate(shape: T, props: Partial): T { + return { ...shape, ...props } + } + + updateChildren(shape: T, children: K[]): Partial[] | void { + return + } + + onChildrenChange(shape: T, children: TLShape[]): Partial | void { + return + } + + onBindingChange( + shape: T, + binding: TLBinding, + target: TLShape, + targetBounds: TLBounds, + center: number[] + ): Partial | void { + return undefined + } + + onHandleChange( + shape: T, + handle: Partial, + info: Partial + ): Partial | void { + return + } + + onRightPointHandle( + shape: T, + handle: Partial, + info: Partial + ): Partial | void { + return + } + + onDoubleClickHandle( + shape: T, + handle: Partial, + info: Partial + ): Partial | void { + return + } + + onSessionComplete(shape: T): Partial | void { + return + } + + onBoundsReset(shape: T): Partial | void { + return + } + + onStyleChange(shape: T): Partial | void { + return + } +} + +/* -------------------- Internal -------------------- */ + +export interface IShapeTreeNode> { + shape: TLShape + children?: IShapeTreeNode[] + isEditing: boolean + isBinding: boolean + isHovered: boolean + isSelected: boolean + isCurrentParent: boolean + meta?: M +} + +/* -------------------------------------------------- */ +/* Utility Types */ +/* -------------------------------------------------- */ + +/** @internal */ +export type MappedByType = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [P in T['type']]: T extends any ? (P extends T['type'] ? T : never) : never +} + +/** @internal */ +export type RequiredKeys = { + [K in keyof T]-?: Record extends Pick ? never : K +}[keyof T] diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts new file mode 100644 index 000000000..62b52f608 --- /dev/null +++ b/packages/core/src/utils/index.ts @@ -0,0 +1,7 @@ +import { Utils } from './utils' +export { Intersect } from './intersect' +export { Utils } from './utils' +export { Svg } from './svg' +export { Vec } from './vec' + +export default Utils diff --git a/packages/core/src/utils/intersect.ts b/packages/core/src/utils/intersect.ts new file mode 100644 index 000000000..f0f0a6bf1 --- /dev/null +++ b/packages/core/src/utils/intersect.ts @@ -0,0 +1,680 @@ +import type { TLBounds, TLIntersection } from '../types' +import { Vec } from './vec' +import { Utils } from './utils' + +/* ----------------- Start Copy Here ---------------- */ + +function getIntersection(message: string, ...points: number[][]): TLIntersection { + const didIntersect = points.length > 0 + return { didIntersect, message, points } +} + +export class Intersect { + static ray = { + // Intersect a ray with a ray. + ray(p0: number[], n0: number[], p1: number[], n1: number[]): TLIntersection { + const dx = p1[0] - p0[0] + const dy = p1[1] - p0[1] + const det = n1[0] * n0[1] - n1[1] * n0[0] + const u = (dy * n1[0] - dx * n1[1]) / det + const v = (dy * n0[0] - dx * n0[1]) / det + if (u < 0 || v < 0) return getIntersection('miss') + + const m0 = n0[1] / n0[0] + const m1 = n1[1] / n1[0] + const b0 = p0[1] - m0 * p0[0] + const b1 = p1[1] - m1 * p1[0] + const x = (b1 - b0) / (m0 - m1) + const y = m0 * x + b0 + + return Number.isFinite(x) + ? getIntersection('intersection', [x, y]) + : getIntersection('parallel') + }, + + // Interseg a ray with a line segment. + lineSegment(origin: number[], direction: number[], a1: number[], a2: number[]): TLIntersection { + const [x, y] = origin + const [dx, dy] = direction + const [x1, y1] = a1 + const [x2, y2] = a2 + + if (dy / dx !== (y2 - y1) / (x2 - x1)) { + const d = dx * (y2 - y1) - dy * (x2 - x1) + if (d !== 0) { + const r = ((y - y1) * (x2 - x1) - (x - x1) * (y2 - y1)) / d + const s = ((y - y1) * dx - (x - x1) * dy) / d + if (r >= 0 && s >= 0 && s <= 1) { + return getIntersection('intersection', [x + r * dx, y + r * dy]) + } + } + } + return getIntersection('no intersection') + }, + + // Intersect a ray with a rectangle. + rectangle( + origin: number[], + direction: number[], + point: number[], + size: number[], + rotation = 0 + ): TLIntersection[] { + return Intersect.rectangle.ray(point, size, rotation, origin, direction) + }, + + // Intersect a ray with an ellipse. + ellipse( + origin: number[], + direction: number[], + center: number[], + rx: number, + ry: number, + rotation: number + ): TLIntersection { + const a1 = origin + const a2 = Vec.mul(direction, 999999999) + return Intersect.lineSegment.ellipse(a1, a2, center, rx, ry, rotation) + }, + + // Intersect a ray with a bounding box. + bounds( + origin: number[], + direction: number[], + bounds: TLBounds, + rotation = 0 + ): TLIntersection[] { + const { minX, minY, width, height } = bounds + return Intersect.ray.rectangle(origin, direction, [minX, minY], [width, height], rotation) + }, + } + + static lineSegment = { + // Intersect a line segment with a ray. + ray(a1: number[], a2: number[], origin: number[], direction: number[]): TLIntersection { + return Intersect.ray.lineSegment(origin, direction, a1, a2) + }, + + // Intersect a line segment with a line segment. + lineSegment(a1: number[], a2: number[], b1: number[], b2: number[]): TLIntersection { + const AB = Vec.sub(a1, b1) + const BV = Vec.sub(b2, b1) + const AV = Vec.sub(a2, a1) + + const ua_t = BV[0] * AB[1] - BV[1] * AB[0] + const ub_t = AV[0] * AB[1] - AV[1] * AB[0] + const u_b = BV[1] * AV[0] - BV[0] * AV[1] + + if (ua_t === 0 || ub_t === 0) { + return getIntersection('coincident') + } + + if (u_b === 0) { + return getIntersection('parallel') + } + + if (u_b !== 0) { + const ua = ua_t / u_b + const ub = ub_t / u_b + if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) { + return getIntersection('intersection', Vec.add(a1, Vec.mul(AV, ua))) + } + } + + return getIntersection('no intersection') + }, + + // Intersect a line segment with a rectangle + rectangle(a1: number[], a2: number[], point: number[], size: number[]): TLIntersection[] { + return Intersect.rectangle.lineSegment(point, size, a1, a2) + }, + + // Intersect a line segment with an arc. + arc( + a1: number[], + a2: number[], + center: number[], + radius: number, + start: number[], + end: number[] + ): TLIntersection { + const sa = Vec.angle(center, start) + const ea = Vec.angle(center, end) + const ellipseTest = Intersect.ellipse.lineSegment(center, radius, radius, 0, a1, a2) + + if (!ellipseTest.didIntersect) return getIntersection('No intersection') + + const points = ellipseTest.points.filter((point) => + Utils.isAngleBetween(sa, ea, Vec.angle(center, point)) + ) + + if (points.length === 0) { + return getIntersection('No intersection') + } + + return getIntersection('intersection', ...points) + }, + + // Intersect a line segment with a circle. + circle(a1: number[], a2: number[], c: number[], r: number): TLIntersection { + const a = (a2[0] - a1[0]) * (a2[0] - a1[0]) + (a2[1] - a1[1]) * (a2[1] - a1[1]) + const b = 2 * ((a2[0] - a1[0]) * (a1[0] - c[0]) + (a2[1] - a1[1]) * (a1[1] - c[1])) + const cc = + c[0] * c[0] + + c[1] * c[1] + + a1[0] * a1[0] + + a1[1] * a1[1] - + 2 * (c[0] * a1[0] + c[1] * a1[1]) - + r * r + + const deter = b * b - 4 * a * cc + + if (deter < 0) { + return getIntersection('outside') + } + + if (deter === 0) { + return getIntersection('tangent') + } + + const e = Math.sqrt(deter) + const u1 = (-b + e) / (2 * a) + const u2 = (-b - e) / (2 * a) + if ((u1 < 0 || u1 > 1) && (u2 < 0 || u2 > 1)) { + if ((u1 < 0 && u2 < 0) || (u1 > 1 && u2 > 1)) { + return getIntersection('outside') + } else { + return getIntersection('inside') + } + } + + const results: number[][] = [] + if (0 <= u1 && u1 <= 1) results.push(Vec.lrp(a1, a2, u1)) + if (0 <= u2 && u2 <= 1) results.push(Vec.lrp(a1, a2, u2)) + + return getIntersection('intersection', ...results) + }, + + // Intersect a line segment with an ellipse. + ellipse( + a1: number[], + a2: number[], + center: number[], + rx: number, + ry: number, + rotation = 0 + ): TLIntersection { + // If the ellipse or line segment are empty, return no tValues. + if (rx === 0 || ry === 0 || Vec.isEqual(a1, a2)) { + return getIntersection('No intersection') + } + + // Get the semimajor and semiminor axes. + rx = rx < 0 ? rx : -rx + ry = ry < 0 ? ry : -ry + + // Rotate points and translate so the ellipse is centered at the origin. + a1 = Vec.sub(Vec.rotWith(a1, center, -rotation), center) + a2 = Vec.sub(Vec.rotWith(a2, center, -rotation), center) + + // Calculate the quadratic parameters. + const diff = Vec.sub(a2, a1) + + const A = (diff[0] * diff[0]) / rx / rx + (diff[1] * diff[1]) / ry / ry + const B = (2 * a1[0] * diff[0]) / rx / rx + (2 * a1[1] * diff[1]) / ry / ry + const C = (a1[0] * a1[0]) / rx / rx + (a1[1] * a1[1]) / ry / ry - 1 + + // Make a list of t values (normalized points on the line where intersections occur). + const tValues: number[] = [] + + // Calculate the discriminant. + const discriminant = B * B - 4 * A * C + + if (discriminant === 0) { + // One real solution. + tValues.push(-B / 2 / A) + } else if (discriminant > 0) { + const root = Math.sqrt(discriminant) + // Two real solutions. + tValues.push((-B + root) / 2 / A) + tValues.push((-B - root) / 2 / A) + } + + // Filter to only points that are on the segment. + // Solve for points, then counter-rotate points. + const points = tValues + .filter((t) => t >= 0 && t <= 1) + .map((t) => Vec.add(center, Vec.add(a1, Vec.mul(Vec.sub(a2, a1), t)))) + .map((p) => Vec.rotWith(p, center, rotation)) + + return getIntersection('intersection', ...points) + }, + + // Intersect a line segment with a bounding box. + bounds(a1: number[], a2: number[], bounds: TLBounds): TLIntersection[] { + return Intersect.bounds.lineSegment(bounds, a1, a2) + }, + + // Intersect a line segment with a polyline + polyline(a1: number[], a2: number[], points: number[][]): TLIntersection[] { + const intersections: TLIntersection[] = [] + + for (let i = 1; i < points.length + 1; i++) { + const int = Intersect.lineSegment.lineSegment( + a1, + a2, + points[i - 1], + points[i % points.length] + ) + + if (int) { + intersections.push(int) + } + } + + return intersections + }, + } + + static rectangle = { + // Intersect a rectangle with a ray. + ray( + point: number[], + size: number[], + rotation: number, + origin: number[], + direction: number[] + ): TLIntersection[] { + const sideIntersections = Utils.getRectangleSides(point, size, rotation).reduce< + TLIntersection[] + >((acc, [message, [a1, a2]]) => { + const intersection = Intersect.ray.lineSegment(origin, direction, a1, a2) + + if (intersection) { + acc.push(getIntersection(message, ...intersection.points)) + } + + return acc + }, []) + + return sideIntersections.filter((int) => int.didIntersect) + }, + + // Intersect a rectangle with a line segment. + lineSegment(point: number[], size: number[], a1: number[], a2: number[]): TLIntersection[] { + const sideIntersections = Utils.getRectangleSides(point, size).reduce( + (acc, [message, [b1, b2]]) => { + const intersection = Intersect.lineSegment.lineSegment(a1, a2, b1, b2) + + if (intersection) { + acc.push(getIntersection(message, ...intersection.points)) + } + + return acc + }, + [] + ) + + return sideIntersections.filter((int) => int.didIntersect) + }, + + // Intersect a rectangle with a rectangle. + rectangle( + point1: number[], + size1: number[], + point2: number[], + size2: number[] + ): TLIntersection[] { + const sideIntersections = Utils.getRectangleSides(point1, size1).reduce( + (acc, [message, [a1, a2]]) => { + const intersections = Intersect.rectangle.lineSegment(point2, size2, a1, a2) + + acc.push( + ...intersections.map((int) => + getIntersection(`${message} ${int.message}`, ...int.points) + ) + ) + + return acc + }, + [] + ) + + return sideIntersections.filter((int) => int.didIntersect) + }, + + // Intersect a rectangle with an arc. + arc( + point: number[], + size: number[], + center: number[], + radius: number, + start: number[], + end: number[] + ): TLIntersection[] { + const sideIntersections = Utils.getRectangleSides(point, size).reduce( + (acc, [message, [a1, a2]]) => { + const intersection = Intersect.arc.lineSegment(center, radius, start, end, a1, a2) + + if (intersection) { + acc.push({ ...intersection, message }) + } + + return acc + }, + [] + ) + + return sideIntersections.filter((int) => int.didIntersect) + }, + + // Intersect a rectangle with a circle. + circle(point: number[], size: number[], c: number[], r: number): TLIntersection[] { + const sideIntersections = Utils.getRectangleSides(point, size).reduce( + (acc, [message, [a1, a2]]) => { + const intersection = Intersect.lineSegment.circle(a1, a2, c, r) + + if (intersection) { + acc.push({ ...intersection, message }) + } + + return acc + }, + [] + ) + + return sideIntersections.filter((int) => int.didIntersect) + }, + + // Intersect a rectangle with an ellipse. + ellipse( + point: number[], + size: number[], + c: number[], + rx: number, + ry: number, + rotation = 0 + ): TLIntersection[] { + const sideIntersections = Utils.getRectangleSides(point, size).reduce( + (acc, [message, [a1, a2]]) => { + const intersection = Intersect.lineSegment.ellipse(a1, a2, c, rx, ry, rotation) + + if (intersection) { + acc.push({ ...intersection, message }) + } + + return acc + }, + [] + ) + + return sideIntersections.filter((int) => int.didIntersect) + }, + + // Intersect a rectangle with a bounding box. + bounds(point: number[], size: number[], bounds: TLBounds): TLIntersection[] { + const { minX, minY, width, height } = bounds + return Intersect.rectangle.rectangle(point, size, [minX, minY], [width, height]) + }, + + // Intersect a rectangle with a polyline + polyline(point: number[], size: number[], points: number[][]): TLIntersection[] { + const sideIntersections = Utils.getRectangleSides(point, size).reduce( + (acc, [message, [a1, a2]]) => { + const intersections = Intersect.lineSegment.polyline(a1, a2, points) + + if (intersections.length > 0) { + acc.push(getIntersection(message, ...intersections.flatMap((i) => i.points))) + } + + return acc + }, + [] + ) + + return sideIntersections.filter((int) => int.didIntersect) + }, + } + + static arc = { + // Intersect an arc with a line segment. + lineSegment( + center: number[], + radius: number, + start: number[], + end: number[], + a1: number[], + a2: number[] + ): TLIntersection { + return Intersect.lineSegment.arc(a1, a2, center, radius, start, end) + }, + + // Intersect an arc with a rectangle. + rectangle( + center: number[], + radius: number, + start: number[], + end: number[], + point: number[], + size: number[] + ): TLIntersection[] { + return Intersect.rectangle.arc(point, size, center, radius, start, end) + }, + + // Intersect an arc with a bounding box. + bounds( + center: number[], + radius: number, + start: number[], + end: number[], + bounds: TLBounds + ): TLIntersection[] { + const { minX, minY, width, height } = bounds + return Intersect.arc.rectangle(center, radius, start, end, [minX, minY], [width, height]) + }, + } + + static circle = { + // Intersect a circle with a line segment. + lineSegment(c: number[], r: number, a1: number[], a2: number[]): TLIntersection { + return Intersect.lineSegment.circle(a1, a2, c, r) + }, + + // Intersect a circle with a circle. + circle(c1: number[], r1: number, c2: number[], r2: number): TLIntersection { + let dx = c2[0] - c1[0], + dy = c2[1] - c1[1] + + const d = Math.sqrt(dx * dx + dy * dy), + x = (d * d - r2 * r2 + r1 * r1) / (2 * d), + y = Math.sqrt(r1 * r1 - x * x) + + dx /= d + dy /= d + + return getIntersection( + 'intersection', + [c1[0] + dx * x - dy * y, c1[1] + dy * x + dx * y], + [c1[0] + dx * x + dy * y, c1[1] + dy * x - dx * y] + ) + }, + + // Intersect a circle with a rectangle. + rectangle(c: number[], r: number, point: number[], size: number[]): TLIntersection[] { + return Intersect.rectangle.circle(point, size, c, r) + }, + + // Intersect a circle with a bounding box. + bounds(c: number[], r: number, bounds: TLBounds): TLIntersection[] { + const { minX, minY, width, height } = bounds + return Intersect.circle.rectangle(c, r, [minX, minY], [width, height]) + }, + } + + static ellipse = { + // Intersect an ellipse with a ray. + ray( + center: number[], + rx: number, + ry: number, + rotation: number, + point: number[], + direction: number[] + ): TLIntersection { + return Intersect.ray.ellipse(point, direction, center, rx, ry, rotation) + }, + + // Intersect an ellipse with a line segment. + lineSegment( + center: number[], + rx: number, + ry: number, + rotation = 0, + a1: number[], + a2: number[] + ): TLIntersection { + if (rx === ry) { + return Intersect.lineSegment.circle(a1, a2, center, rx) + } + + return Intersect.lineSegment.ellipse(a1, a2, center, rx, ry, rotation) + }, + + // Intersect an ellipse with a rectangle. + rectangle( + center: number[], + rx: number, + ry: number, + rotation = 0, + point: number[], + size: number[] + ): TLIntersection[] { + if (rx === ry) { + return Intersect.rectangle.circle(point, size, center, rx) + } + + return Intersect.rectangle.ellipse(point, size, center, rx, ry, rotation) + }, + + // Get an intersection between an ellipse and a second ellipse. + // Adapted from https://gist.github.com/drawable/92792f59b6ff8869d8b1 + ellipse( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _c1: number[], + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _rx1: number, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _ry1: number, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _r1: number, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _c2: number[], + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _rx2: number, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _ry2: number, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _r2: number + ): TLIntersection { + // TODO + return getIntersection('no intersection') + }, + + circle( + c: number[], + rx: number, + ry: number, + rotation: number, + c2: number[], + r2: number + ): TLIntersection { + return Intersect.ellipse.ellipse(c, rx, ry, rotation, c2, r2, r2, 0) + }, + + // Intersect an ellipse with a bounding box. + bounds( + c: number[], + rx: number, + ry: number, + rotation: number, + bounds: TLBounds + ): TLIntersection[] { + const { minX, minY, width, height } = bounds + return Intersect.ellipse.rectangle(c, rx, ry, rotation, [minX, minY], [width, height]) + }, + } + + static bounds = { + ray(bounds: TLBounds, origin: number[], direction: number[]): TLIntersection[] { + const { minX, minY, width, height } = bounds + return Intersect.ray.rectangle(origin, direction, [minX, minY], [width, height]) + }, + + lineSegment(bounds: TLBounds, a1: number[], a2: number[]): TLIntersection[] { + const { minX, minY, width, height } = bounds + return Intersect.lineSegment.rectangle(a1, a2, [minX, minY], [width, height]) + }, + + rectangle(bounds: TLBounds, point: number[], size: number[]): TLIntersection[] { + const { minX, minY, width, height } = bounds + return Intersect.rectangle.rectangle(point, size, [minX, minY], [width, height]) + }, + + bounds(bounds1: TLBounds, bounds2: TLBounds): TLIntersection[] { + return Intersect.rectangle.rectangle( + [bounds1.minX, bounds1.minY], + [bounds1.width, bounds1.height], + [bounds2.minX, bounds2.minY], + [bounds2.width, bounds2.height] + ) + }, + + arc( + bounds: TLBounds, + center: number[], + radius: number, + start: number[], + end: number[] + ): TLIntersection[] { + const { minX, minY, width, height } = bounds + return Intersect.arc.rectangle(center, radius, start, end, [minX, minY], [width, height]) + }, + + circle(bounds: TLBounds, c: number[], r: number): TLIntersection[] { + const { minX, minY, width, height } = bounds + return Intersect.circle.rectangle(c, r, [minX, minY], [width, height]) + }, + + ellipse(bounds: TLBounds, c: number[], rx: number, ry: number, rotation = 0): TLIntersection[] { + const { minX, minY, width, height } = bounds + return Intersect.ellipse.rectangle(c, rx, ry, rotation, [minX, minY], [width, height]) + }, + + polyline(bounds: TLBounds, points: number[][]): TLIntersection[] { + return Intersect.polyline.bounds(points, bounds) + }, + } + + static polyline = { + // Intersect a polyline with a line segment. + lineSegment(points: number[][], a1: number[], a2: number[]): TLIntersection[] { + return Intersect.lineSegment.polyline(a1, a2, points) + }, + + // Interesct a polyline with a rectangle. + rectangle(points: number[][], point: number[], size: number[]): TLIntersection[] { + return Intersect.rectangle.polyline(point, size, points) + }, + + // Intersect a polyline with a bounding box. + bounds(points: number[][], bounds: TLBounds): TLIntersection[] { + return Intersect.rectangle.polyline( + [bounds.minX, bounds.minY], + [bounds.width, bounds.height], + points + ) + }, + } +} + +export default Intersect diff --git a/packages/core/src/utils/polyfills.ts b/packages/core/src/utils/polyfills.ts new file mode 100644 index 000000000..c86244231 --- /dev/null +++ b/packages/core/src/utils/polyfills.ts @@ -0,0 +1,21 @@ +/* eslint-disable @typescript-eslint/ban-ts-comment */ +/* eslint-disable no-extend-native */ + +/** + * String.prototype.replaceAll() polyfill + * https://gomakethings.com/how-to-replace-a-section-of-a-string-with-another-one-with-vanilla-js/ + * @author Chris Ferdinandi + * @license MIT + */ +if (!String.prototype.replaceAll) { + // @ts-ignore + String.prototype.replaceAll = function (str: string, newStr: string) { + // If a regex pattern + if (Object.prototype.toString.call(str).toLowerCase() === '[object regexp]') { + return this.replace(str, newStr) + } + + // If a string + return this.replace(new RegExp(str, 'g'), newStr) + } +} diff --git a/utils/svg.ts b/packages/core/src/utils/svg.ts similarity index 84% rename from utils/svg.ts rename to packages/core/src/utils/svg.ts index 01c945661..b8e6aefb2 100644 --- a/utils/svg.ts +++ b/packages/core/src/utils/svg.ts @@ -1,9 +1,8 @@ -// Some helpers for drawing SVGs. -import { getSweep } from 'utils' +import { Utils } from './utils' // General -export default class Svg { +export class Svg { static ellipse = (A: number[], r: number): string => { return `M ${A[0] - r},${A[1]} a ${r},${r} 0 1,0 ${r * 2},0 @@ -41,8 +40,8 @@ export default class Svg { r, r, 0, - getSweep(C, A, B) > 0 ? '1' : '0', 0, + Utils.getArcLength(C, r, A, B) > 0 ? '1' : '0', B[0], B[1], ].join(' ') @@ -56,11 +55,10 @@ export default class Svg { return ['R', A[0], A[1]].join(' ') } - static getPointAtLength = ( - path: SVGPathElement, - length: number - ): number[] => { + static getPointAtLength = (path: SVGPathElement, length: number): number[] => { const point = path.getPointAtLength(length) return [point.x, point.y] } } + +export default Svg diff --git a/packages/core/src/utils/utils.ts b/packages/core/src/utils/utils.ts new file mode 100644 index 000000000..6dd388cde --- /dev/null +++ b/packages/core/src/utils/utils.ts @@ -0,0 +1,1731 @@ +/* eslint-disable @typescript-eslint/no-extra-semi */ +/* eslint-disable @typescript-eslint/ban-types */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable no-redeclare */ +import type React from 'react' +import deepmerge from 'deepmerge' +import { TLBezierCurveSegment, TLBounds, TLBoundsCorner, TLBoundsEdge } from '../types' +import vec from './vec' +import './polyfills' + +export class Utils { + /* -------------------------------------------------- */ + /* Math & Geometry */ + /* -------------------------------------------------- */ + + static filterObject( + obj: T, + fn: (entry: Entry, i?: number, arr?: Entry[]) => boolean + ) { + return Object.fromEntries((Object.entries(obj) as Entry[]).filter(fn)) as Partial + } + + static deepMerge(target: T, source: any): T { + return deepmerge(target, source, { arrayMerge: (a, b) => b, clone: false }) + + // const result = {} as T + + // for (const key of Object.keys(result)) { + // const tprop = target[key as keyof T] + // const sprop = source[key] + // if (tprop === sprop) { + // continue + // } else if (!(key in target) || target[key as keyof T] === undefined) { + // result[key as keyof T] = sprop + // } else if (!(key in source)) { + // continue + // } else if (source[key as keyof T] === undefined) { + // delete result[key as keyof T] + // } else { + // if (typeof tprop === 'object' && typeof sprop === 'object') { + // result[key as keyof T] = this.deepMerge(tprop, sprop) + // } else { + // result[key as keyof T] = sprop + // } + // } + // } + + // return result + } + + /** + * Linear interpolation betwen two numbers. + * @param y1 + * @param y2 + * @param mu + */ + static lerp(y1: number, y2: number, mu: number): number { + mu = Utils.clamp(mu, 0, 1) + return y1 * (1 - mu) + y2 * mu + } + + /** + * Linear interpolation between two colors. + * + * ### Example + * + *```ts + * lerpColor("#000000", "#0099FF", .25) + *``` + */ + + static lerpColor(color1: string, color2: string, factor = 0.5): string | undefined { + function h2r(hex: string) { + const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex) + return result + ? [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)] + : null + } + + function r2h(rgb: number[]) { + return '#' + ((1 << 24) + (rgb[0] << 16) + (rgb[1] << 8) + rgb[2]).toString(16).slice(1) + } + + const c1 = h2r(color1) || [0, 0, 0] + const c2 = h2r(color2) || [0, 0, 0] + + const result = c1.slice() + + for (let i = 0; i < 3; i++) { + result[i] = Math.round(result[i] + factor * (c2[i] - c1[i])) + } + + return r2h(result) + } + + /** + * Modulate a value between two ranges. + * @param value + * @param rangeA from [low, high] + * @param rangeB to [low, high] + * @param clamp + */ + static modulate(value: number, rangeA: number[], rangeB: number[], clamp = false): number { + const [fromLow, fromHigh] = rangeA + const [v0, v1] = rangeB + const result = v0 + ((value - fromLow) / (fromHigh - fromLow)) * (v1 - v0) + + return clamp + ? v0 < v1 + ? Math.max(Math.min(result, v1), v0) + : Math.max(Math.min(result, v0), v1) + : result + } + + /** + * Clamp a value into a range. + * @param n + * @param min + */ + static clamp(n: number, min: number): number + static clamp(n: number, min: number, max: number): number + static clamp(n: number, min: number, max?: number): number { + return Math.max(min, typeof max !== 'undefined' ? Math.min(n, max) : n) + } + + // TODO: replace with a string compression algorithm + static compress(s: string): string { + return s + } + + // TODO: replace with a string decompression algorithm + static decompress(s: string): string { + return s + } + + /** + * Recursively clone an object or array. + * @param obj + */ + static deepClone(obj: T): T { + if (obj === null) return obj + + if (Array.isArray(obj)) { + return [...obj] as T + } + + if (typeof obj === 'object') { + const clone = { ...(obj as Record) } + + Object.keys(clone).forEach( + (key) => + (clone[key] = + typeof obj[key as keyof T] === 'object' + ? Utils.deepClone(obj[key as keyof T]) + : obj[key as keyof T]) + ) + + return clone as T + } + + return obj + } + + /** + * Seeded random number generator, using [xorshift](https://en.wikipedia.org/wiki/Xorshift). + * The result will always be betweeen -1 and 1. + * + * Adapted from [seedrandom](https://github.com/davidbau/seedrandom). + */ + static rng(seed = ''): () => number { + let x = 0 + let y = 0 + let z = 0 + let w = 0 + + function next() { + const t = x ^ (x << 11) + x = y + y = z + z = w + w ^= ((w >>> 19) ^ t ^ (t >>> 8)) >>> 0 + return w / 0x100000000 + } + + for (let k = 0; k < seed.length + 64; k++) { + x ^= seed.charCodeAt(k) | 0 + next() + } + + return next + } + + /* ---------------------- Boxes --------------------- */ + + static getRectangleSides(point: number[], size: number[], rotation = 0): [string, number[][]][] { + const center = [point[0] + size[0] / 2, point[1] + size[1] / 2] + const tl = vec.rotWith(point, center, rotation) + const tr = vec.rotWith(vec.add(point, [size[0], 0]), center, rotation) + const br = vec.rotWith(vec.add(point, size), center, rotation) + const bl = vec.rotWith(vec.add(point, [0, size[1]]), center, rotation) + + return [ + ['top', [tl, tr]], + ['right', [tr, br]], + ['bottom', [br, bl]], + ['left', [bl, tl]], + ] + } + + static getBoundsSides(bounds: TLBounds): [string, number[][]][] { + return this.getRectangleSides([bounds.minX, bounds.minY], [bounds.width, bounds.height]) + } + + static shallowEqual>(objA: T, objB: T): boolean { + if (objA === objB) return true + + if (!objA || !objB) return false + + const aKeys = Object.keys(objA) + const bKeys = Object.keys(objB) + const len = aKeys.length + + if (bKeys.length !== len) return false + + for (let i = 0; i < len; i++) { + const key = aKeys[i] + + if (objA[key] !== objB[key] || !Object.prototype.hasOwnProperty.call(objB, key)) { + return false + } + } + + return true + } + + /* --------------- Circles and Angles --------------- */ + + /** + * Get the outer of between a circle and a point. + * @param C The circle's center. + * @param r The circle's radius. + * @param P The point. + * @param side + */ + static getCircleTangentToPoint( + C: number[], + r: number, + P: number[], + side: number + ): number[] | null { + const B = vec.lrp(C, P, 0.5) + const r1 = vec.dist(C, B) + const delta = vec.sub(B, C) + const d = vec.len(delta) + + if (!(d <= r + r1 && d >= Math.abs(r - r1))) { + return null + } + + const a = (r * r - r1 * r1 + d * d) / (2.0 * d) + const n = 1 / d + const p = vec.add(C, vec.mul(delta, a * n)) + const h = Math.sqrt(r * r - a * a) + const k = vec.mul(vec.per(delta), h * n) + + return side === 0 ? vec.add(p, k) : vec.sub(p, k) + } + + /** + * Get outer tangents of two circles. + * @param x0 + * @param y0 + * @param r0 + * @param x1 + * @param y1 + * @param r1 + * @returns [lx0, ly0, lx1, ly1, rx0, ry0, rx1, ry1] + */ + static getOuterTangentsOfCircles( + C0: number[], + r0: number, + C1: number[], + r1: number + ): number[][] | null { + const a0 = vec.angle(C0, C1) + const d = vec.dist(C0, C1) + + // Circles are overlapping, no tangents + if (d < Math.abs(r1 - r0)) { + return null + } + + const a1 = Math.acos((r0 - r1) / d) + const t0 = a0 + a1 + const t1 = a0 - a1 + + return [ + [C0[0] + r0 * Math.cos(t1), C0[1] + r0 * Math.sin(t1)], + [C1[0] + r1 * Math.cos(t1), C1[1] + r1 * Math.sin(t1)], + [C0[0] + r0 * Math.cos(t0), C0[1] + r0 * Math.sin(t0)], + [C1[0] + r1 * Math.cos(t0), C1[1] + r1 * Math.sin(t0)], + ] + } + + /** + * Get the closest point on the perimeter of a circle to a given point. + * @param C The circle's center. + * @param r The circle's radius. + * @param P The point. + */ + static getClosestPointOnCircle(C: number[], r: number, P: number[]): number[] { + const v = vec.sub(C, P) + return vec.sub(C, vec.mul(vec.div(v, vec.len(v)), r)) + } + + /** + * Get a circle from three points. + * @param A + * @param B + * @param C + * @returns [x, y, r] + */ + static circleFromThreePoints(A: number[], B: number[], C: number[]): number[] { + const [x1, y1] = A + const [x2, y2] = B + const [x3, y3] = C + + const a = x1 * (y2 - y3) - y1 * (x2 - x3) + x2 * y3 - x3 * y2 + + const b = + (x1 * x1 + y1 * y1) * (y3 - y2) + + (x2 * x2 + y2 * y2) * (y1 - y3) + + (x3 * x3 + y3 * y3) * (y2 - y1) + + const c = + (x1 * x1 + y1 * y1) * (x2 - x3) + + (x2 * x2 + y2 * y2) * (x3 - x1) + + (x3 * x3 + y3 * y3) * (x1 - x2) + + const x = -b / (2 * a) + + const y = -c / (2 * a) + + return [x, y, Math.hypot(x - x1, y - y1)] + } + + /** + * Find the approximate perimeter of an ellipse. + * @param rx + * @param ry + */ + static perimeterOfEllipse(rx: number, ry: number): number { + const h = Math.pow(rx - ry, 2) / Math.pow(rx + ry, 2) + const p = Math.PI * (rx + ry) * (1 + (3 * h) / (10 + Math.sqrt(4 - 3 * h))) + return p + } + + /** + * Get the short angle distance between two angles. + * @param a0 + * @param a1 + */ + static shortAngleDist(a0: number, a1: number): number { + const max = Math.PI * 2 + const da = (a1 - a0) % max + return ((2 * da) % max) - da + } + + /** + * Get the long angle distance between two angles. + * @param a0 + * @param a1 + */ + static longAngleDist(a0: number, a1: number): number { + return Math.PI * 2 - Utils.shortAngleDist(a0, a1) + } + + /** + * Interpolate an angle between two angles. + * @param a0 + * @param a1 + * @param t + */ + static lerpAngles(a0: number, a1: number, t: number): number { + return a0 + Utils.shortAngleDist(a0, a1) * t + } + + /** + * Get the short distance between two angles. + * @param a0 + * @param a1 + */ + static angleDelta(a0: number, a1: number): number { + return Utils.shortAngleDist(a0, a1) + } + + /** + * Get the "sweep" or short distance between two points on a circle's perimeter. + * @param C + * @param A + * @param B + */ + static getSweep(C: number[], A: number[], B: number[]): number { + return Utils.angleDelta(vec.angle(C, A), vec.angle(C, B)) + } + + /** + * Rotate a point around a center. + * @param x The x-axis coordinate of the point. + * @param y The y-axis coordinate of the point. + * @param cx The x-axis coordinate of the point to rotate round. + * @param cy The y-axis coordinate of the point to rotate round. + * @param angle The distance (in radians) to rotate. + */ + static rotatePoint(A: number[], B: number[], angle: number): number[] { + const s = Math.sin(angle) + const c = Math.cos(angle) + + const px = A[0] - B[0] + const py = A[1] - B[1] + + const nx = px * c - py * s + const ny = px * s + py * c + + return [nx + B[0], ny + B[1]] + } + + /** + * Clamp radians within 0 and 2PI + * @param r + */ + static clampRadians(r: number): number { + return (Math.PI * 2 + r) % (Math.PI * 2) + } + + /** + * Clamp rotation to even segments. + * @param r + * @param segments + */ + static clampToRotationToSegments(r: number, segments: number): number { + const seg = (Math.PI * 2) / segments + return Math.floor((Utils.clampRadians(r) + seg / 2) / seg) * seg + } + + /** + * Is angle c between angles a and b? + * @param a + * @param b + * @param c + */ + static isAngleBetween(a: number, b: number, c: number): boolean { + if (c === a || c === b) return true + const PI2 = Math.PI * 2 + const AB = (b - a + PI2) % PI2 + const AC = (c - a + PI2) % PI2 + return AB <= Math.PI !== AC > AB + } + + /** + * Convert degrees to radians. + * @param d + */ + static degreesToRadians(d: number): number { + return (d * Math.PI) / 180 + } + + /** + * Convert radians to degrees. + * @param r + */ + static radiansToDegrees(r: number): number { + return (r * 180) / Math.PI + } + + /** + * Get the length of an arc between two points on a circle's perimeter. + * @param C + * @param r + * @param A + * @param B + */ + static getArcLength(C: number[], r: number, A: number[], B: number[]): number { + const sweep = Utils.getSweep(C, A, B) + return r * (2 * Math.PI) * (sweep / (2 * Math.PI)) + } + + /** + * Get a dash offset for an arc, based on its length. + * @param C + * @param r + * @param A + * @param B + * @param step + */ + static getArcDashOffset(C: number[], r: number, A: number[], B: number[], step: number): number { + const del0 = Utils.getSweep(C, A, B) + const len0 = Utils.getArcLength(C, r, A, B) + const off0 = del0 < 0 ? len0 : 2 * Math.PI * C[2] - len0 + return -off0 / 2 + step + } + + /** + * Get a dash offset for an ellipse, based on its length. + * @param A + * @param step + */ + static getEllipseDashOffset(A: number[], step: number): number { + const c = 2 * Math.PI * A[2] + return -c / 2 + -step + } + + /* --------------- Curves and Splines --------------- */ + + /** + * Get bezier curve segments that pass through an array of points. + * @param points + * @param tension + */ + static getTLBezierCurveSegments(points: number[][], tension = 0.4): TLBezierCurveSegment[] { + const len = points.length + const cpoints: number[][] = [...points] + + if (len < 2) { + throw Error('Curve must have at least two points.') + } + + for (let i = 1; i < len - 1; i++) { + const p0 = points[i - 1] + const p1 = points[i] + const p2 = points[i + 1] + + const pdx = p2[0] - p0[0] + const pdy = p2[1] - p0[1] + const pd = Math.hypot(pdx, pdy) + const nx = pdx / pd // normalized x + const ny = pdy / pd // normalized y + const dp = Math.hypot(p1[0] - p0[0], p1[1] - p0[1]) // Distance to previous + const dn = Math.hypot(p1[0] - p2[0], p1[1] - p2[1]) // Distance to next + + cpoints[i] = [ + // tangent start + p1[0] - nx * dp * tension, + p1[1] - ny * dp * tension, + // tangent end + p1[0] + nx * dn * tension, + p1[1] + ny * dn * tension, + // normal + nx, + ny, + ] + } + + // TODO: Reflect the nearest control points, not average them + const d0 = Math.hypot(points[0][0] + cpoints[1][0]) + cpoints[0][2] = (points[0][0] + cpoints[1][0]) / 2 + cpoints[0][3] = (points[0][1] + cpoints[1][1]) / 2 + cpoints[0][4] = (cpoints[1][0] - points[0][0]) / d0 + cpoints[0][5] = (cpoints[1][1] - points[0][1]) / d0 + + const d1 = Math.hypot(points[len - 1][1] + cpoints[len - 1][1]) + cpoints[len - 1][0] = (points[len - 1][0] + cpoints[len - 2][2]) / 2 + cpoints[len - 1][1] = (points[len - 1][1] + cpoints[len - 2][3]) / 2 + cpoints[len - 1][4] = (cpoints[len - 2][2] - points[len - 1][0]) / -d1 + cpoints[len - 1][5] = (cpoints[len - 2][3] - points[len - 1][1]) / -d1 + + const results: TLBezierCurveSegment[] = [] + + for (let i = 1; i < cpoints.length; i++) { + results.push({ + start: points[i - 1].slice(0, 2), + tangentStart: cpoints[i - 1].slice(2, 4), + normalStart: cpoints[i - 1].slice(4, 6), + pressureStart: 2 + ((i - 1) % 2 === 0 ? 1.5 : 0), + end: points[i].slice(0, 2), + tangentEnd: cpoints[i].slice(0, 2), + normalEnd: cpoints[i].slice(4, 6), + pressureEnd: 2 + (i % 2 === 0 ? 1.5 : 0), + }) + } + + return results + } + + /** + * Find a point along a curve segment, via pomax. + * @param t + * @param points [cpx1, cpy1, cpx2, cpy2, px, py][] + */ + static computePointOnCurve(t: number, points: number[][]): number[] { + // shortcuts + if (t === 0) { + return points[0] + } + + const order = points.length - 1 + + if (t === 1) { + return points[order] + } + + const mt = 1 - t + let p = points // constant? + + if (order === 0) { + return points[0] + } // linear? + + if (order === 1) { + return [mt * p[0][0] + t * p[1][0], mt * p[0][1] + t * p[1][1]] + } // quadratic/cubic curve? + + // if (order < 4) { + const mt2 = mt * mt + const t2 = t * t + + let a: number + let b: number + let c: number + let d = 0 + + if (order === 2) { + p = [p[0], p[1], p[2], [0, 0]] + a = mt2 + b = mt * t * 2 + c = t2 + // } else if (order === 3) { + } else { + a = mt2 * mt + b = mt2 * t * 3 + c = mt * t2 * 3 + d = t * t2 + } + + return [ + a * p[0][0] + b * p[1][0] + c * p[2][0] + d * p[3][0], + a * p[0][1] + b * p[1][1] + c * p[2][1] + d * p[3][1], + ] + // } // higher order curves: use de Casteljau's computation + } + + /** + * Evaluate a 2d cubic bezier at a point t on the x axis. + * @param tx + * @param x1 + * @param y1 + * @param x2 + * @param y2 + */ + static cubicBezier(tx: number, x1: number, y1: number, x2: number, y2: number): number { + // Inspired by Don Lancaster's two articles + // http://www.tinaja.com/glib/cubemath.pdf + // http://www.tinaja.com/text/bezmath.html + + // Set start and end point + const x0 = 0 + const y0 = 0 + const x3 = 1 + const y3 = 1 + // Convert the coordinates to equation space + const A = x3 - 3 * x2 + 3 * x1 - x0 + const B = 3 * x2 - 6 * x1 + 3 * x0 + const C = 3 * x1 - 3 * x0 + const D = x0 + const E = y3 - 3 * y2 + 3 * y1 - y0 + const F = 3 * y2 - 6 * y1 + 3 * y0 + const G = 3 * y1 - 3 * y0 + const H = y0 + // Variables for the loop below + const iterations = 5 + + let i: number + let slope: number + let x: number + let t = tx + + // Loop through a few times to get a more accurate time value, according to the Newton-Raphson method + // http://en.wikipedia.org/wiki/Newton's_method + for (i = 0; i < iterations; i++) { + // The curve's x equation for the current time value + x = A * t * t * t + B * t * t + C * t + D + + // The slope we want is the inverse of the derivate of x + slope = 1 / (3 * A * t * t + 2 * B * t + C) + + // Get the next estimated time value, which will be more accurate than the one before + t -= (x - tx) * slope + t = t > 1 ? 1 : t < 0 ? 0 : t + } + + // Find the y value through the curve's y equation, with the now more accurate time value + return Math.abs(E * t * t * t + F * t * t + G * t * H) + } + + /** + * Get a bezier curve data for a spline that fits an array of points. + * @param points An array of points formatted as [x, y] + * @param k Tension + */ + static getSpline( + pts: number[][], + k = 0.5 + ): { + cp1x: number + cp1y: number + cp2x: number + cp2y: number + px: number + py: number + }[] { + let p0: number[] + let [p1, p2, p3] = pts + + const results: { + cp1x: number + cp1y: number + cp2x: number + cp2y: number + px: number + py: number + }[] = [] + + for (let i = 1, len = pts.length; i < len; i++) { + p0 = p1 + p1 = p2 + p2 = p3 + p3 = pts[i + 2] ? pts[i + 2] : p2 + + results.push({ + cp1x: p1[0] + ((p2[0] - p0[0]) / 6) * k, + cp1y: p1[1] + ((p2[1] - p0[1]) / 6) * k, + cp2x: p2[0] - ((p3[0] - p1[0]) / 6) * k, + cp2y: p2[1] - ((p3[1] - p1[1]) / 6) * k, + px: pts[i][0], + py: pts[i][1], + }) + } + + return results + } + + /** + * Get a bezier curve data for a spline that fits an array of points. + * @param pts + * @param tension + * @param isClosed + * @param numOfSegments + */ + static getCurvePoints( + pts: number[][], + tension = 0.5, + isClosed = false, + numOfSegments = 3 + ): number[][] { + const _pts = [...pts] + const len = pts.length + const res: number[][] = [] // results + + let t1x: number, // tension vectors + t2x: number, + t1y: number, + t2y: number, + c1: number, // cardinal points + c2: number, + c3: number, + c4: number, + st: number, + st2: number, + st3: number + + // The algorithm require a previous and next point to the actual point array. + // Check if we will draw closed or open curve. + // If closed, copy end points to beginning and first points to end + // If open, duplicate first points to befinning, end points to end + if (isClosed) { + _pts.unshift(_pts[len - 1]) + _pts.push(_pts[0]) + } else { + // copy 1. point and insert at beginning + _pts.unshift(_pts[0]) + _pts.push(_pts[len - 1]) + // _pts.push(_pts[len - 1]) + } + + // For each point, calculate a segment + for (let i = 1; i < _pts.length - 2; i++) { + // Calculate points along segment and add to results + for (let t = 0; t <= numOfSegments; t++) { + // Step + st = t / numOfSegments + st2 = Math.pow(st, 2) + st3 = Math.pow(st, 3) + + // Cardinals + c1 = 2 * st3 - 3 * st2 + 1 + c2 = -(2 * st3) + 3 * st2 + c3 = st3 - 2 * st2 + st + c4 = st3 - st2 + + // Tension + t1x = (_pts[i + 1][0] - _pts[i - 1][0]) * tension + t2x = (_pts[i + 2][0] - _pts[i][0]) * tension + t1y = (_pts[i + 1][1] - _pts[i - 1][1]) * tension + t2y = (_pts[i + 2][1] - _pts[i][1]) * tension + + // Control points + res.push([ + c1 * _pts[i][0] + c2 * _pts[i + 1][0] + c3 * t1x + c4 * t2x, + c1 * _pts[i][1] + c2 * _pts[i + 1][1] + c3 * t1y + c4 * t2y, + ]) + } + } + + res.push(pts[pts.length - 1]) + + return res + } + + /** + * Simplify a line (using Ramer-Douglas-Peucker algorithm). + * @param points An array of points as [x, y, ...][] + * @param tolerance The minimum line distance (also called epsilon). + * @returns Simplified array as [x, y, ...][] + */ + static simplify(points: number[][], tolerance = 1): number[][] { + const len = points.length + const a = points[0] + const b = points[len - 1] + const [x1, y1] = a + const [x2, y2] = b + + if (len > 2) { + let distance = 0 + let index = 0 + const max = Math.hypot(y2 - y1, x2 - x1) + + for (let i = 1; i < len - 1; i++) { + const [x0, y0] = points[i] + const d = Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) / max + + if (distance > d) continue + + distance = d + index = i + } + + if (distance > tolerance) { + const l0 = Utils.simplify(points.slice(0, index + 1), tolerance) + const l1 = Utils.simplify(points.slice(index + 1), tolerance) + return l0.concat(l1.slice(1)) + } + } + + return [a, b] + } + + /** + * Get whether a point is inside of a circle. + * @param A + * @param b + * @returns + */ + static pointInCircle(A: number[], C: number[], r: number): boolean { + return vec.dist(A, C) <= r + } + + /** + * Get whether a point is inside of an ellipse. + * @param point + * @param center + * @param rx + * @param ry + * @param rotation + * @returns + */ + static pointInEllipse(A: number[], C: number[], rx: number, ry: number, rotation = 0): boolean { + rotation = rotation || 0 + const cos = Math.cos(rotation) + const sin = Math.sin(rotation) + const delta = vec.sub(A, C) + const tdx = cos * delta[0] + sin * delta[1] + const tdy = sin * delta[0] - cos * delta[1] + + return (tdx * tdx) / (rx * rx) + (tdy * tdy) / (ry * ry) <= 1 + } + + /** + * Get whether a point is inside of a rectangle. + * @param point + * @param size + */ + static pointInRect(point: number[], size: number[]): boolean { + return !( + point[0] < size[0] || + point[0] > point[0] + size[0] || + point[1] < size[1] || + point[1] > point[1] + size[1] + ) + } + + static pointInPolygon(p: number[], points: number[][]): boolean { + let wn = 0 // winding number + + points.forEach((a, i) => { + const b = points[(i + 1) % points.length] + if (a[1] <= p[1]) { + if (b[1] > p[1] && vec.cross(a, b, p) > 0) { + wn += 1 + } + } else if (b[1] <= p[1] && vec.cross(a, b, p) < 0) { + wn -= 1 + } + }) + + return wn !== 0 + } + + /* --------------------- Bounds --------------------- */ + + /** + * Expand a bounding box by a delta. + * + * ### Example + * + *```ts + * expandBounds(myBounds, [100, 100]) + *``` + */ + static expandBounds(bounds: TLBounds, delta: number): TLBounds { + return { + minX: bounds.minX - delta, + minY: bounds.minY - delta, + maxX: bounds.maxX + delta, + maxY: bounds.maxY + delta, + width: bounds.width + delta * 2, + height: bounds.height + delta * 2, + } + } + + /** + * Get whether a point is inside of a bounds. + * @param A + * @param b + * @returns + */ + static pointInBounds(A: number[], b: TLBounds): boolean { + return !(A[0] < b.minX || A[0] > b.maxX || A[1] < b.minY || A[1] > b.maxY) + } + + /** + * Get whether two bounds collide. + * @param a Bounds + * @param b Bounds + * @returns + */ + static boundsCollide(a: TLBounds, b: TLBounds): boolean { + return !(a.maxX < b.minX || a.minX > b.maxX || a.maxY < b.minY || a.minY > b.maxY) + } + + /** + * Get whether the bounds of A contain the bounds of B. A perfect match will return true. + * @param a Bounds + * @param b Bounds + * @returns + */ + static boundsContain(a: TLBounds, b: TLBounds): boolean { + return a.minX < b.minX && a.minY < b.minY && a.maxY > b.maxY && a.maxX > b.maxX + } + + /** + * Get whether the bounds of A are contained by the bounds of B. + * @param a Bounds + * @param b Bounds + * @returns + */ + static boundsContained(a: TLBounds, b: TLBounds): boolean { + return Utils.boundsContain(b, a) + } + + /** + * Get whether two bounds are identical. + * @param a Bounds + * @param b Bounds + * @returns + */ + static boundsAreEqual(a: TLBounds, b: TLBounds): boolean { + return !(b.maxX !== a.maxX || b.minX !== a.minX || b.maxY !== a.maxY || b.minY !== a.minY) + } + + /** + * Find a bounding box from an array of points. + * @param points + * @param rotation (optional) The bounding box's rotation. + */ + static getBoundsFromPoints(points: number[][], rotation = 0): TLBounds { + let minX = Infinity + let minY = Infinity + let maxX = -Infinity + let maxY = -Infinity + + if (points.length < 2) { + minX = 0 + minY = 0 + maxX = 1 + maxY = 1 + } else { + for (const [x, y] of points) { + minX = Math.min(x, minX) + minY = Math.min(y, minY) + maxX = Math.max(x, maxX) + maxY = Math.max(y, maxY) + } + } + + if (rotation !== 0) { + return Utils.getBoundsFromPoints( + points.map((pt) => vec.rotWith(pt, [(minX + maxX) / 2, (minY + maxY) / 2], rotation)) + ) + } + + return { + minX, + minY, + maxX, + maxY, + width: Math.max(1, maxX - minX), + height: Math.max(1, maxY - minY), + } + } + + /** + * Center a bounding box around a given point. + * @param bounds + * @param center + */ + static centerBounds(bounds: TLBounds, point: number[]): TLBounds { + const boundsCenter = this.getBoundsCenter(bounds) + const dx = point[0] - boundsCenter[0] + const dy = point[1] - boundsCenter[1] + return this.translateBounds(bounds, [dx, dy]) + } + + /** + * Move a bounding box without recalculating it. + * @param bounds + * @param delta + * @returns + */ + static translateBounds(bounds: TLBounds, delta: number[]): TLBounds { + return { + minX: bounds.minX + delta[0], + minY: bounds.minY + delta[1], + maxX: bounds.maxX + delta[0], + maxY: bounds.maxY + delta[1], + width: bounds.width, + height: bounds.height, + } + } + + /** + * Rotate a bounding box. + * @param bounds + * @param center + * @param rotation + */ + static rotateBounds(bounds: TLBounds, center: number[], rotation: number): TLBounds { + const [minX, minY] = vec.rotWith([bounds.minX, bounds.minY], center, rotation) + const [maxX, maxY] = vec.rotWith([bounds.maxX, bounds.maxY], center, rotation) + + return { + minX, + minY, + maxX, + maxY, + width: bounds.width, + height: bounds.height, + } + } + + /** + * Get the rotated bounds of an ellipse. + * @param x + * @param y + * @param rx + * @param ry + * @param rotation + */ + static getRotatedEllipseBounds( + x: number, + y: number, + rx: number, + ry: number, + rotation: number + ): TLBounds { + const c = Math.cos(rotation) + const s = Math.sin(rotation) + const w = Math.hypot(rx * c, ry * s) + const h = Math.hypot(rx * s, ry * c) + + return { + minX: x + rx - w, + minY: y + ry - h, + maxX: x + rx + w, + maxY: y + ry + h, + width: w * 2, + height: h * 2, + } + } + + /** + * Get a bounding box that includes two bounding boxes. + * @param a Bounding box + * @param b Bounding box + * @returns + */ + static getExpandedBounds(a: TLBounds, b: TLBounds): TLBounds { + const minX = Math.min(a.minX, b.minX) + const minY = Math.min(a.minY, b.minY) + const maxX = Math.max(a.maxX, b.maxX) + const maxY = Math.max(a.maxY, b.maxY) + const width = Math.abs(maxX - minX) + const height = Math.abs(maxY - minY) + + return { minX, minY, maxX, maxY, width, height } + } + + /** + * Get the common bounds of a group of bounds. + * @returns + */ + static getCommonBounds(bounds: TLBounds[]): TLBounds { + if (bounds.length < 2) return bounds[0] + + let result = bounds[0] + + for (let i = 1; i < bounds.length; i++) { + result = Utils.getExpandedBounds(result, bounds[i]) + } + + return result + } + + static getRotatedCorners(b: TLBounds, rotation = 0): number[][] { + const center = [b.minX + b.width / 2, b.minY + b.height / 2] + + return [ + [b.minX, b.minY], + [b.maxX, b.minY], + [b.maxX, b.maxY], + [b.minX, b.maxY], + ].map((point) => vec.rotWith(point, center, rotation)) + } + + static getTransformedBoundingBox( + bounds: TLBounds, + handle: TLBoundsCorner | TLBoundsEdge | 'center', + delta: number[], + rotation = 0, + isAspectRatioLocked = false + ): TLBounds & { scaleX: number; scaleY: number } { + // Create top left and bottom right corners. + const [ax0, ay0] = [bounds.minX, bounds.minY] + const [ax1, ay1] = [bounds.maxX, bounds.maxY] + + // Create a second set of corners for the new box. + let [bx0, by0] = [bounds.minX, bounds.minY] + let [bx1, by1] = [bounds.maxX, bounds.maxY] + + // If the drag is on the center, just translate the bounds. + if (handle === 'center') { + return { + minX: bx0 + delta[0], + minY: by0 + delta[1], + maxX: bx1 + delta[0], + maxY: by1 + delta[1], + width: bx1 - bx0, + height: by1 - by0, + scaleX: 1, + scaleY: 1, + } + } + + // Counter rotate the delta. This lets us make changes as if + // the (possibly rotated) boxes were axis aligned. + const [dx, dy] = vec.rot(delta, -rotation) + + /* +1. Delta + +Use the delta to adjust the new box by changing its corners. +The dragging handle (corner or edge) will determine which +corners should change. +*/ + switch (handle) { + case TLBoundsEdge.Top: + case TLBoundsCorner.TopLeft: + case TLBoundsCorner.TopRight: { + by0 += dy + break + } + case TLBoundsEdge.Bottom: + case TLBoundsCorner.BottomLeft: + case TLBoundsCorner.BottomRight: { + by1 += dy + break + } + } + + switch (handle) { + case TLBoundsEdge.Left: + case TLBoundsCorner.TopLeft: + case TLBoundsCorner.BottomLeft: { + bx0 += dx + break + } + case TLBoundsEdge.Right: + case TLBoundsCorner.TopRight: + case TLBoundsCorner.BottomRight: { + bx1 += dx + break + } + } + + const aw = ax1 - ax0 + const ah = ay1 - ay0 + + const scaleX = (bx1 - bx0) / aw + const scaleY = (by1 - by0) / ah + + const flipX = scaleX < 0 + const flipY = scaleY < 0 + + const bw = Math.abs(bx1 - bx0) + const bh = Math.abs(by1 - by0) + + /* +2. Aspect ratio + +If the aspect ratio is locked, adjust the corners so that the +new box's aspect ratio matches the original aspect ratio. +*/ + + if (isAspectRatioLocked) { + const ar = aw / ah + const isTall = ar < bw / bh + const tw = bw * (scaleY < 0 ? 1 : -1) * (1 / ar) + const th = bh * (scaleX < 0 ? 1 : -1) * ar + + switch (handle) { + case TLBoundsCorner.TopLeft: { + if (isTall) by0 = by1 + tw + else bx0 = bx1 + th + break + } + case TLBoundsCorner.TopRight: { + if (isTall) by0 = by1 + tw + else bx1 = bx0 - th + break + } + case TLBoundsCorner.BottomRight: { + if (isTall) by1 = by0 - tw + else bx1 = bx0 - th + break + } + case TLBoundsCorner.BottomLeft: { + if (isTall) by1 = by0 - tw + else bx0 = bx1 + th + break + } + case TLBoundsEdge.Bottom: + case TLBoundsEdge.Top: { + const m = (bx0 + bx1) / 2 + const w = bh * ar + bx0 = m - w / 2 + bx1 = m + w / 2 + break + } + case TLBoundsEdge.Left: + case TLBoundsEdge.Right: { + const m = (by0 + by1) / 2 + const h = bw / ar + by0 = m - h / 2 + by1 = m + h / 2 + break + } + } + } + + /* +3. Rotation + +If the bounds are rotated, get a vector from the rotated anchor +corner in the inital bounds to the rotated anchor corner in the +result's bounds. Subtract this vector from the result's corners, +so that the two anchor points (initial and result) will be equal. +*/ + + if (rotation % (Math.PI * 2) !== 0) { + let cv = [0, 0] + + const c0 = vec.med([ax0, ay0], [ax1, ay1]) + const c1 = vec.med([bx0, by0], [bx1, by1]) + + switch (handle) { + case TLBoundsCorner.TopLeft: { + cv = vec.sub(vec.rotWith([bx1, by1], c1, rotation), vec.rotWith([ax1, ay1], c0, rotation)) + break + } + case TLBoundsCorner.TopRight: { + cv = vec.sub(vec.rotWith([bx0, by1], c1, rotation), vec.rotWith([ax0, ay1], c0, rotation)) + break + } + case TLBoundsCorner.BottomRight: { + cv = vec.sub(vec.rotWith([bx0, by0], c1, rotation), vec.rotWith([ax0, ay0], c0, rotation)) + break + } + case TLBoundsCorner.BottomLeft: { + cv = vec.sub(vec.rotWith([bx1, by0], c1, rotation), vec.rotWith([ax1, ay0], c0, rotation)) + break + } + case TLBoundsEdge.Top: { + cv = vec.sub( + vec.rotWith(vec.med([bx0, by1], [bx1, by1]), c1, rotation), + vec.rotWith(vec.med([ax0, ay1], [ax1, ay1]), c0, rotation) + ) + break + } + case TLBoundsEdge.Left: { + cv = vec.sub( + vec.rotWith(vec.med([bx1, by0], [bx1, by1]), c1, rotation), + vec.rotWith(vec.med([ax1, ay0], [ax1, ay1]), c0, rotation) + ) + break + } + case TLBoundsEdge.Bottom: { + cv = vec.sub( + vec.rotWith(vec.med([bx0, by0], [bx1, by0]), c1, rotation), + vec.rotWith(vec.med([ax0, ay0], [ax1, ay0]), c0, rotation) + ) + break + } + case TLBoundsEdge.Right: { + cv = vec.sub( + vec.rotWith(vec.med([bx0, by0], [bx0, by1]), c1, rotation), + vec.rotWith(vec.med([ax0, ay0], [ax0, ay1]), c0, rotation) + ) + break + } + } + + ;[bx0, by0] = vec.sub([bx0, by0], cv) + ;[bx1, by1] = vec.sub([bx1, by1], cv) + } + + /* +4. Flips + +If the axes are flipped (e.g. if the right edge has been dragged +left past the initial left edge) then swap points on that axis. +*/ + + if (bx1 < bx0) { + ;[bx1, bx0] = [bx0, bx1] + } + + if (by1 < by0) { + ;[by1, by0] = [by0, by1] + } + + return { + minX: bx0, + minY: by0, + maxX: bx1, + maxY: by1, + width: bx1 - bx0, + height: by1 - by0, + scaleX: ((bx1 - bx0) / (ax1 - ax0 || 1)) * (flipX ? -1 : 1), + scaleY: ((by1 - by0) / (ay1 - ay0 || 1)) * (flipY ? -1 : 1), + } + } + + static getTransformAnchor( + type: TLBoundsEdge | TLBoundsCorner, + isFlippedX: boolean, + isFlippedY: boolean + ): TLBoundsCorner | TLBoundsEdge { + let anchor: TLBoundsCorner | TLBoundsEdge = type + + // Change corner anchors if flipped + switch (type) { + case TLBoundsCorner.TopLeft: { + if (isFlippedX && isFlippedY) { + anchor = TLBoundsCorner.BottomRight + } else if (isFlippedX) { + anchor = TLBoundsCorner.TopRight + } else if (isFlippedY) { + anchor = TLBoundsCorner.BottomLeft + } else { + anchor = TLBoundsCorner.BottomRight + } + break + } + case TLBoundsCorner.TopRight: { + if (isFlippedX && isFlippedY) { + anchor = TLBoundsCorner.BottomLeft + } else if (isFlippedX) { + anchor = TLBoundsCorner.TopLeft + } else if (isFlippedY) { + anchor = TLBoundsCorner.BottomRight + } else { + anchor = TLBoundsCorner.BottomLeft + } + break + } + case TLBoundsCorner.BottomRight: { + if (isFlippedX && isFlippedY) { + anchor = TLBoundsCorner.TopLeft + } else if (isFlippedX) { + anchor = TLBoundsCorner.BottomLeft + } else if (isFlippedY) { + anchor = TLBoundsCorner.TopRight + } else { + anchor = TLBoundsCorner.TopLeft + } + break + } + case TLBoundsCorner.BottomLeft: { + if (isFlippedX && isFlippedY) { + anchor = TLBoundsCorner.TopRight + } else if (isFlippedX) { + anchor = TLBoundsCorner.BottomRight + } else if (isFlippedY) { + anchor = TLBoundsCorner.TopLeft + } else { + anchor = TLBoundsCorner.TopRight + } + break + } + } + + return anchor + } + + /** + * Get the relative bounds (usually a child) within a transformed bounding box. + * @param bounds + * @param initialBounds + * @param initialShapeBounds + * @param isFlippedX + * @param isFlippedY + */ + static getRelativeTransformedBoundingBox( + bounds: TLBounds, + initialBounds: TLBounds, + initialShapeBounds: TLBounds, + isFlippedX: boolean, + isFlippedY: boolean + ): TLBounds { + const nx = + (isFlippedX + ? initialBounds.maxX - initialShapeBounds.maxX + : initialShapeBounds.minX - initialBounds.minX) / initialBounds.width + + const ny = + (isFlippedY + ? initialBounds.maxY - initialShapeBounds.maxY + : initialShapeBounds.minY - initialBounds.minY) / initialBounds.height + + const nw = initialShapeBounds.width / initialBounds.width + const nh = initialShapeBounds.height / initialBounds.height + + const minX = bounds.minX + bounds.width * nx + const minY = bounds.minY + bounds.height * ny + const width = bounds.width * nw + const height = bounds.height * nh + + return { + minX, + minY, + maxX: minX + width, + maxY: minY + height, + width, + height, + } + } + + /** + * Get the size of a rotated box. + * @param size : ; + * @param rotation + */ + static getRotatedSize(size: number[], rotation: number): number[] { + const center = vec.div(size, 2) + + const points = [[0, 0], [size[0], 0], size, [0, size[1]]].map((point) => + vec.rotWith(point, center, rotation) + ) + + const bounds = Utils.getBoundsFromPoints(points) + + return [bounds.width, bounds.height] + } + + /** + * Get the center of a bounding box. + * @param bounds + */ + static getBoundsCenter(bounds: TLBounds): number[] { + return [bounds.minX + bounds.width / 2, bounds.minY + bounds.height / 2] + } + + /* -------------------------------------------------- */ + /* Lists and Collections */ + /* -------------------------------------------------- */ + + /** + * + * + * ### Example + * + *```ts + * example + *``` + */ + static removeDuplicatePoints(points: number[][]) { + return points.reduce((acc, pt, i) => { + if (i === 0 || !vec.isEqual(pt, acc[i - 1])) { + acc.push(pt) + } + return acc + }, []) + } + + /** + // points = + + +/** + * Get a value from a cache (a WeakMap), filling the value if it is not present. + * + * ### Example + * + *```ts + * getFromCache(boundsCache, shape, (cache) => cache.set(shape, "value")) + *``` + */ + // eslint-disable-next-line @typescript-eslint/ban-types + static getFromCache(cache: WeakMap, item: I, getNext: () => V): V { + let value = cache.get(item) + + if (value === undefined) { + cache.set(item, getNext()) + value = cache.get(item) + + if (value === undefined) { + throw Error('Cache did not include item!') + } + } + + return value + } + + /** + * Get a unique string id. + */ + static uniqueId(a = ''): string { + return a + ? /* eslint-disable no-bitwise */ + ((Number(a) ^ (Math.random() * 16)) >> (Number(a) / 4)).toString(16) + : `${1e7}-${1e3}-${4e3}-${8e3}-${1e11}`.replace(/[018]/g, Utils.uniqueId) + } + + /** + * Shuffle the contents of an array. + * @param arr + * @param offset + */ + static shuffleArr(arr: T[], offset: number): T[] { + return arr.map((_, i) => arr[(i + offset) % arr.length]) + } + + /** + * Deep compare two arrays. + * @param a + * @param b + */ + static deepCompareArrays(a: T[], b: T[]): boolean { + if (a?.length !== b?.length) return false + return Utils.deepCompare(a, b) + } + + /** + * Deep compare any values. + * @param a + * @param b + */ + static deepCompare(a: T, b: T): boolean { + return a === b || JSON.stringify(a) === JSON.stringify(b) + } + + /** + * Find whether two arrays intersect. + * @param a + * @param b + * @param fn An optional function to apply to the items of a; will check if b includes the result. + */ + static arrsIntersect(a: T[], b: K[], fn?: (item: K) => T): boolean + static arrsIntersect(a: T[], b: T[]): boolean + static arrsIntersect(a: T[], b: unknown[], fn?: (item: unknown) => T): boolean { + return a.some((item) => b.includes(fn ? fn(item) : item)) + } + + /** + * Get the unique values from an array of strings or numbers. + * @param items + */ + static uniqueArray(...items: T[]): T[] { + return Array.from(new Set(items).values()) + } + + /** + * Convert a set to an array. + * @param set + */ + static setToArray(set: Set): T[] { + return Array.from(set.values()) + } + + /** + * Debounce a function. + */ + static debounce void>(fn: T, ms = 0) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let timeoutId: number | any + return function (...args: Parameters) { + clearTimeout(timeoutId) + timeoutId = setTimeout(() => fn.apply(args), ms) + } + } + + /** + * Turn an array of points into a path of quadradic curves. + * @param stroke ; + */ + static getSvgPathFromStroke(stroke: number[][]): string { + if (!stroke.length) return '' + + const d = stroke.reduce( + (acc, [x0, y0], i, arr) => { + const [x1, y1] = arr[(i + 1) % arr.length] + acc.push(` ${x0},${y0} ${(x0 + x1) / 2},${(y0 + y1) / 2}`) + return acc + }, + ['M ', `${stroke[0][0]},${stroke[0][1]}`, ' Q'] + ) + + d.push(' Z') + + return d.join('').replaceAll(/(\s?[A-Z]?,?-?[0-9]*\.[0-9]{0,2})(([0-9]|e|-)*)/g, '$1') + } + + /* -------------------------------------------------- */ + /* Browser and DOM */ + /* -------------------------------------------------- */ + + static isMobileSize() { + if (typeof window === 'undefined') return false + return window.innerWidth < 768 + } + + static isMobileSafari() { + if (typeof window === 'undefined') return false + const ua = window.navigator.userAgent + const iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i) + const webkit = !!ua.match(/WebKit/i) + return iOS && webkit && !ua.match(/CriOS/i) + } + + // via https://github.com/bameyrick/throttle-typescript + static throttle any>( + func: T, + limit: number + ): (...args: Parameters) => ReturnType { + let inThrottle: boolean + let lastResult: ReturnType + + return function (this: any, ...args: any[]): ReturnType { + if (!inThrottle) { + inThrottle = true + + setTimeout(() => (inThrottle = false), limit) + + lastResult = func.apply(this, ...args) + } + + return lastResult + } + } + + /** + * Find whether the current display is a touch display. + */ + // static isTouchDisplay(): boolean { + // return ( + // 'ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0 + // ) + // } + + /** + * Find whether the current device is a Mac / iOS / iPadOS. + */ + static isDarwin(): boolean { + return /Mac|iPod|iPhone|iPad/.test(window.navigator.platform) + } + + /** + * Get whether an event is command (mac) or control (pc). + * @param e + */ + static metaKey(e: KeyboardEvent | React.KeyboardEvent): boolean { + return Utils.isDarwin() ? e.metaKey : e.ctrlKey + } +} + +export default Utils + +// Helper types + +type Entry = { + [K in keyof T]: [K, T[K]] +}[keyof T] diff --git a/utils/vec.ts b/packages/core/src/utils/vec.tsx similarity index 91% rename from utils/vec.ts rename to packages/core/src/utils/vec.tsx index 68bc9cecc..777094a87 100644 --- a/utils/vec.ts +++ b/packages/core/src/utils/vec.tsx @@ -2,7 +2,7 @@ /* ----------------- Start Copy Here ---------------- */ -export default class Vec { +export class Vec { /** * Clamp a value into a range. * @param n @@ -14,6 +14,17 @@ export default class Vec { return Math.max(min, typeof max !== 'undefined' ? Math.min(n, max) : n) } + /** + * Clamp a value into a range. + * @param n + * @param min + */ + static clampV(A: number[], min: number): number[] + static clampV(A: number[], min: number, max: number): number[] + static clampV(A: number[], min: number, max?: number): number[] { + return A.map((n) => (max ? Vec.clamp(n, min, max) : Vec.clamp(n, min))) + } + /** * Negate a vector. * @param A @@ -125,6 +136,14 @@ export default class Vec { return A[0] * B[1] - B[0] * A[1] } + /** + * Cross (for point in polygon) + * + */ + static cross(x: number[], y: number[], z: number[]): number { + return (y[0] - x[0]) * (z[1] - x[1]) - (z[0] - x[0]) * (y[1] - x[1]) + } + /** * Length of the vector squared * @param A @@ -241,10 +260,7 @@ export default class Vec { * @param r rotation in radians */ static rot = (A: number[], r: number): number[] => { - return [ - A[0] * Math.cos(r) - A[1] * Math.sin(r), - A[0] * Math.sin(r) + A[1] * Math.cos(r), - ] + return [A[0] * Math.cos(r) - A[1] * Math.sin(r), A[0] * Math.sin(r) + A[1] * Math.cos(r)] } /** @@ -295,13 +311,7 @@ export default class Vec { * @param to Ending value * @param s Strength */ - static int = ( - A: number[], - B: number[], - from: number, - to: number, - s = 1 - ): number[] => { + static int = (A: number[], B: number[], from: number, to: number, s = 1): number[] => { const t = (Vec.clamp(from, to) - from) / (to - from) return Vec.add(Vec.mul(A, 1 - t), Vec.mul(B, s)) } @@ -402,11 +412,7 @@ export default class Vec { * @param P A point not on the line to test. * @returns */ - static nearestPointOnLineThroughPoint = ( - A: number[], - u: number[], - P: number[] - ): number[] => { + static nearestPointOnLineThroughPoint = (A: number[], u: number[], P: number[]): number[] => { return Vec.add(A, Vec.mul(u, Vec.pry(Vec.sub(P, A), u))) } @@ -417,11 +423,7 @@ export default class Vec { * @param P A point not on the line to test. * @returns */ - static distanceToLineThroughPoint = ( - A: number[], - u: number[], - P: number[] - ): number => { + static distanceToLineThroughPoint = (A: number[], u: number[], P: number[]): number => { return Vec.dist(P, Vec.nearestPointOnLineThroughPoint(A, u, P)) } @@ -464,12 +466,7 @@ export default class Vec { * @param clamp Whether to clamp the point between A and B. * @returns */ - static distanceToLineSegment = ( - A: number[], - B: number[], - P: number[], - clamp = true - ): number => { + static distanceToLineSegment = (A: number[], B: number[], P: number[], clamp = true): number => { return Vec.dist(P, Vec.nearestPointOnLineSegment(A, B, P, clamp)) } @@ -513,8 +510,10 @@ export default class Vec { return Array.from(Array(steps)) .map((_, i) => { const t = i / steps - return t * t * t + return t * t * t * t }) .map((t) => Vec.round([...Vec.lrp(a, b, t), (1 - t) / 2])) } } + +export default Vec diff --git a/packages/core/tsconfig.build.json b/packages/core/tsconfig.build.json new file mode 100644 index 000000000..92e47bf2b --- /dev/null +++ b/packages/core/tsconfig.build.json @@ -0,0 +1,15 @@ +{ + "extends": "./tsconfig.json", + "exclude": [ + "node_modules", + "**/*.test.tsx", + "**/*.test.ts", + "**/*.spec.tsx", + "**/*.spec.ts", + "src/test", + "dist" + ], + "compilerOptions": { + "outDir": "./dist/types" + } +} diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json new file mode 100644 index 000000000..3c6698426 --- /dev/null +++ b/packages/core/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src"], + "exclude": ["node_modules", "dist"], + "compilerOptions": { + "emitDeclarationOnly": true, + "rootDir": "src", + "outDir": "./dist/types", + "baseUrl": "src", + "paths": { + "+*": ["./*"] + } + } +} diff --git a/packages/dev/README.md b/packages/dev/README.md new file mode 100644 index 000000000..c8d3b3631 --- /dev/null +++ b/packages/dev/README.md @@ -0,0 +1,3 @@ +# Dev Server + +Dev server with fast refresh. diff --git a/packages/dev/esbuild.config.mjs b/packages/dev/esbuild.config.mjs new file mode 100644 index 000000000..bc5dce38a --- /dev/null +++ b/packages/dev/esbuild.config.mjs @@ -0,0 +1,43 @@ +/* eslint-disable no-undef */ +import fs from 'fs' +import esbuild from 'esbuild' +import serve, { error, log } from 'create-serve' + +const isDevServer = process.argv.includes('--dev') + +if (!fs.existsSync('./dist')) { + fs.mkdirSync('./dist') +} + +fs.copyFile('./src/index.html', './dist/index.html', (err) => { + if (err) throw err +}) + +esbuild + .build({ + entryPoints: ['src/index.tsx'], + bundle: true, + outfile: 'dist/bundle.js', + minify: false, + sourcemap: true, + incremental: isDevServer, + target: ['chrome58', 'firefox57', 'safari11', 'edge18'], + define: { + 'process.env.NODE_ENV': isDevServer ? '"development"' : '"production"', + }, + watch: isDevServer && { + onRebuild(err) { + serve.update() + err ? error('❌ Failed') : log('✅ Updated') + }, + }, + }) + .catch(() => process.exit(1)) + +if (isDevServer) { + serve.start({ + port: 5000, + root: './dist', + live: true, + }) +} diff --git a/packages/dev/package.json b/packages/dev/package.json new file mode 100644 index 000000000..23bf2bba1 --- /dev/null +++ b/packages/dev/package.json @@ -0,0 +1,37 @@ +{ + "name": "@tldraw/dev", + "version": "0.0.59", + "private": true, + "description": "A tiny little drawing app (core).", + "author": "@steveruizok", + "license": "MIT", + "keywords": [ + "react", + "typescript", + "esbuild" + ], + "scripts": { + "start": "node ./esbuild.config.mjs --dev tsc --watch" + }, + "files": [ + "README.md", + "src" + ], + "dependencies": { + "@tldraw/tldraw": "^0.0.59", + "idb": "^6.1.2", + "react": "^17.0.2", + "react-dom": "^17.0.2" + }, + "devDependencies": { + "@types/node": "^14.14.35", + "@types/react": "^17.0.3", + "@types/react-dom": "^17.0.2", + "concurrently": "6.0.1", + "create-serve": "1.0.1", + "esbuild": "0.11.5", + "rimraf": "3.0.2", + "typescript": "4.2.3" + }, + "gitHead": "a7dac0f83ad998e205c2aab58182cb4ba4e099a6" +} diff --git a/packages/dev/src/app.tsx b/packages/dev/src/app.tsx new file mode 100644 index 000000000..1e6ebd434 --- /dev/null +++ b/packages/dev/src/app.tsx @@ -0,0 +1,6 @@ +import * as React from 'react' +import Editor from './components/editor' + +export default function App(): JSX.Element { + return +} diff --git a/public/VerveineRegular.woff b/packages/dev/src/assets/VerveineRegular.woff similarity index 100% rename from public/VerveineRegular.woff rename to packages/dev/src/assets/VerveineRegular.woff diff --git a/packages/dev/src/components/editor.tsx b/packages/dev/src/components/editor.tsx new file mode 100644 index 000000000..ba0101975 --- /dev/null +++ b/packages/dev/src/components/editor.tsx @@ -0,0 +1,27 @@ +import * as React from 'react' +import { TLDraw, TLDrawState } from '@tldraw/tldraw' + +export default function Editor(): JSX.Element { + const rTLDrawState = React.useRef() + + const handleMount = React.useCallback((state: TLDrawState) => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + window.tlstate = state + + rTLDrawState.current = state + state.selectAll() + state.createShapes({ + id: 'rect1', + type: 'rectangle', + point: [100, 100], + size: [200, 200], + }) + state.updateShapes({ + id: 'rect1', + point: [150, 150], + }) + }, []) + + return +} diff --git a/packages/dev/src/hooks/usePersistence.tsx b/packages/dev/src/hooks/usePersistence.tsx new file mode 100644 index 000000000..04e59a243 --- /dev/null +++ b/packages/dev/src/hooks/usePersistence.tsx @@ -0,0 +1,100 @@ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +import * as React from 'react' +import { openDB, DBSchema } from 'idb' +import type { TLDrawDocument } from '@tldraw/tldraw' + +const VERSION = 5 + +interface TLDatabase extends DBSchema { + documents: { + key: string + value: TLDrawDocument + } +} + +/** + * Persist a value in indexdb. This hook is designed to be used primarily through + * its methods, `setValue` and `forceUpdate`. The `setValue` method will update the + * value in the database, howeever it will NOT cause the hook's component to update. + * The `forceUpdate` method will cause the component to update with the latest value + * in the database. + * + * ### Example + * + *```ts + * const {status, value, setValue, forceUpdate} = usePersistence() + *``` + */ +export function usePersistence(id: string, doc: TLDrawDocument) { + const [status, setStatus] = React.useState<'loading' | 'ready'>('loading') + const [value, _setValue] = React.useState(null) + + // A function that other parts of the program can use to manually update + // the state to the latest value in the database. + const forceUpdate = React.useCallback(() => { + _setValue(null) + setStatus('loading') + + openDB('db', VERSION).then((db) => + db.get('documents', id).then((v) => { + if (!v) throw Error(`Could not find document with id: ${id}`) + _setValue(v) + setStatus('ready') + }) + ) + }, [id]) + + // A function that other parts of the program can use to manually set the + // value in the database. + const setValue = React.useCallback( + (doc: TLDrawDocument) => { + openDB('db', VERSION).then((db) => db.put('documents', doc, id)) + }, + [id] + ) + + // Whenever the id or doc changes, save the new value to the database and update + // the state. + React.useEffect(() => { + async function handleLoad() { + const db = await openDB('db', VERSION, { + upgrade(db, _oldVersion, newVersion) { + if (newVersion) { + if (db.objectStoreNames.contains('documents')) { + db.deleteObjectStore('documents') + } + db.createObjectStore('documents') + } + }, + }) + + let savedDoc: TLDrawDocument + + try { + const restoredDoc = await db.get('documents', id) + if (!restoredDoc) throw Error('No document') + savedDoc = restoredDoc + restoredDoc.pageStates = Object.fromEntries( + Object.entries(restoredDoc.pageStates).map(([pageId, pageState]) => [ + pageId, + { + ...pageState, + hoveredId: undefined, + editingId: undefined, + }, + ]) + ) + } catch (e) { + await db.put('documents', doc, id) + savedDoc = doc + } + + _setValue(savedDoc) + setStatus('ready') + } + + handleLoad() + }, [id, doc]) + + return { value, status, setValue, forceUpdate } +} diff --git a/packages/dev/src/index.html b/packages/dev/src/index.html new file mode 100644 index 000000000..a9ad15a5c --- /dev/null +++ b/packages/dev/src/index.html @@ -0,0 +1,24 @@ + + + + + + + tldraw + + +
+ + + + + diff --git a/packages/dev/src/index.tsx b/packages/dev/src/index.tsx new file mode 100644 index 000000000..64dd2bde6 --- /dev/null +++ b/packages/dev/src/index.tsx @@ -0,0 +1,10 @@ +import React from 'react' +import ReactDOM from 'react-dom' +import App from './app' + +ReactDOM.render( + + + , + document.getElementById('root') +) diff --git a/packages/dev/tsconfig.json b/packages/dev/tsconfig.json new file mode 100644 index 000000000..cf9a3b892 --- /dev/null +++ b/packages/dev/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src"], + "exclude": ["node_modules", "**/*.test.ts", "**/*.spec.ts", "dist"], + "compilerOptions": { + "rootDir": "src", + "outDir": "./dist/types", + "baseUrl": "src" + } +} diff --git a/packages/tldraw/README.md b/packages/tldraw/README.md new file mode 100644 index 000000000..0ff14834a --- /dev/null +++ b/packages/tldraw/README.md @@ -0,0 +1,148 @@ +# @tldraw/tldraw + +This package contains the [tldraw](https://tldraw.com) editor as a standalone React component. + +## Installation + +```bash +npm i @tldraw/tldraw +``` + +or + +```bash +yarn add @tldraw/tldraw +``` + +## Usage + +Import the `TLDraw` React component and use it in your app. + +```tsx +import { TLDraw } from '@tldraw/tldraw' + +function App() { + return ( +
+ +
+ ) +} +``` + +## 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. + +| Prop | Type | Description | +| --------------- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `document` | `TLDrawDocument` | (optional) An initial [`TLDrawDocument`](#tldrawdocument) object. | +| `currentPageId` | `string` | (optional) A current page id, referencing the `TLDrawDocument` object provided via the `document` prop. | +| `onMount` | `(TLDrawState) => void` | (optional) A callback function that will be called when the editor first mounts, receiving the current `TLDrawState`. | +| `onChange` | `(TLDrawState, string) => void` | (optional) A callback function that will be called whenever the `TLDrawState` updates. The update will include the current `TLDrawState` and the reason for the change. | + +### `TLDrawDocument` + +A `TLDrawDocument` is an object with three properties: + +- `id` - A unique ID for this document +- `pages` - A table of `TLPage` objects +- `pageStates` - A table of `TLPageState` objects + +```ts +const tldocument: TLDrawDocument = { + id: 'doc', + pages: { + page1: { + id: 'page1', + shapes: {}, + bindings: {}, + }, + }, + pageStates: { + page1: { + id: 'page1', + selectedIds: [], + currentParentId: 'page1', + camera: { + point: [0, 0], + zoom: 1, + }, + }, + }, +} +``` + +**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. + +In the example above, the page above with the id `page1`is at `tldocument.pages["page1"]`. Its corresponding page state has the same id (`page1`) and is at `tldocument.pageStates["page1"]`. + +### 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` | `TLHandle{}` | (optional) A table of `TLHandle` objects. | +| `isLocked` | `boolean` | True if the shape is locked. | +| `isHidden` | `boolean` | True if the shape is hidden. | +| `isEditing` | `boolean` | True if the shape is currently editing. | +| `isGenerated` | `boolean` | True if the shape is generated. | +| `isAspectRatioLocked` | `boolean` | True if the shape's aspect ratio is locked. | + +> **Important:** In order for re-ordering to work correctly, 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. | + +#### Draw + +| Property | Type | Description | +| -------- | ------------ | ----------------------------------------- | +| `points` | `number[][]` | An array of points as `[x, y, pressure]`. | + +##### Rectangle + +| Property | Type | Description | +| -------- | ---------- | --------------------------------------- | +| `size` | `number[]` | The `[width, height]` of the rectangle. | + +#### Ellipse + +| Property | Type | Description | +| -------- | ---------- | ----------------------------------- | +| `radius` | `number[]` | The `[x, y]` radius of the ellipse. | + +#### Arrow + +| Property | Type | Description | +| --------- | -------- | ----------------------------------------------------------------------- | +| `handles` | `object` | An object with three `TLHandle` properties: `start`, `end`, and `bend`. | + +#### Text + +| Property | Type | Description | +| -------- | -------- | ------------------------- | +| `text` | `string` | The shape's text content. | + +## Development + +### Running unit tests + +Run `nx test tldraw` to execute the unit tests via [Jest](https://jestjs.io). diff --git a/packages/tldraw/package.json b/packages/tldraw/package.json new file mode 100644 index 000000000..0b229c2b6 --- /dev/null +++ b/packages/tldraw/package.json @@ -0,0 +1,69 @@ +{ + "name": "@tldraw/tldraw", + "version": "0.0.59", + "private": false, + "description": "A tiny little drawing app (editor).", + "author": "@steveruizok", + "repository": { + "type": "git", + "url": "git+https://github.com/tldraw/tldraw.git", + "directory": "packages/tldraw" + }, + "license": "MIT", + "keywords": [], + "main": "./dist/cjs/index.js", + "module": "./dist/esm/index.js", + "types": "./dist/types/index.d.ts", + "typings": "./dist/types/index.d.ts", + "scripts": { + "start:pre": "node scripts/pre-dev && yarn types:pre", + "start": "node scripts/dev & yarn types:dev", + "build": "yarn clean && node scripts/build && yarn types:build", + "types:pre": "tsc", + "types:dev": "tsc --watch", + "types:build": "tsc --project tsconfig.build.json", + "lint": "eslint src/ --ext .ts,.tsx", + "clean": "rm -rf dist", + "ts-node": "ts-node", + "docs": "typedoc --entryPoints src/index.ts" + }, + "devDependencies": { + "@babel/core": "^7.15.5", + "@babel/preset-env": "^7.15.4", + "@types/jest": "^27.0.1", + "@types/node": "^16.7.10", + "@types/react": "^17.0.16", + "@types/react-dom": "^17.0.9", + "@typescript-eslint/eslint-plugin": "^4.30.0", + "@typescript-eslint/parser": "^4.30.0", + "esbuild": "^0.12.24", + "eslint": "^7.32.0", + "lerna": "^4.0.0", + "react": "^17.0.2", + "react-dom": "^17.0.2", + "ts-node": "^10.2.1", + "tslib": "^2.3.1", + "typedoc": "^0.21.9", + "typescript": "^4.4.2" + }, + "peerDependencies": { + "react": "^17.0.2", + "react-dom": "^17.0.2" + }, + "dependencies": { + "@radix-ui/react-alert-dialog": "^0.0.20", + "@radix-ui/react-checkbox": "^0.0.16", + "@radix-ui/react-context-menu": "^0.0.23", + "@radix-ui/react-dropdown-menu": "^0.0.22", + "@radix-ui/react-icons": "^1.0.3", + "@radix-ui/react-id": "^0.0.6", + "@radix-ui/react-radio-group": "^0.0.18", + "@radix-ui/react-tooltip": "^0.0.20", + "@stitches/react": "^1.0.0", + "@tldraw/core": "^0.0.59", + "perfect-freehand": "^0.5.3", + "react-hotkeys-hook": "^3.4.0", + "rko": "^0.5.20" + }, + "gitHead": "838fabdbff1a66d4d7ee8aa5c5d117bc55acbff2" +} diff --git a/packages/tldraw/scripts/build.js b/packages/tldraw/scripts/build.js new file mode 100644 index 000000000..f2477147b --- /dev/null +++ b/packages/tldraw/scripts/build.js @@ -0,0 +1,52 @@ +/* eslint-disable */ +const fs = require('fs') +const esbuild = require('esbuild') + +const name = process.env.npm_package_name || '' + +async function main() { + if (!fs.existsSync('./dist')) { + fs.mkdirSync('./dist') + } + + try { + esbuild.buildSync({ + entryPoints: ['./src/index.ts'], + outdir: 'dist/cjs', + minify: true, + bundle: true, + format: 'cjs', + target: 'es6', + jsxFactory: 'React.createElement', + jsxFragment: 'React.Fragment', + tsconfig: './tsconfig.json', + external: ['react', 'react-dom'], + }) + + esbuild.buildSync({ + entryPoints: ['./src/index.ts'], + outdir: 'dist/esm', + minify: true, + bundle: true, + format: 'esm', + target: 'es6', + tsconfig: './tsconfig.build.json', + jsxFactory: 'React.createElement', + jsxFragment: 'React.Fragment', + external: ['react', 'react-dom'], + }) + + for (const file of ['package.json', 'README.md']) { + fs.copyFile(file, `dist/${file}`, fs.constants.COPYFILE_EXCL, (err) => { + if (err) throw err + }) + } + + console.log(`✔ ${name}: Built package.`) + } catch (e) { + console.log(`× ${name}: Build failed due to an error.`) + console.log(e) + } +} + +main() diff --git a/packages/tldraw/scripts/dev.js b/packages/tldraw/scripts/dev.js new file mode 100644 index 000000000..d300f6f57 --- /dev/null +++ b/packages/tldraw/scripts/dev.js @@ -0,0 +1,31 @@ +/* eslint-disable */ +const esbuild = require('esbuild') + +const name = process.env.npm_package_name || '' + +async function main() { + esbuild.build({ + entryPoints: ['./src/index.ts'], + outdir: 'dist/cjs', + minify: false, + bundle: true, + format: 'cjs', + target: 'es6', + jsxFactory: 'React.createElement', + jsxFragment: 'React.Fragment', + tsconfig: './tsconfig.build.json', + external: ['react', 'react-dom'], + incremental: true, + watch: { + onRebuild(error) { + if (error) { + console.log(`× ${name}: An error in prevented the rebuild.`) + return + } + console.log(`✔ ${name}: Rebuilt.`) + }, + }, + }) +} + +main() diff --git a/packages/tldraw/scripts/pre-dev.js b/packages/tldraw/scripts/pre-dev.js new file mode 100644 index 000000000..37a935ea8 --- /dev/null +++ b/packages/tldraw/scripts/pre-dev.js @@ -0,0 +1,34 @@ +/* eslint-disable */ +const fs = require('fs') +const esbuild = require('esbuild') + +async function main() { + if (fs.existsSync('./dist')) { + fs.rmSync('./dist', { recursive: true }, (e) => { + if (e) { + throw e + } + }) + } + + fs.mkdir('./dist', (e) => { + if (e) { + throw e + } + }) + + esbuild.build({ + entryPoints: ['./src/index.ts'], + outdir: 'dist/cjs', + minify: false, + bundle: true, + format: 'cjs', + target: 'es6', + jsxFactory: 'React.createElement', + jsxFragment: 'React.Fragment', + tsconfig: './tsconfig.build.json', + external: ['react', 'react-dom'], + }) +} + +main() diff --git a/packages/tldraw/src/assets/VerveineRegular.woff b/packages/tldraw/src/assets/VerveineRegular.woff new file mode 100644 index 000000000..098d9fb17 Binary files /dev/null and b/packages/tldraw/src/assets/VerveineRegular.woff differ diff --git a/packages/tldraw/src/components/context-menu/context-menu.test.tsx b/packages/tldraw/src/components/context-menu/context-menu.test.tsx new file mode 100644 index 000000000..e68ce3b5a --- /dev/null +++ b/packages/tldraw/src/components/context-menu/context-menu.test.tsx @@ -0,0 +1,13 @@ +import * as React from 'react' +import { ContextMenu } from './context-menu' +import { renderWithContext } from '~test' + +describe('context menu', () => { + test('mounts component without crashing', () => { + renderWithContext( + +
Hello
+
+ ) + }) +}) diff --git a/packages/tldraw/src/components/context-menu/context-menu.tsx b/packages/tldraw/src/components/context-menu/context-menu.tsx new file mode 100644 index 000000000..ab677a430 --- /dev/null +++ b/packages/tldraw/src/components/context-menu/context-menu.tsx @@ -0,0 +1,386 @@ +import * as React from 'react' +import styled from '~styles' +import { Utils } from '@tldraw/core' +import * as RadixContextMenu from '@radix-ui/react-context-menu' +import { useTLDrawContext } from '~hooks' +import { Data, AlignType, DistributeType, StretchType } from '~types' +import { + Kbd, + IconWrapper, + breakpoints, + RowButton, + ContextMenuArrow, + ContextMenuDivider, + ContextMenuButton, + ContextMenuSubMenu, + ContextMenuIconButton, + ContextMenuRoot, + MenuContent, +} from '../shared' +import { + ChevronRightIcon, + AlignBottomIcon, + AlignCenterHorizontallyIcon, + AlignCenterVerticallyIcon, + AlignLeftIcon, + AlignRightIcon, + AlignTopIcon, + SpaceEvenlyHorizontallyIcon, + SpaceEvenlyVerticallyIcon, + StretchHorizontallyIcon, + StretchVerticallyIcon, +} from '@radix-ui/react-icons' + +const has1SelectedIdsSelector = (s: Data) => { + return s.document.pageStates[s.appState.currentPageId].selectedIds.length > 0 +} +const has2SelectedIdsSelector = (s: Data) => { + return s.document.pageStates[s.appState.currentPageId].selectedIds.length > 1 +} +const has3SelectedIdsSelector = (s: Data) => { + return s.document.pageStates[s.appState.currentPageId].selectedIds.length > 2 +} + +const isDebugModeSelector = (s: Data) => { + return s.settings.isDebugMode +} + +const hasGroupSelectedSelector = (s: Data) => { + return s.document.pageStates[s.appState.currentPageId].selectedIds.some( + (id) => s.document.pages[s.appState.currentPageId].shapes[id].children !== undefined + ) +} + +interface ContextMenuProps { + children: React.ReactNode +} + +export const ContextMenu = React.memo(({ children }: ContextMenuProps): JSX.Element => { + const { tlstate, useSelector } = useTLDrawContext() + const hasSelection = useSelector(has1SelectedIdsSelector) + const hasTwoOrMore = useSelector(has2SelectedIdsSelector) + const hasThreeOrMore = useSelector(has3SelectedIdsSelector) + const isDebugMode = useSelector(isDebugModeSelector) + const hasGroupSelected = useSelector(hasGroupSelectedSelector) + + const rContent = React.useRef(null) + + const handleFlipHorizontal = React.useCallback(() => { + tlstate.flipHorizontal() + }, [tlstate]) + + const handleFlipVertical = React.useCallback(() => { + tlstate.flipVertical() + }, [tlstate]) + + const handleDuplicate = React.useCallback(() => { + tlstate.duplicate() + }, [tlstate]) + + const handleGroup = React.useCallback(() => { + tlstate.group() + }, [tlstate]) + + const handleMoveToBack = React.useCallback(() => { + tlstate.moveToBack() + }, [tlstate]) + + const handleMoveBackward = React.useCallback(() => { + tlstate.moveBackward() + }, [tlstate]) + + const handleMoveForward = React.useCallback(() => { + tlstate.moveForward() + }, [tlstate]) + + const handleMoveToFront = React.useCallback(() => { + tlstate.moveToFront() + }, [tlstate]) + + const handleDelete = React.useCallback(() => { + tlstate.delete() + }, [tlstate]) + + const handleCopyJson = React.useCallback(() => { + tlstate.copyJson() + }, [tlstate]) + + const handleCopy = React.useCallback(() => { + tlstate.copy() + }, [tlstate]) + + const handlePaste = React.useCallback(() => { + tlstate.paste() + }, [tlstate]) + + const handleCopySvg = React.useCallback(() => { + tlstate.copySvg() + }, [tlstate]) + + const handleUndo = React.useCallback(() => { + tlstate.undo() + }, [tlstate]) + + const handleRedo = React.useCallback(() => { + tlstate.redo() + }, [tlstate]) + + return ( + + {children} + + {hasSelection ? ( + <> + + Flip Horizontal + ⇧H + + + Flip Vertical + ⇧V + + + Duplicate + #D + + + {hasGroupSelected || + (hasTwoOrMore && ( + <> + {hasGroupSelected && ( + + Ungroup + #⇧G + + )} + {hasTwoOrMore && ( + + Group + #G + + )} + + ))} + + + To Front + #⇧] + + + Forward + #] + + + Backward + #[ + + + To Back + #⇧[ + + + + {hasTwoOrMore && ( + + )} + + + Copy + #C + + + Copy to SVG + ⇧#C + + {isDebugMode && ( + + Copy to JSON + + )} + + Paste + #V + + + + Delete + + + + ) : ( + <> + + Paste + #V + + + Undo + #Z + + + Redo + #⇧Z + + + )} + + + ) +}) + +function AlignDistributeSubMenu({ + hasThreeOrMore, +}: { + hasTwoOrMore: boolean + hasThreeOrMore: boolean +}) { + const { tlstate } = useTLDrawContext() + + const alignTop = React.useCallback(() => { + tlstate.align(AlignType.Top) + }, [tlstate]) + + const alignCenterVertical = React.useCallback(() => { + tlstate.align(AlignType.CenterVertical) + }, [tlstate]) + + const alignBottom = React.useCallback(() => { + tlstate.align(AlignType.Bottom) + }, [tlstate]) + + const stretchVertically = React.useCallback(() => { + tlstate.stretch(StretchType.Vertical) + }, [tlstate]) + + const distributeVertically = React.useCallback(() => { + tlstate.distribute(DistributeType.Vertical) + }, [tlstate]) + + const alignLeft = React.useCallback(() => { + tlstate.align(AlignType.Left) + }, [tlstate]) + + const alignCenterHorizontal = React.useCallback(() => { + tlstate.align(AlignType.CenterHorizontal) + }, [tlstate]) + + const alignRight = React.useCallback(() => { + tlstate.align(AlignType.Right) + }, [tlstate]) + + const stretchHorizontally = React.useCallback(() => { + tlstate.stretch(StretchType.Horizontal) + }, [tlstate]) + + const distributeHorizontally = React.useCallback(() => { + tlstate.distribute(DistributeType.Horizontal) + }, [tlstate]) + + return ( + + + Align / Distribute + + + + + + + + + + + + + + + + + + {hasThreeOrMore && ( + + + + )} + + + + + + + + + + + + + + {hasThreeOrMore && ( + + + + )} + + + + ) +} + +const StyledGrid = styled(MenuContent, { + display: 'grid', + variants: { + selectedStyle: { + threeOrMore: { + gridTemplateColumns: 'repeat(5, auto)', + }, + twoOrMore: { + gridTemplateColumns: 'repeat(4, auto)', + }, + }, + }, +}) + +const currentPageIdSelector = (s: Data) => s.appState.currentPageId +const documentPagesSelector = (s: Data) => s.document.pages + +function MoveToPageMenu(): JSX.Element | null { + const { tlstate, useSelector } = useTLDrawContext() + const currentPageId = useSelector(currentPageIdSelector) + const documentPages = useSelector(documentPagesSelector) + + const sorted = Object.values(documentPages) + .sort((a, b) => (a.childIndex || 0) - (b.childIndex || 0)) + .filter((a) => a.id !== currentPageId) + + if (sorted.length === 0) return null + + console.log(sorted) + + return ( + + + Move To Page + + + + + + {sorted.map(({ id, name }, i) => ( + tlstate.moveToPage(id)} + > + {name || `Page ${i}`} + + ))} + + + + ) +} diff --git a/packages/tldraw/src/components/context-menu/index.ts b/packages/tldraw/src/components/context-menu/index.ts new file mode 100644 index 000000000..beff13a99 --- /dev/null +++ b/packages/tldraw/src/components/context-menu/index.ts @@ -0,0 +1 @@ +export * from './context-menu' diff --git a/components/icons/check.tsx b/packages/tldraw/src/components/icons/check.tsx similarity index 97% rename from components/icons/check.tsx rename to packages/tldraw/src/components/icons/check.tsx index a70df8b03..563acdfdd 100644 --- a/components/icons/check.tsx +++ b/packages/tldraw/src/components/icons/check.tsx @@ -2,12 +2,7 @@ import * as React from 'react' function SvgCheck(props: React.SVGProps): JSX.Element { return ( - + , 'stroke' | 'fill'> & { + size: number + } +) { + const { size = 16, ...rest } = props + return ( + + + + ) +} diff --git a/components/icons/index.tsx b/packages/tldraw/src/components/icons/index.tsx similarity index 77% rename from components/icons/index.tsx rename to packages/tldraw/src/components/icons/index.tsx index c3f81e636..9da9315bf 100644 --- a/components/icons/index.tsx +++ b/packages/tldraw/src/components/icons/index.tsx @@ -2,3 +2,4 @@ export { default as Redo } from './redo' export { default as Trash } from './trash' export { default as Undo } from './undo' export { default as Check } from './check' +export { default as CircleIcon } from './circle' diff --git a/components/icons/redo.tsx b/packages/tldraw/src/components/icons/redo.tsx similarity index 81% rename from components/icons/redo.tsx rename to packages/tldraw/src/components/icons/redo.tsx index 986e00c8a..ee8320df2 100644 --- a/components/icons/redo.tsx +++ b/packages/tldraw/src/components/icons/redo.tsx @@ -2,12 +2,7 @@ import * as React from 'react' function SvgRedo(props: React.SVGProps): JSX.Element { return ( - + ): JSX.Element { return ( - + ): JSX.Element { return ( - + { + test('mounts component without crashing', () => { + renderWithContext() + }) +}) diff --git a/components/menu/menu.tsx b/packages/tldraw/src/components/menu/menu.tsx similarity index 53% rename from components/menu/menu.tsx rename to packages/tldraw/src/components/menu/menu.tsx index afe830258..874afc9ef 100644 --- a/components/menu/menu.tsx +++ b/packages/tldraw/src/components/menu/menu.tsx @@ -1,7 +1,6 @@ import * as React from 'react' import { ExitIcon, HamburgerMenuIcon } from '@radix-ui/react-icons' import * as DropdownMenu from '@radix-ui/react-dropdown-menu' -import { memo } from 'react' import { FloatingContainer, DropdownMenuRoot, @@ -11,21 +10,31 @@ import { DropdownMenuButton, DropdownMenuSubMenu, DropdownMenuDivider, - DropdownMenuCheckboxItem, IconWrapper, Kbd, -} from '../shared' -import state, { useSelector } from 'state' -import { commandKey } from 'utils' -import { signOut } from 'next-auth/client' -import { useTheme } from 'next-themes' +} from '~components/shared' +import { useTLDrawContext } from '~hooks' +import { Preferences } from './preferences' -const handleNew = () => state.send('CREATED_NEW_PROJECT') -const handleSave = () => state.send('SAVED') -const handleLoad = () => state.send('LOADED_FROM_FILE_STSTEM') -const toggleDebugMode = () => state.send('TOGGLED_DEBUG_MODE') +export const Menu = React.memo(() => { + const { tlstate } = useTLDrawContext() + + const handleNew = React.useCallback(() => { + tlstate.newProject() + }, [tlstate]) + + const handleSave = React.useCallback(() => { + tlstate.saveProject() + }, [tlstate]) + + const handleLoad = React.useCallback(() => { + tlstate.loadProject() + }, [tlstate]) + + const handleSignOut = React.useCallback(() => { + tlstate.signOut() + }, [tlstate]) -function Menu() { return ( @@ -35,40 +44,27 @@ function Menu() { New Project - - {commandKey()} - N - + #N Open... - - {commandKey()} - L - + #L Save - - {commandKey()} - S - + #S Save As... - - - {commandKey()} - S - + ⇧#S - + Sign Out @@ -78,9 +74,7 @@ function Menu() { ) -} - -export default memo(Menu) +}) function RecentFiles() { return ( @@ -97,27 +91,3 @@ function RecentFiles() { ) } - -function Preferences() { - const { theme, setTheme } = useTheme() - - const isDebugMode = useSelector((s) => s.data.settings.isDebugMode) - const isDarkMode = theme === 'dark' - - return ( - - setTheme(isDarkMode ? 'light' : 'dark')} - > - Dark Mode - - - Debug Mode - - - ) -} diff --git a/packages/tldraw/src/components/menu/preferences.tsx b/packages/tldraw/src/components/menu/preferences.tsx new file mode 100644 index 000000000..a3c867097 --- /dev/null +++ b/packages/tldraw/src/components/menu/preferences.tsx @@ -0,0 +1,44 @@ +import * as React from 'react' +import { DropdownMenuSubMenu, DropdownMenuCheckboxItem } from '~components/shared' +import { useTLDrawContext } from '~hooks' +import type { Data } from '~types' + +const isDebugModeSelector = (s: Data) => s.settings.isDebugMode +const isDarkModeSelector = (s: Data) => s.settings.isDarkMode +const isZoomSnapSelector = (s: Data) => s.settings.isZoomSnap + +export function Preferences() { + const { tlstate, useSelector } = useTLDrawContext() + + const isDebugMode = useSelector(isDebugModeSelector) + + const isDarkMode = useSelector(isDarkModeSelector) + + const isZoomSnap = useSelector(isZoomSnapSelector) + + const toggleDebugMode = React.useCallback(() => { + tlstate.toggleDebugMode() + }, [tlstate]) + + const toggleDarkMode = React.useCallback(() => { + tlstate.toggleDarkMode() + }, [tlstate]) + + const toggleZoomSnap = React.useCallback(() => { + tlstate.toggleZoomSnap() + }, [tlstate]) + + return ( + + + Dark Mode + + + Zoom Snap + + + Debug Mode + + + ) +} diff --git a/packages/tldraw/src/components/page-options-dialog/index.ts b/packages/tldraw/src/components/page-options-dialog/index.ts new file mode 100644 index 000000000..2d13bdb3b --- /dev/null +++ b/packages/tldraw/src/components/page-options-dialog/index.ts @@ -0,0 +1 @@ +export * from './page-options-dialog' diff --git a/packages/tldraw/src/components/page-options-dialog/page-options-dialog.test.tsx b/packages/tldraw/src/components/page-options-dialog/page-options-dialog.test.tsx new file mode 100644 index 000000000..f9ceb7e19 --- /dev/null +++ b/packages/tldraw/src/components/page-options-dialog/page-options-dialog.test.tsx @@ -0,0 +1,9 @@ +import * as React from 'react' +import { PageOptionsDialog } from './page-options-dialog' +import { mockDocument, renderWithContext } from '~test' + +describe('page options dialog', () => { + test('mounts component without crashing', () => { + renderWithContext() + }) +}) diff --git a/packages/tldraw/src/components/page-options-dialog/page-options-dialog.tsx b/packages/tldraw/src/components/page-options-dialog/page-options-dialog.tsx new file mode 100644 index 000000000..91c6709c2 --- /dev/null +++ b/packages/tldraw/src/components/page-options-dialog/page-options-dialog.tsx @@ -0,0 +1,106 @@ +import * as React from 'react' +import * as Dialog from '@radix-ui/react-alert-dialog' +import { MixerVerticalIcon } from '@radix-ui/react-icons' +import { + breakpoints, + IconButton, + DialogOverlay, + DialogContent, + RowButton, + Divider, +} from '~components/shared' +import type { Data, TLDrawPage } from '~types' +import { useTLDrawContext } from '~hooks' + +const canDeleteSelector = (s: Data) => { + return Object.keys(s.document.pages).length > 1 +} + +interface PageOptionsDialogProps { + page: TLDrawPage + onOpen?: () => void + onClose?: () => void +} + +export function PageOptionsDialog({ page, onOpen, onClose }: PageOptionsDialogProps): JSX.Element { + const { tlstate, useSelector } = useTLDrawContext() + + const [isOpen, setIsOpen] = React.useState(false) + + const canDelete = useSelector(canDeleteSelector) + + const rInput = React.useRef(null) + + const handleDuplicate = React.useCallback(() => { + tlstate.duplicatePage(page.id) + onClose?.() + }, [tlstate]) + + const handleDelete = React.useCallback(() => { + if (window.confirm(`Are you sure you want to delete this page?`)) { + tlstate.deletePage(page.id) + onClose?.() + } + }, [tlstate]) + + const handleOpenChange = React.useCallback( + (isOpen: boolean) => { + setIsOpen(isOpen) + + if (isOpen) { + onOpen?.() + return + } + }, + [tlstate, name] + ) + + function stopPropagation(e: React.KeyboardEvent) { + e.stopPropagation() + } + + // TODO: Replace with text input + function handleRename() { + const nextName = window.prompt('New name:', page.name) + tlstate.renamePage(page.id, nextName || page.name || 'Page') + } + + React.useEffect(() => { + if (isOpen) { + setTimeout(() => { + rInput.current?.focus() + rInput.current?.select() + }, 0) + } + }, [isOpen]) + + return ( + + + + + + + + Rename + + + Duplicate + + + Delete + + + + Cancel + + + + ) +} diff --git a/packages/tldraw/src/components/page-panel/index.ts b/packages/tldraw/src/components/page-panel/index.ts new file mode 100644 index 000000000..333268ef3 --- /dev/null +++ b/packages/tldraw/src/components/page-panel/index.ts @@ -0,0 +1 @@ +export * from './page-panel' diff --git a/packages/tldraw/src/components/page-panel/page-panel.test.tsx b/packages/tldraw/src/components/page-panel/page-panel.test.tsx new file mode 100644 index 000000000..bb577e494 --- /dev/null +++ b/packages/tldraw/src/components/page-panel/page-panel.test.tsx @@ -0,0 +1,9 @@ +import * as React from 'react' +import { PagePanel } from './page-panel' +import { renderWithContext } from '~test' + +describe('page panel', () => { + test('mounts component without crashing', () => { + renderWithContext() + }) +}) diff --git a/packages/tldraw/src/components/page-panel/page-panel.tsx b/packages/tldraw/src/components/page-panel/page-panel.tsx new file mode 100644 index 000000000..32f350140 --- /dev/null +++ b/packages/tldraw/src/components/page-panel/page-panel.tsx @@ -0,0 +1,130 @@ +import * as React from 'react' +import * as DropdownMenu from '@radix-ui/react-dropdown-menu' +import { PlusIcon, CheckIcon } from '@radix-ui/react-icons' +import { + breakpoints, + DropdownMenuButton, + DropdownMenuDivider, + RowButton, + MenuContent, + FloatingContainer, + IconWrapper, +} from '~components/shared' +import { PageOptionsDialog } from '~components/page-options-dialog' +import styled from '~styles' +import { useTLDrawContext } from '~hooks' +import type { Data } from '~types' + +const sortedSelector = (s: Data) => + Object.values(s.document.pages).sort((a, b) => (a.childIndex || 0) - (b.childIndex || 0)) + +const currentPageNameSelector = (s: Data) => s.document.pages[s.appState.currentPageId].name + +const currentPageIdSelector = (s: Data) => s.document.pages[s.appState.currentPageId].id + +export function PagePanel(): JSX.Element { + const { useSelector } = useTLDrawContext() + + const rIsOpen = React.useRef(false) + + const [isOpen, setIsOpen] = React.useState(false) + + React.useEffect(() => { + if (rIsOpen.current !== isOpen) { + rIsOpen.current = isOpen + } + }, [isOpen]) + + const handleClose = React.useCallback(() => { + setIsOpen(false) + }, [setIsOpen]) + + const handleOpenChange = React.useCallback( + (isOpen: boolean) => { + if (rIsOpen.current !== isOpen) { + setIsOpen(isOpen) + } + }, + [setIsOpen] + ) + const currentPageName = useSelector(currentPageNameSelector) + + return ( + + + + {currentPageName || 'Page'} + + + + {isOpen && } + + + ) +} + +function PageMenuContent({ onClose }: { onClose: () => void }) { + const { tlstate, useSelector } = useTLDrawContext() + + const sortedPages = useSelector(sortedSelector) + + const currentPageId = useSelector(currentPageIdSelector) + + const handleCreatePage = React.useCallback(() => { + tlstate.createPage() + }, [tlstate]) + + const handleChangePage = React.useCallback( + (id: string) => { + onClose() + tlstate.changePage(id) + }, + [tlstate] + ) + + return ( + <> + + {sortedPages.map((page) => ( + + + {page.name || 'Page'} + + + + + + + + + ))} + + + + Create Page + + + + + + ) +} + +const ButtonWithOptions = styled('div', { + display: 'grid', + gridTemplateColumns: '1fr auto', + gridAutoFlow: 'column', + + '& > *[data-shy="true"]': { + opacity: 0, + }, + + '&:hover > *[data-shy="true"]': { + opacity: 1, + }, +}) diff --git a/packages/tldraw/src/components/shared/breakpoints.tsx b/packages/tldraw/src/components/shared/breakpoints.tsx new file mode 100644 index 000000000..dfd64f662 --- /dev/null +++ b/packages/tldraw/src/components/shared/breakpoints.tsx @@ -0,0 +1,6 @@ +/* -------------------------------------------------- */ +/* Breakpoints */ +/* -------------------------------------------------- */ + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export const breakpoints: any = { '@initial': 'mobile', '@sm': 'small' } diff --git a/packages/tldraw/src/components/shared/buttons-row.tsx b/packages/tldraw/src/components/shared/buttons-row.tsx new file mode 100644 index 000000000..4d902cc79 --- /dev/null +++ b/packages/tldraw/src/components/shared/buttons-row.tsx @@ -0,0 +1,18 @@ +import styled from '~styles' + +/* -------------------------------------------------- */ +/* Buttons Row */ +/* -------------------------------------------------- */ + +export const ButtonsRow = styled('div', { + position: 'relative', + display: 'flex', + width: '100%', + background: 'none', + border: 'none', + cursor: 'pointer', + outline: 'none', + alignItems: 'center', + justifyContent: 'flex-start', + padding: 0, +}) diff --git a/packages/tldraw/src/components/shared/context-menu.tsx b/packages/tldraw/src/components/shared/context-menu.tsx new file mode 100644 index 000000000..b18346138 --- /dev/null +++ b/packages/tldraw/src/components/shared/context-menu.tsx @@ -0,0 +1,134 @@ +import * as React from 'react' +import { CheckIcon, ChevronRightIcon } from '@radix-ui/react-icons' +import { + Root as CMRoot, + TriggerItem as CMTriggerItem, + Separator as CMSeparator, + Item as CMItem, + Arrow as CMArrow, + Content as CMContent, + ItemIndicator as CMItemIndicator, + CheckboxItem as CMCheckboxItem, +} from '@radix-ui/react-context-menu' +import { breakpoints } from './breakpoints' +import { RowButton } from './row-button' +import { IconButton } from './icon-button' +import { IconWrapper } from './icon-wrapper' +import { MenuContent } from './menu' +import styled from '~styles' + +/* -------------------------------------------------- */ +/* Context Menu */ +/* -------------------------------------------------- */ + +export interface ContextMenuRootProps { + onOpenChange?: (isOpen: boolean) => void + children: React.ReactNode +} + +export function ContextMenuRoot({ onOpenChange, children }: ContextMenuRootProps): JSX.Element { + return ( + + {children} + + ) +} + +export interface ContextMenuSubMenuProps { + label: string + children: React.ReactNode +} + +export function ContextMenuSubMenu({ children, label }: ContextMenuSubMenuProps): JSX.Element { + return ( + + + {label} + + + + + + {children} + + + + ) +} + +export const ContextMenuDivider = styled(CMSeparator, { + backgroundColor: '$hover', + height: 1, + margin: '$2 -$2', +}) + +export const ContextMenuArrow = styled(CMArrow, { + fill: '$panel', +}) + +export interface ContextMenuButtonProps { + onSelect?: () => void + disabled?: boolean + children: React.ReactNode +} + +export function ContextMenuButton({ + onSelect, + children, + disabled = false, +}: ContextMenuButtonProps): JSX.Element { + return ( + + {children} + + ) +} + +interface ContextMenuIconButtonProps { + onSelect: () => void + disabled?: boolean + children: React.ReactNode +} + +export function ContextMenuIconButton({ + onSelect, + children, + disabled = false, +}: ContextMenuIconButtonProps): JSX.Element { + return ( + + {children} + + ) +} + +interface ContextMenuCheckboxItemProps { + checked: boolean + disabled?: boolean + onCheckedChange: (isChecked: boolean) => void + children: React.ReactNode +} + +export function ContextMenuCheckboxItem({ + checked, + disabled = false, + onCheckedChange, + children, +}: ContextMenuCheckboxItemProps): JSX.Element { + return ( + + {children} + + + + + + + ) +} diff --git a/packages/tldraw/src/components/shared/dialog.tsx b/packages/tldraw/src/components/shared/dialog.tsx new file mode 100644 index 000000000..7ccbb3fd5 --- /dev/null +++ b/packages/tldraw/src/components/shared/dialog.tsx @@ -0,0 +1,51 @@ +import styled from '~styles' + +/* -------------------------------------------------- */ +/* Dialog */ +/* -------------------------------------------------- */ + +export const DialogContent = styled('div', { + position: 'fixed', + top: '50%', + left: '50%', + transform: 'translate(-50%, -50%)', + minWidth: 240, + maxWidth: 'fit-content', + maxHeight: '85vh', + marginTop: '-5vh', + pointerEvents: 'all', + backgroundColor: '$panel', + border: '1px solid $panel', + padding: '$0', + boxShadow: '$4', + borderRadius: '4px', + font: '$ui', + + '&:focus': { + outline: 'none', + }, +}) + +export const DialogOverlay = styled('div', { + backgroundColor: 'rgba(0, 0, 0, .15)', + position: 'fixed', + top: 0, + right: 0, + bottom: 0, + left: 0, +}) + +export const DialogInputWrapper = styled('div', { + padding: '$4 $2', +}) + +export const DialogTitleRow = styled('div', { + display: 'flex', + padding: '0 0 0 $4', + alignItems: 'center', + justifyContent: 'space-between', + + h3: { + fontSize: '$1', + }, +}) diff --git a/packages/tldraw/src/components/shared/dropdown-menu.tsx b/packages/tldraw/src/components/shared/dropdown-menu.tsx new file mode 100644 index 000000000..199971bd2 --- /dev/null +++ b/packages/tldraw/src/components/shared/dropdown-menu.tsx @@ -0,0 +1,173 @@ +import * as React from 'react' +import { CheckIcon, ChevronRightIcon } from '@radix-ui/react-icons' +import { + Root as DMRoot, + TriggerItem as DMTriggerItem, + Separator as DMSeparator, + Item as DMItem, + Arrow as DMArrow, + Content as DMContent, + Trigger as DMTrigger, + ItemIndicator as DMItemIndicator, + CheckboxItem as DMCheckboxItem, +} from '@radix-ui/react-dropdown-menu' + +import { Tooltip } from './tooltip' +import { breakpoints } from './breakpoints' +import { RowButton } from './row-button' +import { IconButton } from './icon-button' +import { IconWrapper } from './icon-wrapper' +import { MenuContent } from './menu' + +import styled from '~styles' + +/* -------------------------------------------------- */ +/* Dropdown Menu */ +/* -------------------------------------------------- */ + +export interface DropdownMenuRootProps { + isOpen?: boolean + onOpenChange?: (isOpen: boolean) => void + children: React.ReactNode +} + +export function DropdownMenuRoot({ + isOpen, + onOpenChange, + children, +}: DropdownMenuRootProps): JSX.Element { + return ( + + {children} + + ) +} + +export interface DropdownMenuSubMenuProps { + label: string + disabled?: boolean + children: React.ReactNode +} + +export function DropdownMenuSubMenu({ + children, + disabled = false, + label, +}: DropdownMenuSubMenuProps): JSX.Element { + return ( + + + {label} + + + + + + {children} + + + + ) +} + +export const DropdownMenuDivider = styled(DMSeparator, { + backgroundColor: '$hover', + height: 1, + marginTop: '$2', + marginRight: '-$2', + marginBottom: '$2', + marginLeft: '-$2', +}) + +export const DropdownMenuArrow = styled(DMArrow, { + fill: '$panel', +}) + +export interface DropdownMenuButtonProps { + onSelect?: () => void + disabled?: boolean + children: React.ReactNode +} + +export function DropdownMenuButton({ + onSelect, + children, + disabled = false, +}: DropdownMenuButtonProps): JSX.Element { + return ( + + {children} + + ) +} + +interface DropdownMenuIconButtonProps { + onSelect: () => void + disabled?: boolean + children: React.ReactNode +} + +export function DropdownMenuIconButton({ + onSelect, + children, + disabled = false, +}: DropdownMenuIconButtonProps): JSX.Element { + return ( + + {children} + + ) +} + +interface DropdownMenuIconTriggerButtonProps { + label: string + kbd?: string + disabled?: boolean + children: React.ReactNode +} + +export function DropdownMenuIconTriggerButton({ + label, + kbd, + children, + disabled = false, +}: DropdownMenuIconTriggerButtonProps): JSX.Element { + return ( + + + {children} + + + ) +} + +interface MenuCheckboxItemProps { + checked: boolean + disabled?: boolean + onCheckedChange: (isChecked: boolean) => void + children: React.ReactNode +} + +export function DropdownMenuCheckboxItem({ + checked, + disabled = false, + onCheckedChange, + children, +}: MenuCheckboxItemProps): JSX.Element { + return ( + + {children} + + + + + + + ) +} diff --git a/packages/tldraw/src/components/shared/floating-container.tsx b/packages/tldraw/src/components/shared/floating-container.tsx new file mode 100644 index 000000000..173ac5226 --- /dev/null +++ b/packages/tldraw/src/components/shared/floating-container.tsx @@ -0,0 +1,44 @@ +import styled from '~styles' + +/* -------------------------------------------------- */ +/* Floating Container */ +/* -------------------------------------------------- */ + +export const FloatingContainer = styled('div', { + backgroundColor: '$panel', + border: '1px solid $panel', + borderRadius: '4px', + boxShadow: '$4', + display: 'flex', + height: 'fit-content', + padding: '$0', + pointerEvents: 'all', + position: 'relative', + userSelect: 'none', + zIndex: 200, + + variants: { + direction: { + row: { + flexDirection: 'row', + }, + column: { + flexDirection: 'column', + }, + }, + elevation: { + 0: { + boxShadow: 'none', + }, + 2: { + boxShadow: '$2', + }, + 3: { + boxShadow: '$3', + }, + 4: { + boxShadow: '$4', + }, + }, + }, +}) diff --git a/packages/tldraw/src/components/shared/icon-button.tsx b/packages/tldraw/src/components/shared/icon-button.tsx new file mode 100644 index 000000000..83685ca05 --- /dev/null +++ b/packages/tldraw/src/components/shared/icon-button.tsx @@ -0,0 +1,84 @@ +import styled from '~styles' + +/* -------------------------------------------------- */ +/* Icon Button */ +/* -------------------------------------------------- */ + +export const IconButton = styled('button', { + position: 'relative', + height: '32px', + width: '32px', + backgroundColor: '$panel', + borderRadius: '4px', + padding: '0', + margin: '0', + display: 'grid', + alignItems: 'center', + justifyContent: 'center', + outline: 'none', + border: 'none', + pointerEvents: 'all', + fontSize: '$0', + color: '$text', + cursor: 'pointer', + + '& > *': { + gridRow: 1, + gridColumn: 1, + }, + + '&:disabled': { + opacity: '0.5', + }, + + '& > span': { + width: '100%', + height: '100%', + display: 'flex', + alignItems: 'center', + }, + + variants: { + bp: { + mobile: { + backgroundColor: 'transparent', + }, + small: { + '&:hover:not(:disabled)': { + backgroundColor: '$hover', + }, + }, + }, + size: { + small: { + height: 32, + width: 32, + '& svg:nth-of-type(1)': { + height: '16px', + width: '16px', + }, + }, + medium: { + height: 44, + width: 44, + '& svg:nth-of-type(1)': { + height: '18px', + width: '18px', + }, + }, + large: { + height: 44, + width: 44, + '& svg:nth-of-type(1)': { + height: '20px', + width: '20px', + }, + }, + }, + isActive: { + true: { + color: '$selected', + }, + }, + }, +}) diff --git a/packages/tldraw/src/components/shared/icon-wrapper.tsx b/packages/tldraw/src/components/shared/icon-wrapper.tsx new file mode 100644 index 000000000..2d0750ae1 --- /dev/null +++ b/packages/tldraw/src/components/shared/icon-wrapper.tsx @@ -0,0 +1,47 @@ +import styled from '~styles' + +/* -------------------------------------------------- */ +/* Icon Wrapper */ +/* -------------------------------------------------- */ + +export const IconWrapper = styled('div', { + height: '100%', + borderRadius: '4px', + marginRight: '1px', + display: 'grid', + alignItems: 'center', + justifyContent: 'center', + outline: 'none', + border: 'none', + pointerEvents: 'all', + cursor: 'pointer', + color: '$text', + + '& svg': { + height: 22, + width: 22, + strokeWidth: 1, + }, + + '& > *': { + gridRow: 1, + gridColumn: 1, + }, + + variants: { + size: { + small: { + '& svg': { + height: '16px', + width: '16px', + }, + }, + medium: { + '& svg': { + height: '22px', + width: '22px', + }, + }, + }, + }, +}) diff --git a/packages/tldraw/src/components/shared/index.ts b/packages/tldraw/src/components/shared/index.ts new file mode 100644 index 000000000..64b34a6b9 --- /dev/null +++ b/packages/tldraw/src/components/shared/index.ts @@ -0,0 +1,13 @@ +export * from './breakpoints' +export * from './buttons-row' +export * from './context-menu' +export * from './dialog' +export * from './dropdown-menu' +export * from './floating-container' +export * from './icon-button' +export * from './icon-wrapper' +export * from './kbd' +export * from './menu' +export * from './radio-group' +export * from './row-button' +export * from './tooltip' diff --git a/packages/tldraw/src/components/shared/kbd.tsx b/packages/tldraw/src/components/shared/kbd.tsx new file mode 100644 index 000000000..6a7171ba8 --- /dev/null +++ b/packages/tldraw/src/components/shared/kbd.tsx @@ -0,0 +1,64 @@ +import * as React from 'react' +import styled from '~styles' +import { Utils } from '@tldraw/core' + +/* -------------------------------------------------- */ +/* Keyboard Shortcut */ +/* -------------------------------------------------- */ + +export function commandKey(): string { + return Utils.isDarwin() ? '⌘' : 'Ctrl' +} + +export function Kbd({ + variant, + children, +}: { + variant: 'tooltip' | 'menu' + children: string +}): JSX.Element | null { + return ( + + {children + .replaceAll('#', commandKey()) + .split('') + .map((k, i) => ( + {k} + ))} + + ) +} + +export const StyledKbd = styled('kbd', { + marginLeft: '$3', + textShadow: '$2', + textAlign: 'center', + fontSize: '$0', + fontFamily: '$ui', + fontWeight: 400, + gap: '$1', + display: 'flex', + alignItems: 'center', + + '& > span': { + padding: '$0', + borderRadius: '$0', + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + }, + + variants: { + variant: { + tooltip: { + '& > span': { + background: '$overlayContrast', + boxShadow: '$key', + width: '20px', + height: '20px', + }, + }, + menu: {}, + }, + }, +}) diff --git a/packages/tldraw/src/components/shared/menu.tsx b/packages/tldraw/src/components/shared/menu.tsx new file mode 100644 index 000000000..5739f23fd --- /dev/null +++ b/packages/tldraw/src/components/shared/menu.tsx @@ -0,0 +1,62 @@ +import { breakpoints } from './breakpoints' +import styled from '~styles' +import { RowButton } from './row-button' + +/* -------------------------------------------------- */ +/* Menu */ +/* -------------------------------------------------- */ + +export const MenuContent = styled('div', { + position: 'relative', + overflow: 'hidden', + userSelect: 'none', + zIndex: 180, + minWidth: 180, + pointerEvents: 'all', + backgroundColor: '$panel', + border: '1px solid $panel', + padding: '$0', + boxShadow: '$4', + borderRadius: '4px', + font: '$ui', +}) + +export const Divider = styled('div', { + backgroundColor: '$hover', + height: 1, + marginTop: '$2', + marginRight: '-$2', + marginBottom: '$2', + marginLeft: '-$2', +}) + +export function MenuButton({ + warn, + onSelect, + children, + disabled = false, +}: { + warn?: boolean + onSelect?: () => void + disabled?: boolean + children: React.ReactNode +}): JSX.Element { + return ( + + {children} + + ) +} + +export const MenuTextInput = styled('input', { + backgroundColor: '$panel', + border: 'none', + padding: '$4 $3', + width: '100%', + outline: 'none', + background: '$input', + borderRadius: '4px', + fontFamily: '$ui', + fontSize: '$1', + userSelect: 'all', +}) diff --git a/packages/tldraw/src/components/shared/radio-group.tsx b/packages/tldraw/src/components/shared/radio-group.tsx new file mode 100644 index 000000000..f605967c7 --- /dev/null +++ b/packages/tldraw/src/components/shared/radio-group.tsx @@ -0,0 +1,10 @@ +import styled from '~styles' +import { Root as RGRoot } from '@radix-ui/react-radio-group' + +/* -------------------------------------------------- */ +/* Radio Group */ +/* -------------------------------------------------- */ + +export const Group = styled(RGRoot, { + display: 'flex', +}) diff --git a/packages/tldraw/src/components/shared/row-button.tsx b/packages/tldraw/src/components/shared/row-button.tsx new file mode 100644 index 000000000..a4d03aaaa --- /dev/null +++ b/packages/tldraw/src/components/shared/row-button.tsx @@ -0,0 +1,101 @@ +import styled from '~styles' + +/* -------------------------------------------------- */ +/* Row Button */ +/* -------------------------------------------------- */ + +export const RowButton = styled('button', { + position: 'relative', + display: 'flex', + width: '100%', + background: 'none', + height: '32px', + border: 'none', + cursor: 'pointer', + color: '$text', + outline: 'none', + alignItems: 'center', + fontFamily: '$ui', + fontWeight: 400, + fontSize: '$1', + justifyContent: 'space-between', + padding: '4px 8px 4px 12px', + borderRadius: 4, + userSelect: 'none', + + '& label': { + fontWeight: '$1', + margin: 0, + padding: 0, + }, + + '& svg': { + position: 'relative', + stroke: '$overlay', + strokeWidth: 1, + zIndex: 1, + }, + + '&[data-disabled]': { + opacity: 0.3, + }, + + '&:disabled': { + opacity: 0.3, + }, + + variants: { + bp: { + mobile: {}, + small: { + '& *[data-shy="true"]': { + opacity: 0, + }, + '&:hover:not(:disabled)': { + backgroundColor: '$hover', + '& *[data-shy="true"]': { + opacity: 1, + }, + }, + }, + }, + size: { + icon: { + padding: '4px ', + width: 'auto', + }, + }, + variant: { + noIcon: { + padding: '4px 12px', + }, + pageButton: { + display: 'grid', + gridTemplateColumns: '24px auto', + width: '100%', + paddingLeft: '$1', + gap: '$3', + justifyContent: 'flex-start', + [`& > *[data-state="checked"]`]: { + gridRow: 1, + gridColumn: 1, + }, + '& > span': { + gridRow: 1, + gridColumn: 2, + width: '100%', + }, + }, + }, + warn: { + true: { + color: '$warn', + }, + }, + isActive: { + true: { + backgroundColor: '$hover', + }, + }, + }, +}) diff --git a/packages/tldraw/src/components/shared/tooltip.tsx b/packages/tldraw/src/components/shared/tooltip.tsx new file mode 100644 index 000000000..76a387cc0 --- /dev/null +++ b/packages/tldraw/src/components/shared/tooltip.tsx @@ -0,0 +1,46 @@ +import * as RadixTooltip from '@radix-ui/react-tooltip' +import * as React from 'react' +import styled from '~styles' +import { Kbd } from './kbd' + +/* -------------------------------------------------- */ +/* Tooltip */ +/* -------------------------------------------------- */ + +interface TooltipProps { + children: React.ReactNode + label: string + kbd?: string + side?: 'bottom' | 'left' | 'right' | 'top' +} + +export function Tooltip({ children, label, kbd, side = 'top' }: TooltipProps): JSX.Element { + return ( + + {children} + + {label} + {kbd ? {kbd} : null} + + + + ) +} + +const StyledContent = styled(RadixTooltip.Content, { + borderRadius: 3, + padding: '$3 $3 $3 $3', + fontSize: '$1', + backgroundColor: '$tooltipBg', + color: '$tooltipText', + boxShadow: '$3', + display: 'flex', + alignItems: 'center', + fontFamily: '$ui', + userSelect: 'none', +}) + +const StyledArrow = styled(RadixTooltip.Arrow, { + fill: '$tooltipBg', + margin: '0 8px', +}) diff --git a/packages/tldraw/src/components/style-panel/align-distribute.tsx b/packages/tldraw/src/components/style-panel/align-distribute.tsx new file mode 100644 index 000000000..d55df7a40 --- /dev/null +++ b/packages/tldraw/src/components/style-panel/align-distribute.tsx @@ -0,0 +1,136 @@ +import * as React from 'react' +import { + AlignBottomIcon, + AlignCenterHorizontallyIcon, + AlignCenterVerticallyIcon, + AlignLeftIcon, + AlignRightIcon, + AlignTopIcon, + SpaceEvenlyHorizontallyIcon, + SpaceEvenlyVerticallyIcon, + StretchHorizontallyIcon, + StretchVerticallyIcon, +} from '@radix-ui/react-icons' +import { AlignType, DistributeType, StretchType } from '~types' +import { useTLDrawContext } from '~hooks' +import { breakpoints, ButtonsRow, IconButton } from '../shared' + +export interface AlignDistributeProps { + hasTwoOrMore: boolean + hasThreeOrMore: boolean +} + +export const AlignDistribute = React.memo( + ({ hasTwoOrMore, hasThreeOrMore }: AlignDistributeProps): JSX.Element => { + const { tlstate } = useTLDrawContext() + + const alignTop = React.useCallback(() => { + tlstate.align(AlignType.Top) + }, [tlstate]) + + const alignCenterVertical = React.useCallback(() => { + tlstate.align(AlignType.CenterVertical) + }, [tlstate]) + + const alignBottom = React.useCallback(() => { + tlstate.align(AlignType.Bottom) + }, [tlstate]) + + const stretchVertically = React.useCallback(() => { + tlstate.stretch(StretchType.Vertical) + }, [tlstate]) + + const distributeVertically = React.useCallback(() => { + tlstate.distribute(DistributeType.Vertical) + }, [tlstate]) + + const alignLeft = React.useCallback(() => { + tlstate.align(AlignType.Left) + }, [tlstate]) + + const alignCenterHorizontal = React.useCallback(() => { + tlstate.align(AlignType.CenterHorizontal) + }, [tlstate]) + + const alignRight = React.useCallback(() => { + tlstate.align(AlignType.Right) + }, [tlstate]) + + const stretchHorizontally = React.useCallback(() => { + tlstate.stretch(StretchType.Horizontal) + }, [tlstate]) + + const distributeHorizontally = React.useCallback(() => { + tlstate.distribute(DistributeType.Horizontal) + }, [tlstate]) + + return ( + <> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ) + } +) diff --git a/packages/tldraw/src/components/style-panel/index.ts b/packages/tldraw/src/components/style-panel/index.ts new file mode 100644 index 000000000..01bd999c5 --- /dev/null +++ b/packages/tldraw/src/components/style-panel/index.ts @@ -0,0 +1 @@ +export * from './style-panel' diff --git a/components/style-panel/quick-color-select.tsx b/packages/tldraw/src/components/style-panel/quick-color-select.tsx similarity index 54% rename from components/style-panel/quick-color-select.tsx rename to packages/tldraw/src/components/style-panel/quick-color-select.tsx index e1c9103d9..1a1355389 100644 --- a/components/style-panel/quick-color-select.tsx +++ b/packages/tldraw/src/components/style-panel/quick-color-select.tsx @@ -1,18 +1,23 @@ +import * as React from 'react' import * as DropdownMenu from '@radix-ui/react-dropdown-menu' -import { DropdownMenuIconTriggerButton } from 'components/shared' -import { strokes } from 'state/shape-styles' -import state, { useSelector } from 'state' -import { BoxIcon, StyleDropdownItem, StyleDropdownContent } from './shared' -import { useTheme } from 'next-themes' -import { ColorStyle } from 'types' +import { BoxIcon, StyleDropdownItem, StyleDropdownContent } from './styled' +import { DropdownMenuIconTriggerButton } from '../shared' +import { strokes } from '~shape' +import { useTheme, useTLDrawContext } from '~hooks' +import type { Data, ColorStyle } from '~types' -function handleColorChange(color: ColorStyle): void { - state.send('CHANGED_STYLE', { color }) -} +const selectColor = (s: Data) => s.appState.selectedStyle.color -export default function QuickColorSelect(): JSX.Element { - const color = useSelector((s) => s.values.selectedStyle.color) +export const QuickColorSelect = React.memo((): JSX.Element => { const { theme } = useTheme() + const { tlstate, useSelector } = useTLDrawContext() + + const color = useSelector(selectColor) + + const handleColorChange = React.useCallback( + (color) => tlstate.style({ color: color as ColorStyle }), + [tlstate] + ) return ( @@ -21,11 +26,11 @@ export default function QuickColorSelect(): JSX.Element { - {Object.keys(strokes[theme]).map((colorStyle: ColorStyle) => ( + {Object.keys(strokes[theme]).map((colorStyle: string) => ( ))} @@ -42,4 +47,4 @@ export default function QuickColorSelect(): JSX.Element { ) -} +}) diff --git a/components/style-panel/quick-dash-select.tsx b/packages/tldraw/src/components/style-panel/quick-dash-select.tsx similarity index 58% rename from components/style-panel/quick-dash-select.tsx rename to packages/tldraw/src/components/style-panel/quick-dash-select.tsx index 78da7e37f..6423cf0b1 100644 --- a/components/style-panel/quick-dash-select.tsx +++ b/packages/tldraw/src/components/style-panel/quick-dash-select.tsx @@ -1,8 +1,6 @@ -import React, { memo } from 'react' +import * as React from 'react' import * as DropdownMenu from '@radix-ui/react-dropdown-menu' -import { DropdownMenuIconTriggerButton } from 'components/shared' -import state, { useSelector } from 'state' -import { DashStyle } from 'types' +import { DropdownMenuIconTriggerButton } from '../shared' import { DashDrawIcon, DashDottedIcon, @@ -10,7 +8,9 @@ import { DashDashedIcon, StyleDropdownContent, StyleDropdownItem, -} from './shared' +} from './styled' +import { useTLDrawContext } from '~hooks' +import { DashStyle, Data } from '~types' const dashes = { [DashStyle.Draw]: , @@ -19,18 +19,21 @@ const dashes = { [DashStyle.Dotted]: , } -function changeDashStyle(dash: DashStyle): void { - state.send('CHANGED_STYLE', { dash }) -} +const selectDash = (s: Data) => s.appState.selectedStyle.dash -function QuickdashSelect(): JSX.Element { - const dash = useSelector((s) => s.values.selectedStyle.dash) +export const QuickDashSelect = React.memo((): JSX.Element => { + const { tlstate, useSelector } = useTLDrawContext() + + const dash = useSelector(selectDash) + + const changeDashStyle = React.useCallback( + (dash) => tlstate.style({ dash: dash as DashStyle }), + [tlstate] + ) return ( - - {dashes[dash]} - + {dashes[dash]} - {Object.keys(DashStyle).map((dashStyle: DashStyle) => ( + {Object.keys(DashStyle).map((dashStyle: string) => ( - {dashes[dashStyle]} + {dashes[dashStyle as DashStyle]} ))} ) -} - -export default memo(QuickdashSelect) +}) diff --git a/packages/tldraw/src/components/style-panel/quick-fill-select.tsx b/packages/tldraw/src/components/style-panel/quick-fill-select.tsx new file mode 100644 index 000000000..c8efbbf4c --- /dev/null +++ b/packages/tldraw/src/components/style-panel/quick-fill-select.tsx @@ -0,0 +1,38 @@ +import * as React from 'react' +import * as Checkbox from '@radix-ui/react-checkbox' +import { BoxIcon, IsFilledFillIcon } from './styled' +import { breakpoints, Tooltip, IconButton, IconWrapper } from '../shared' +import { useTLDrawContext } from '~hooks' +import type { Data } from '~types' + +const isFilledSelector = (s: Data) => s.appState.selectedStyle.isFilled + +export const QuickFillSelect = React.memo((): JSX.Element => { + const { tlstate, useSelector } = useTLDrawContext() + + const isFilled = useSelector(isFilledSelector) + + const handleIsFilledChange = React.useCallback( + (isFilled: boolean) => tlstate.style({ isFilled }), + [tlstate] + ) + + return ( + + + + + + + + + + + ) +}) diff --git a/components/style-panel/quick-size-select.tsx b/packages/tldraw/src/components/style-panel/quick-size-select.tsx similarity index 51% rename from components/style-panel/quick-size-select.tsx rename to packages/tldraw/src/components/style-panel/quick-size-select.tsx index 535ac7ee9..8cb97ba90 100644 --- a/components/style-panel/quick-size-select.tsx +++ b/packages/tldraw/src/components/style-panel/quick-size-select.tsx @@ -1,10 +1,10 @@ -import { memo } from 'react' +import * as React from 'react' import * as DropdownMenu from '@radix-ui/react-dropdown-menu' -import { DropdownMenuIconTriggerButton } from 'components/shared' -import { Circle } from 'react-feather' -import state, { useSelector } from 'state' -import { SizeStyle } from 'types' -import { StyleDropdownContent, StyleDropdownItem } from './shared' +import { DropdownMenuIconTriggerButton } from '../shared/dropdown-menu' +import { CircleIcon } from '../icons' +import { StyleDropdownContent, StyleDropdownItem } from './styled' +import { Data, SizeStyle } from '~types' +import { useTLDrawContext } from '~hooks' const sizes = { [SizeStyle.Small]: 6, @@ -12,17 +12,22 @@ const sizes = { [SizeStyle.Large]: 22, } -function changeSizeStyle(size: SizeStyle): void { - state.send('CHANGED_STYLE', { size }) -} +const selectSize = (s: Data) => s.appState.selectedStyle.size -function QuickSizeSelect(): JSX.Element { - const size = useSelector((s) => s.values.selectedStyle.size) +export const QuickSizeSelect = React.memo((): JSX.Element => { + const { tlstate, useSelector } = useTLDrawContext() + + const size = useSelector(selectSize) + + const changeSizeStyle = React.useCallback( + (size: string) => tlstate.style({ size: size as SizeStyle }), + [tlstate] + ) return ( - + - {Object.keys(SizeStyle).map((sizeStyle: SizeStyle) => ( + {Object.keys(SizeStyle).map((sizeStyle: string) => ( - + ))} ) -} - -export default memo(QuickSizeSelect) +}) diff --git a/packages/tldraw/src/components/style-panel/shapes-functions.tsx b/packages/tldraw/src/components/style-panel/shapes-functions.tsx new file mode 100644 index 000000000..a015c4260 --- /dev/null +++ b/packages/tldraw/src/components/style-panel/shapes-functions.tsx @@ -0,0 +1,215 @@ +import * as React from 'react' +import { IconButton, ButtonsRow, breakpoints } from '../shared' +import { Trash } from '../icons' +import { Tooltip } from '../shared/tooltip' +import { + ArrowDownIcon, + ArrowUpIcon, + AspectRatioIcon, + CopyIcon, + GroupIcon, + LockClosedIcon, + LockOpen1Icon, + PinBottomIcon, + PinTopIcon, + RotateCounterClockwiseIcon, +} from '@radix-ui/react-icons' +import { useTLDrawContext } from '~hooks' +import type { Data } from '~types' + +const isAllLockedSelector = (s: Data) => { + const page = s.document.pages[s.appState.currentPageId] + const { selectedIds } = s.document.pageStates[s.appState.currentPageId] + return selectedIds.every((id) => page.shapes[id].isLocked) +} + +const isAllAspectLockedSelector = (s: Data) => { + const page = s.document.pages[s.appState.currentPageId] + const { selectedIds } = s.document.pageStates[s.appState.currentPageId] + return selectedIds.every((id) => page.shapes[id].isAspectRatioLocked) +} + +const isAllGroupedSelector = (s: Data) => { + const page = s.document.pages[s.appState.currentPageId] + const selectedShapes = s.document.pageStates[s.appState.currentPageId].selectedIds.map( + (id) => page.shapes[id] + ) + + return selectedShapes.every( + (shape) => + shape.children !== undefined || + (shape.parentId === selectedShapes[0].parentId && + selectedShapes[0].parentId !== s.appState.currentPageId) + ) +} + +const hasSelectionSelector = (s: Data) => { + const { selectedIds } = s.document.pageStates[s.appState.currentPageId] + return selectedIds.length > 0 +} + +const hasMultipleSelectionSelector = (s: Data) => { + const { selectedIds } = s.document.pageStates[s.appState.currentPageId] + return selectedIds.length > 1 +} + +export const ShapesFunctions = React.memo(() => { + const { tlstate, useSelector } = useTLDrawContext() + + const isAllLocked = useSelector(isAllLockedSelector) + + const isAllAspectLocked = useSelector(isAllAspectLockedSelector) + + const isAllGrouped = useSelector(isAllGroupedSelector) + + const hasSelection = useSelector(hasSelectionSelector) + + const hasMultipleSelection = useSelector(hasMultipleSelectionSelector) + + const handleRotate = React.useCallback(() => { + tlstate.rotate() + }, [tlstate]) + + const handleDuplicate = React.useCallback(() => { + tlstate.duplicate() + }, [tlstate]) + + const handleToggleLocked = React.useCallback(() => { + tlstate.toggleLocked() + }, [tlstate]) + + const handleToggleAspectRatio = React.useCallback(() => { + tlstate.toggleAspectRatioLocked() + }, [tlstate]) + + const handleGroup = React.useCallback(() => { + tlstate.group() + }, [tlstate]) + + const handleMoveToBack = React.useCallback(() => { + tlstate.moveToBack() + }, [tlstate]) + + const handleMoveBackward = React.useCallback(() => { + tlstate.moveBackward() + }, [tlstate]) + + const handleMoveForward = React.useCallback(() => { + tlstate.moveForward() + }, [tlstate]) + + const handleMoveToFront = React.useCallback(() => { + tlstate.moveToFront() + }, [tlstate]) + + const handleDelete = React.useCallback(() => { + tlstate.delete() + }, [tlstate]) + + return ( + <> + + + + + + + + + + + + + + + + {isAllLocked ? : } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ) +}) diff --git a/packages/tldraw/src/components/style-panel/style-panel.test.tsx b/packages/tldraw/src/components/style-panel/style-panel.test.tsx new file mode 100644 index 000000000..985c597b6 --- /dev/null +++ b/packages/tldraw/src/components/style-panel/style-panel.test.tsx @@ -0,0 +1,9 @@ +import * as React from 'react' +import { renderWithContext } from '~test' +import { StylePanel } from './style-panel' + +describe('style panel', () => { + test('mounts component without crashing', () => { + renderWithContext() + }) +}) diff --git a/packages/tldraw/src/components/style-panel/style-panel.tsx b/packages/tldraw/src/components/style-panel/style-panel.tsx new file mode 100644 index 000000000..288f2d79a --- /dev/null +++ b/packages/tldraw/src/components/style-panel/style-panel.tsx @@ -0,0 +1,97 @@ +import * as React from 'react' +import { Utils } from '@tldraw/core' +import { DotsHorizontalIcon, Cross2Icon } from '@radix-ui/react-icons' +import { useTLDrawContext } from '~hooks' +import type { Data } from '~types' +import { ShapesFunctions } from './shapes-functions' +import { AlignDistribute } from './align-distribute' +import { QuickColorSelect } from './quick-color-select' +import { QuickSizeSelect } from './quick-size-select' +import { QuickDashSelect } from './quick-dash-select' +import { QuickFillSelect } from './quick-fill-select' +import { Tooltip } from '../shared/tooltip' +import { Kbd } from '../shared/kbd' +import { + IconButton, + ButtonsRow, + breakpoints, + RowButton, + FloatingContainer, + Divider, +} from '../shared' + +const isStyleOpenSelector = (s: Data) => s.appState.isStyleOpen + +export function StylePanel(): JSX.Element { + const { tlstate, useSelector } = useTLDrawContext() + const isOpen = useSelector(isStyleOpenSelector) + + return ( + + + + + + + + + {isOpen ? : } + + + + {isOpen && } + + ) +} + +const showKbds = !Utils.isMobileSize() + +const selectedShapesCountSelector = (s: Data) => + s.document.pageStates[s.appState.currentPageId].selectedIds.length + +function SelectedShapeContent(): JSX.Element { + const { tlstate, useSelector } = useTLDrawContext() + const selectedShapesCount = useSelector(selectedShapesCountSelector) + + const handleCopy = React.useCallback(() => { + tlstate.copy() + }, [tlstate]) + + const handlePaste = React.useCallback(() => { + tlstate.paste() + }, [tlstate]) + + const handleCopySvg = React.useCallback(() => { + tlstate.copySvg() + }, [tlstate]) + + return ( + <> + + + + 1} + hasThreeOrMore={selectedShapesCount > 2} + /> + + + Copy + {showKbds && #C} + + + Paste + {showKbds && #V} + + + Copy to SVG + {showKbds && ⇧#C} + + + ) +} diff --git a/components/style-panel/shared.tsx b/packages/tldraw/src/components/style-panel/styled.tsx similarity index 95% rename from components/style-panel/shared.tsx rename to packages/tldraw/src/components/style-panel/styled.tsx index 5e60e082c..44e87dc3b 100644 --- a/components/style-panel/shared.tsx +++ b/packages/tldraw/src/components/style-panel/styled.tsx @@ -1,5 +1,5 @@ import * as React from 'react' -import styled from 'styles' +import styled from '~styles' export const StyleDropdownContent = styled('div', { display: 'grid', @@ -87,32 +87,15 @@ export function BoxIcon({ export function DashSolidIcon(): JSX.Element { return ( - - + + ) } export function DashDashedIcon(): JSX.Element { return ( - + + { + test('mounts component without crashing', () => { + render() + }) +}) diff --git a/packages/tldraw/src/components/tldraw/tldraw.tsx b/packages/tldraw/src/components/tldraw/tldraw.tsx new file mode 100644 index 000000000..c8ba14a29 --- /dev/null +++ b/packages/tldraw/src/components/tldraw/tldraw.tsx @@ -0,0 +1,241 @@ +import * as React from 'react' +import { IdProvider } from '@radix-ui/react-id' +import { Renderer } from '@tldraw/core' +import styled from '~styles' +import type { Data, TLDrawDocument } from '~types' +import { TLDrawState } from '~state' +import { TLDrawContext, useCustomFonts, useKeyboardShortcuts, useTLDrawContext } from '~hooks' +import { tldrawShapeUtils } from '~shape' +import { ContextMenu } from '~components/context-menu' +import { StylePanel } from '~components/style-panel' +import { ToolsPanel } from '~components/tools-panel' +import { PagePanel } from '~components/page-panel' +import { Menu } from '~components/menu' + +// Selectors +const isInSelectSelector = (s: Data) => s.appState.activeTool === 'select' + +const isSelectedShapeWithHandlesSelector = (s: Data) => { + const { shapes } = s.document.pages[s.appState.currentPageId] + const { selectedIds } = s.document.pageStates[s.appState.currentPageId] + return selectedIds.length === 1 && selectedIds.every((id) => shapes[id].handles !== undefined) +} + +const pageSelector = (s: Data) => s.document.pages[s.appState.currentPageId] + +const pageStateSelector = (s: Data) => s.document.pageStates[s.appState.currentPageId] + +const isDarkModeSelector = (s: Data) => s.settings.isDarkMode + +export interface TLDrawProps { + /** + * (optional) If provided, the component will load / persist state under this key. + */ + id?: string + /** + * (optional) The document to load or update from. + */ + document?: TLDrawDocument + /** + * (optional) The current page id. + */ + currentPageId?: string + /** + * (optional) A callback to run when the component mounts. + */ + onMount?: (state: TLDrawState) => void + /** + * (optional) A callback to run when the component's state changes. + */ + onChange?: TLDrawState['_onChange'] +} + +export function TLDraw({ id, document, currentPageId, onMount, onChange }: TLDrawProps) { + const [tlstate, setTlstate] = React.useState(() => new TLDrawState(id)) + + React.useEffect(() => { + setTlstate(new TLDrawState(id, onChange, onMount)) + }, [id]) + + const [context] = React.useState(() => { + return { tlstate, useSelector: tlstate.useStore } + }) + + React.useEffect(() => { + if (!document) return + tlstate.loadDocument(document) + }, [document, tlstate]) + + React.useEffect(() => { + if (!currentPageId) return + tlstate.changePage(currentPageId) + }, [currentPageId, tlstate]) + + return ( + + + + + + ) +} + +function InnerTldraw() { + useCustomFonts() + + const { tlstate, useSelector } = useTLDrawContext() + + useKeyboardShortcuts() + + const page = useSelector(pageSelector) + + const pageState = useSelector(pageStateSelector) + + const isDarkMode = useSelector(isDarkModeSelector) + + const isSelecting = useSelector(isInSelectSelector) + + const isSelectedHandlesShape = useSelector(isSelectedShapeWithHandlesSelector) + + const isInSession = tlstate.session !== undefined + + // Hide bounds when not using the select tool, or when the only selected shape has handles + const hideBounds = + (tlstate.session && tlstate.session.id !== 'brush') || !isSelecting || isSelectedHandlesShape + + // Hide bounds when not using the select tool, or when in session + const hideHandles = isInSession || !isSelecting + + // Hide indicators when not using the select tool, or when in session + const hideIndicators = isInSession || !isSelecting + + // Custom rendering meta, with dark mode for shapes + const meta = React.useMemo(() => ({ isDarkMode }), [isDarkMode]) + + // Custom theme, based on darkmode + const theme = React.useMemo(() => { + if (isDarkMode) { + return { + brushFill: 'rgba(180, 180, 180, .05)', + brushStroke: 'rgba(180, 180, 180, .25)', + selected: 'rgba(38, 150, 255, 1.000)', + selectFill: 'rgba(38, 150, 255, 0.05)', + background: '#343d45', + foreground: '#49555f', + } + } + + return {} + }, [isDarkMode]) + + return ( + + + + + + + + + + + + + ) +} + +const Spacer = styled('div', { + flexGrow: 2, +}) + +const MenuButtons = styled('div', { + display: 'flex', + gap: 8, +}) + +const Layout = styled('main', { + position: 'fixed', + overflow: 'hidden', + top: 0, + left: 0, + bottom: 0, + right: 0, + height: '100%', + width: '100%', + padding: '8px 8px 0 8px', + zIndex: 200, + display: 'flex', + alignItems: 'flex-start', + justifyContent: 'flex-start', + boxSizing: 'border-box', + outline: 'none', + pointerEvents: 'none', + + '& > *': { + pointerEvents: 'all', + }, + + '& .tl-container': { + position: 'absolute', + top: 0, + left: 0, + }, +}) diff --git a/packages/tldraw/src/components/tools-panel/back-to-content.tsx b/packages/tldraw/src/components/tools-panel/back-to-content.tsx new file mode 100644 index 000000000..15b5d1fae --- /dev/null +++ b/packages/tldraw/src/components/tools-panel/back-to-content.tsx @@ -0,0 +1,31 @@ +import * as React from 'react' +import { FloatingContainer, RowButton } from '../shared' +import styled from '~styles' +import type { Data } from '~types' +import { useTLDrawContext } from '~hooks' + +const isEmptyCanvasSelector = (s: Data) => + Object.keys(s.document.pages[s.appState.currentPageId].shapes).length > 0 && + s.appState.isEmptyCanvas + +export const BackToContent = React.memo(() => { + const { tlstate, useSelector } = useTLDrawContext() + + const isEmptyCanvas = useSelector(isEmptyCanvasSelector) + + if (!isEmptyCanvas) return null + + return ( + + Back to content + + ) +}) + +const BackToContentButton = styled(FloatingContainer, { + pointerEvents: 'all', + width: 'fit-content', + gridRow: 1, + flexGrow: 2, + display: 'block', +}) diff --git a/packages/tldraw/src/components/tools-panel/index.ts b/packages/tldraw/src/components/tools-panel/index.ts new file mode 100644 index 000000000..a2728adb6 --- /dev/null +++ b/packages/tldraw/src/components/tools-panel/index.ts @@ -0,0 +1 @@ +export * from './tools-panel' diff --git a/packages/tldraw/src/components/tools-panel/status-bar.tsx b/packages/tldraw/src/components/tools-panel/status-bar.tsx new file mode 100644 index 000000000..e644e9b5d --- /dev/null +++ b/packages/tldraw/src/components/tools-panel/status-bar.tsx @@ -0,0 +1,50 @@ +import * as React from 'react' +import { useTLDrawContext } from '~hooks' +import type { Data } from '~types' +import styled from '~styles' + +const statusSelector = (s: Data) => s.appState.status.current +const activeToolSelector = (s: Data) => s.appState.activeTool + +export function StatusBar(): JSX.Element | null { + const { useSelector } = useTLDrawContext() + const status = useSelector(statusSelector) + const activeTool = useSelector(activeToolSelector) + + return ( + +
+ {activeTool} | {status} +
+
+ ) +} + +const StatusBarContainer = styled('div', { + height: 40, + userSelect: 'none', + borderTop: '1px solid $border', + gridArea: 'status', + display: 'flex', + color: '$text', + justifyContent: 'space-between', + alignItems: 'center', + backgroundColor: '$panel', + gap: 8, + fontFamily: '$ui', + fontSize: '$0', + padding: '0 16px', + + variants: { + size: { + small: { + fontSize: '$1', + }, + }, + }, +}) + +const Section = styled('div', { + whiteSpace: 'nowrap', + overflow: 'hidden', +}) diff --git a/components/tools-panel/shared.tsx b/packages/tldraw/src/components/tools-panel/styled.tsx similarity index 96% rename from components/tools-panel/shared.tsx rename to packages/tldraw/src/components/tools-panel/styled.tsx index 4161d7def..bdc200525 100644 --- a/components/tools-panel/shared.tsx +++ b/packages/tldraw/src/components/tools-panel/styled.tsx @@ -1,6 +1,7 @@ -import { FloatingContainer } from 'components/shared' -import Tooltip from 'components/tooltip' -import styled from 'styles' +import * as React from 'react' +import { FloatingContainer } from '../shared' +import { Tooltip } from '../shared/tooltip' +import styled from '~styles' export const ToolButton = styled('button', { position: 'relative', diff --git a/packages/tldraw/src/components/tools-panel/tools-panel.test.tsx b/packages/tldraw/src/components/tools-panel/tools-panel.test.tsx new file mode 100644 index 000000000..12ba8d9f6 --- /dev/null +++ b/packages/tldraw/src/components/tools-panel/tools-panel.test.tsx @@ -0,0 +1,9 @@ +import * as React from 'react' +import { ToolsPanel } from './tools-panel' +import { renderWithContext } from '~test' + +describe('tools panel', () => { + test('mounts component without crashing', () => { + renderWithContext() + }) +}) diff --git a/components/tools-panel/tools-panel.tsx b/packages/tldraw/src/components/tools-panel/tools-panel.tsx similarity index 61% rename from components/tools-panel/tools-panel.tsx rename to packages/tldraw/src/components/tools-panel/tools-panel.tsx index 21edd1de9..a9927b5b7 100644 --- a/components/tools-panel/tools-panel.tsx +++ b/packages/tldraw/src/components/tools-panel/tools-panel.tsx @@ -1,3 +1,4 @@ +import * as React from 'react' import { ArrowTopRightIcon, CircleIcon, @@ -8,29 +9,52 @@ import { SquareIcon, TextIcon, } from '@radix-ui/react-icons' -import * as React from 'react' -import state, { useSelector } from 'state' -import StatusBar from 'components/status-bar' -import { FloatingContainer } from 'components/shared' -import { PrimaryButton, SecondaryButton } from './shared' -import styled from 'styles' -import { ShapeType } from 'types' -import UndoRedo from './undo-redo' -import Zoom from './zoom' -import BackToContent from './back-to-content' +import styled from '~styles' +import { Data, TLDrawShapeType } from '~types' +import { useTLDrawContext } from '~hooks' +import { StatusBar } from './status-bar' +import { FloatingContainer } from '../shared' +import { PrimaryButton, SecondaryButton } from './styled' +import { UndoRedo } from './undo-redo' +import { Zoom } from './zoom' +import { BackToContent } from './back-to-content' -const selectArrowTool = () => state.send('SELECTED_ARROW_TOOL') -const selectDrawTool = () => state.send('SELECTED_DRAW_TOOL') -const selectEllipseTool = () => state.send('SELECTED_ELLIPSE_TOOL') -const selectTextTool = () => state.send('SELECTED_TEXT_TOOL') -const selectRectangleTool = () => state.send('SELECTED_RECTANGLE_TOOL') -const selectSelectTool = () => state.send('SELECTED_SELECT_TOOL') -const toggleToolLock = () => state.send('TOGGLED_TOOL_LOCK') +const activeToolSelector = (s: Data) => s.appState.activeTool +const isToolLockedSelector = (s: Data) => s.appState.isToolLocked +const isDebugModeSelector = (s: Data) => s.settings.isDebugMode -export default function ToolsPanel(): JSX.Element { - const activeTool = useSelector((s) => s.data.activeTool) +export const ToolsPanel = React.memo((): JSX.Element => { + const { tlstate, useSelector } = useTLDrawContext() - const isToolLocked = useSelector((s) => s.data.settings.isToolLocked) + const activeTool = useSelector(activeToolSelector) + + const isToolLocked = useSelector(isToolLockedSelector) + + const isDebugMode = useSelector(isDebugModeSelector) + + const selectSelectTool = React.useCallback(() => { + tlstate.selectTool('select') + }, [tlstate]) + + const selectDrawTool = React.useCallback(() => { + tlstate.selectTool(TLDrawShapeType.Draw) + }, [tlstate]) + + const selectRectangleTool = React.useCallback(() => { + tlstate.selectTool(TLDrawShapeType.Rectangle) + }, [tlstate]) + + const selectEllipseTool = React.useCallback(() => { + tlstate.selectTool(TLDrawShapeType.Ellipse) + }, [tlstate]) + + const selectArrowTool = React.useCallback(() => { + tlstate.selectTool(TLDrawShapeType.Arrow) + }, [tlstate]) + + const selectTextTool = React.useCallback(() => { + tlstate.selectTool(TLDrawShapeType.Text) + }, [tlstate]) return ( @@ -52,41 +76,41 @@ export default function ToolsPanel(): JSX.Element { @@ -97,7 +121,7 @@ export default function ToolsPanel(): JSX.Element { {isToolLocked ? : } @@ -105,12 +129,14 @@ export default function ToolsPanel(): JSX.Element { - - - + {isDebugMode && ( + + + + )} ) -} +}) const ToolsPanelContainer = styled('div', { position: 'fixed', @@ -122,11 +148,16 @@ const ToolsPanelContainer = styled('div', { maxWidth: '100%', display: 'grid', gridTemplateColumns: '1fr auto 1fr', + gridTemplateRows: 'auto auto', padding: '0', alignItems: 'flex-end', zIndex: 200, gridGap: '$4', gridRowGap: '$4', + pointerEvents: 'none', + '& > div > *': { + pointerEvents: 'all', + }, }) const CenterWrap = styled('div', { diff --git a/packages/tldraw/src/components/tools-panel/undo-redo.tsx b/packages/tldraw/src/components/tools-panel/undo-redo.tsx new file mode 100644 index 000000000..4bef0ead8 --- /dev/null +++ b/packages/tldraw/src/components/tools-panel/undo-redo.tsx @@ -0,0 +1,30 @@ +import * as React from 'react' +import { useTLDrawContext } from '~hooks' +import { TertiaryButton, TertiaryButtonsContainer } from './styled' +import { Undo, Redo, Trash } from '../icons' + +export const UndoRedo = React.memo((): JSX.Element => { + const { tlstate } = useTLDrawContext() + + const handleDelete = React.useCallback(() => { + tlstate.delete() + }, [tlstate]) + + const handleClear = React.useCallback(() => { + tlstate.clear() + }, [tlstate]) + + return ( + + + + + + + + + + + + ) +}) diff --git a/packages/tldraw/src/components/tools-panel/zoom.tsx b/packages/tldraw/src/components/tools-panel/zoom.tsx new file mode 100644 index 000000000..cc1dd6127 --- /dev/null +++ b/packages/tldraw/src/components/tools-panel/zoom.tsx @@ -0,0 +1,39 @@ +import * as React from 'react' +import { ZoomInIcon, ZoomOutIcon } from '@radix-ui/react-icons' +import { TertiaryButton, TertiaryButtonsContainer } from './styled' +import { useTLDrawContext } from '~hooks' +import type { Data } from '~types' + +export const Zoom = React.memo((): JSX.Element => { + const { tlstate } = useTLDrawContext() + + return ( + + + + + + + + + + ) +}) + +const zoomSelector = (s: Data) => s.document.pageStates[s.appState.currentPageId].camera.zoom + +function ZoomCounter() { + const { tlstate, useSelector } = useTLDrawContext() + const zoom = useSelector(zoomSelector) + + return ( + + {Math.round(zoom * 100)}% + + ) +} diff --git a/packages/tldraw/src/hooks/index.ts b/packages/tldraw/src/hooks/index.ts new file mode 100644 index 000000000..bf38556de --- /dev/null +++ b/packages/tldraw/src/hooks/index.ts @@ -0,0 +1,4 @@ +export * from './useKeyboardShortcuts' +export * from './useTLDrawContext' +export * from './useTheme' +export * from './useCustomFonts' diff --git a/packages/tldraw/src/hooks/useCustomFonts.ts b/packages/tldraw/src/hooks/useCustomFonts.ts new file mode 100644 index 000000000..c80a9c470 --- /dev/null +++ b/packages/tldraw/src/hooks/useCustomFonts.ts @@ -0,0 +1,9 @@ +import { useStyle, css } from '~hooks/useStyle' + +const customFonts = css` + @import url('https://fonts.googleapis.com/css2?family=Caveat+Brush&display=swap'); +` + +export function useCustomFonts() { + useStyle('tldraw-fonts', customFonts) +} diff --git a/packages/tldraw/src/hooks/useKeyboardShortcuts.tsx b/packages/tldraw/src/hooks/useKeyboardShortcuts.tsx new file mode 100644 index 000000000..7cedfc97d --- /dev/null +++ b/packages/tldraw/src/hooks/useKeyboardShortcuts.tsx @@ -0,0 +1,223 @@ +import * as React from 'react' +import { inputs } from '@tldraw/core' +import { useHotkeys } from 'react-hotkeys-hook' +import { TLDrawShapeType } from '~types' +import { useTLDrawContext } from '~hooks' + +export function useKeyboardShortcuts() { + const { tlstate } = useTLDrawContext() + + React.useEffect(() => { + const handleKeyDown = (e: KeyboardEvent) => { + const info = inputs.keydown(e) + tlstate.onKeyDown(e.key, info) + } + + const handleKeyUp = (e: KeyboardEvent) => { + const info = inputs.keyup(e) + tlstate.onKeyUp(e.key, info) + } + + window.addEventListener('keydown', handleKeyDown) + window.addEventListener('keyup', handleKeyUp) + + return () => { + window.removeEventListener('keydown', handleKeyDown) + window.removeEventListener('keyup', handleKeyUp) + } + }, [tlstate]) + + /* ---------------------- Tools --------------------- */ + + useHotkeys('v,1', () => { + tlstate.selectTool('select') + }) + + useHotkeys('d,2', () => { + tlstate.selectTool(TLDrawShapeType.Draw) + }) + + useHotkeys('r,3', () => { + tlstate.selectTool(TLDrawShapeType.Rectangle) + }) + + useHotkeys('e,4', () => { + tlstate.selectTool(TLDrawShapeType.Ellipse) + }) + + useHotkeys('a,5', () => { + tlstate.selectTool(TLDrawShapeType.Arrow) + }) + + useHotkeys('t,6', () => { + tlstate.selectTool(TLDrawShapeType.Text) + }) + + /* ---------------------- Misc ---------------------- */ + + // Save + + useHotkeys('ctrl+s,command+s', () => { + tlstate.saveProject() + }) + + // Undo Redo + + useHotkeys('command+z,ctrl+z', () => { + tlstate.undo() + }) + + useHotkeys('ctrl+shift-z,command+shift+z', () => { + tlstate.redo() + }) + + // Undo Redo + + useHotkeys('command+u,ctrl+u', () => { + tlstate.undoSelect() + }) + + useHotkeys('ctrl+shift-u,command+shift+u', () => { + tlstate.redoSelect() + }) + + /* -------------------- Commands -------------------- */ + + // Camera + + useHotkeys('ctrl+=,command+=', (e) => { + tlstate.zoomIn() + e.preventDefault() + }) + + useHotkeys('ctrl+-,command+-', (e) => { + tlstate.zoomOut() + e.preventDefault() + }) + + useHotkeys('shift+1', () => { + tlstate.zoomToFit() + }) + + useHotkeys('shift+2', () => { + tlstate.zoomToSelection() + }) + + useHotkeys('shift+0', () => { + tlstate.zoomToActual() + }) + + // Duplicate + + useHotkeys('ctrl+d,command+d', (e) => { + tlstate.duplicate() + e.preventDefault() + }) + + // Flip + + useHotkeys('shift+h', () => { + tlstate.flipHorizontal() + }) + + useHotkeys('shift+v', () => { + tlstate.flipVertical() + }) + + // Cancel + + useHotkeys('escape', () => { + tlstate.cancel() + }) + + // Delete + + useHotkeys('backspace', () => { + tlstate.delete() + }) + + // Select All + + useHotkeys('command+a,ctrl+a', () => { + tlstate.selectAll() + }) + + // Nudge + + useHotkeys('up', () => { + tlstate.nudge([0, -1], false) + }) + + useHotkeys('right', () => { + tlstate.nudge([1, 0], false) + }) + + useHotkeys('down', () => { + tlstate.nudge([0, 1], false) + }) + + useHotkeys('left', () => { + tlstate.nudge([-1, 0], false) + }) + + useHotkeys('shift+up', () => { + tlstate.nudge([0, -1], true) + }) + + useHotkeys('shift+right', () => { + tlstate.nudge([1, 0], true) + }) + + useHotkeys('shift+down', () => { + tlstate.nudge([0, 1], true) + }) + + useHotkeys('shift+left', () => { + tlstate.nudge([-1, 0], true) + }) + + // Copy & Paste + + useHotkeys('command+c,ctrl+c', () => { + tlstate.copy() + }) + + useHotkeys('command+v,ctrl+v', () => { + tlstate.paste() + }) + + // Group & Ungroup + + useHotkeys('command+g,ctrl+g', (e) => { + tlstate.group() + e.preventDefault() + }) + + useHotkeys('command+shift+g,ctrl+shift+g', (e) => { + tlstate.ungroup() + e.preventDefault() + }) + + // Move + + useHotkeys('[', () => { + tlstate.moveBackward() + }) + + useHotkeys(']', () => { + tlstate.moveForward() + }) + + useHotkeys('shift+[', () => { + tlstate.moveToBack() + }) + + useHotkeys('shift+]', () => { + tlstate.moveToFront() + }) + + useHotkeys('command+shift+backspace', (e) => { + tlstate.resetDocument() + e.preventDefault() + }) +} diff --git a/packages/tldraw/src/hooks/useStyle.ts b/packages/tldraw/src/hooks/useStyle.ts new file mode 100644 index 000000000..7aa82eb24 --- /dev/null +++ b/packages/tldraw/src/hooks/useStyle.ts @@ -0,0 +1,30 @@ +import * as React from 'react' + +const styles = new Map() + +export const css = (strings: TemplateStringsArray, ...args: unknown[]) => + strings.reduce( + (acc, string, index) => acc + string + (index < args.length ? args[index] : ''), + '' + ) + +export function useStyle(uid: string, rules: string) { + React.useLayoutEffect(() => { + if (styles.get(uid)) { + return () => void null + } + + const style = document.createElement('style') + style.innerHTML = rules + style.setAttribute('id', uid) + document.head.appendChild(style) + styles.set(uid, style) + + return () => { + if (style && document.head.contains(style)) { + document.head.removeChild(style) + styles.delete(uid) + } + } + }, [uid, rules]) +} diff --git a/packages/tldraw/src/hooks/useTLDrawContext.tsx b/packages/tldraw/src/hooks/useTLDrawContext.tsx new file mode 100644 index 000000000..b5c59a07b --- /dev/null +++ b/packages/tldraw/src/hooks/useTLDrawContext.tsx @@ -0,0 +1,17 @@ +import * as React from 'react' +import type { Data } from '~types' +import type { UseStore } from 'zustand' +import type { TLDrawState } from '~state' + +export interface TLDrawContextType { + tlstate: TLDrawState + useSelector: UseStore +} + +export const TLDrawContext = React.createContext({} as TLDrawContextType) + +export function useTLDrawContext() { + const context = React.useContext(TLDrawContext) + + return context +} diff --git a/packages/tldraw/src/hooks/useTheme.ts b/packages/tldraw/src/hooks/useTheme.ts new file mode 100644 index 000000000..667a99fac --- /dev/null +++ b/packages/tldraw/src/hooks/useTheme.ts @@ -0,0 +1,25 @@ +import React from 'react' +import type { Data, Theme } from '~types' +import { useTLDrawContext } from './useTLDrawContext' +import { dark } from '~styles' + +const themeSelector = (data: Data): Theme => (data.settings.isDarkMode ? 'dark' : 'light') + +export function useTheme() { + const { tlstate, useSelector } = useTLDrawContext() + + const theme = useSelector(themeSelector) + + React.useEffect(() => { + if (theme === 'dark') { + document.body.classList.add(dark) + } else { + document.body.classList.remove(dark) + } + }, [theme]) + + return { + theme, + toggle: tlstate.toggleDarkMode, + } +} diff --git a/packages/tldraw/src/index.ts b/packages/tldraw/src/index.ts new file mode 100644 index 000000000..5fd99bf02 --- /dev/null +++ b/packages/tldraw/src/index.ts @@ -0,0 +1,4 @@ +export * from './components/tldraw' +export * from './types' +export * from './shape' +export { TLDrawState } from './state' diff --git a/packages/tldraw/src/shape/index.ts b/packages/tldraw/src/shape/index.ts new file mode 100644 index 000000000..950227d98 --- /dev/null +++ b/packages/tldraw/src/shape/index.ts @@ -0,0 +1,2 @@ +export * from './shape-utils' +export * from './shape-styles' diff --git a/state/shape-styles.ts b/packages/tldraw/src/shape/shape-styles.ts similarity index 54% rename from state/shape-styles.ts rename to packages/tldraw/src/shape/shape-styles.ts index 565cf78e5..5751e9d6f 100644 --- a/state/shape-styles.ts +++ b/packages/tldraw/src/shape/shape-styles.ts @@ -1,5 +1,5 @@ -import { Theme, ColorStyle, DashStyle, ShapeStyles, SizeStyle } from 'types' -import { lerpColor } from 'utils' +import { Utils } from '@tldraw/core' +import { Theme, ColorStyle, DashStyle, ShapeStyles, SizeStyle } from '~types' const canvasLight = '#fafafa' @@ -24,7 +24,7 @@ export const strokes: Record> = { light: colors, dark: { ...(Object.fromEntries( - Object.entries(colors).map(([k, v]) => [k, lerpColor(v, canvasDark, 0.1)]) + Object.entries(colors).map(([k, v]) => [k, Utils.lerpColor(v, canvasDark, 0.1)]) ) as Record), [ColorStyle.White]: '#ffffff', [ColorStyle.Black]: '#000', @@ -34,16 +34,13 @@ export const strokes: Record> = { export const fills: Record> = { light: { ...(Object.fromEntries( - Object.entries(colors).map(([k, v]) => [ - k, - lerpColor(v, canvasLight, 0.82), - ]) + Object.entries(colors).map(([k, v]) => [k, Utils.lerpColor(v, canvasLight, 0.82)]) ) as Record), [ColorStyle.White]: '#ffffff', [ColorStyle.Black]: '#ffffff', }, dark: Object.fromEntries( - Object.entries(colors).map(([k, v]) => [k, lerpColor(v, canvasDark, 0.618)]) + Object.entries(colors).map(([k, v]) => [k, Utils.lerpColor(v, canvasDark, 0.618)]) ) as Record, } @@ -68,10 +65,11 @@ export function getFontSize(size: SizeStyle): number { return fontSizes[size] } -export function getFontStyle(scale: number, style: ShapeStyles): string { +export function getFontStyle(style: ShapeStyles): string { const fontSize = getFontSize(style.size) + const { scale = 1 } = style - return `${fontSize * scale}px/1.4 Verveine Regular` + return `${fontSize * scale}px/1.3 "Caveat Brush"` } export function getShapeStyle( @@ -101,3 +99,50 @@ export const defaultStyle: ShapeStyles = { isFilled: false, dash: DashStyle.Draw, } + +/** + * Get balanced dash-strokearray and dash-strokeoffset properties for a path of a given length. + * @param length The length of the path. + * @param strokeWidth The shape's stroke-width property. + * @param style The stroke's style: "dashed" or "dotted" (default "dashed"). + * @param snap An interval for dashes (e.g. 4 will produce arrays with 4, 8, 16, etc dashes). + */ +export function getPerfectDashProps( + length: number, + strokeWidth: number, + style: DashStyle, + snap = 1 +): { + strokeDasharray: string + strokeDashoffset: string +} { + let dashLength: number + let strokeDashoffset: string + let ratio: number + + if (style === DashStyle.Solid || style === DashStyle.Draw) { + return { + strokeDasharray: 'none', + strokeDashoffset: 'none', + } + } else if (style === DashStyle.Dashed) { + dashLength = strokeWidth * 2 + ratio = 1 + strokeDashoffset = (dashLength / 2).toString() + } else { + dashLength = strokeWidth / 100 + ratio = 100 + strokeDashoffset = '0' + } + + let dashes = Math.floor(length / dashLength / (2 * ratio)) + dashes -= dashes % snap + if (dashes === 0) dashes = 1 + + const gapLength = (length - dashes * dashLength) / dashes + + return { + strokeDasharray: [dashLength, gapLength].join(' '), + strokeDashoffset, + } +} diff --git a/packages/tldraw/src/shape/shape-utils.tsx b/packages/tldraw/src/shape/shape-utils.tsx new file mode 100644 index 000000000..d03004b63 --- /dev/null +++ b/packages/tldraw/src/shape/shape-utils.tsx @@ -0,0 +1,25 @@ +import { Rectangle, Ellipse, Arrow, Draw, Text, Group } from './shapes' +import { TLDrawShapeType, TLDrawShape, TLDrawShapeUtil, TLDrawShapeUtils } from '~types' + +export const tldrawShapeUtils: TLDrawShapeUtils = { + [TLDrawShapeType.Rectangle]: new Rectangle(), + [TLDrawShapeType.Ellipse]: new Ellipse(), + [TLDrawShapeType.Draw]: new Draw(), + [TLDrawShapeType.Arrow]: new Arrow(), + [TLDrawShapeType.Text]: new Text(), + [TLDrawShapeType.Group]: new Group(), +} + +export type ShapeByType = TLDrawShapeUtils[T] + +export function getShapeUtilsByType(shape: T): TLDrawShapeUtil { + return tldrawShapeUtils[shape.type as T['type']] as TLDrawShapeUtil +} + +export function getShapeUtils(shape: T): TLDrawShapeUtil { + return tldrawShapeUtils[shape.type as T['type']] as TLDrawShapeUtil +} + +export function createShape(type: TLDrawShapeType, props: Partial) { + return tldrawShapeUtils[type].create(props) +} diff --git a/packages/tldraw/src/shape/shapes/arrow/arrow.spec.tsx b/packages/tldraw/src/shape/shapes/arrow/arrow.spec.tsx new file mode 100644 index 000000000..4ef7108f5 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/arrow/arrow.spec.tsx @@ -0,0 +1,7 @@ +import { Arrow } from './arrow' + +describe('Arrow shape', () => { + it('Creates an instance', () => { + new Arrow() + }) +}) diff --git a/packages/tldraw/src/shape/shapes/arrow/arrow.tsx b/packages/tldraw/src/shape/shapes/arrow/arrow.tsx new file mode 100644 index 000000000..f59850296 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/arrow/arrow.tsx @@ -0,0 +1,782 @@ +import * as React from 'react' +import { + TLBounds, + Utils, + Vec, + TLTransformInfo, + Intersect, + TLHandle, + TLPointerInfo, +} from '@tldraw/core' +import getStroke from 'perfect-freehand' +import { defaultStyle, getPerfectDashProps, getShapeStyle } from '~shape/shape-styles' +import { + ArrowShape, + Decoration, + TLDrawShapeUtil, + TLDrawShapeType, + TLDrawToolType, + DashStyle, + TLDrawShape, + ArrowBinding, + TLDrawRenderInfo, +} from '~types' + +export class Arrow extends TLDrawShapeUtil { + type = TLDrawShapeType.Arrow as const + toolType = TLDrawToolType.Handle + canStyleFill = false + simplePathCache = new WeakMap() + pathCache = new WeakMap() + + defaultProps = { + id: 'id', + type: TLDrawShapeType.Arrow as const, + name: 'Arrow', + parentId: 'page', + childIndex: 1, + point: [0, 0], + rotation: 0, + bend: 0, + handles: { + start: { + id: 'start', + index: 0, + point: [0, 0], + canBind: true, + }, + end: { + id: 'end', + index: 1, + point: [1, 1], + canBind: true, + }, + bend: { + id: 'bend', + index: 2, + point: [0.5, 0.5], + }, + }, + decorations: { + end: Decoration.Arrow, + }, + style: { + ...defaultStyle, + isFilled: false, + }, + } + + shouldRender = (prev: ArrowShape, next: ArrowShape) => { + return next.handles !== prev.handles || next.style !== prev.style + } + + render = (shape: ArrowShape, { meta }: TLDrawRenderInfo) => { + const { + handles: { start, bend, end }, + decorations = {}, + style, + } = shape + + const isDraw = style.dash === DashStyle.Draw + + // TODO: Improve drawn arrows + + const isStraightLine = Vec.dist(bend.point, Vec.round(Vec.med(start.point, end.point))) < 1 + + const styles = getShapeStyle(style, meta.isDarkMode) + + const { strokeWidth } = styles + + const arrowDist = Vec.dist(start.point, end.point) + + const arrowHeadLength = Math.min(arrowDist / 3, strokeWidth * 8) + + let shaftPath: JSX.Element | null + let startArrowHead: { left: number[]; right: number[] } | undefined + let endArrowHead: { left: number[]; right: number[] } | undefined + + if (isStraightLine) { + const sw = strokeWidth * (isDraw ? 1.25 : 1.618) + + const path = Utils.getFromCache(this.pathCache, shape, () => + isDraw + ? renderFreehandArrowShaft(shape) + : 'M' + Vec.round(start.point) + 'L' + Vec.round(end.point) + ) + + const { strokeDasharray, strokeDashoffset } = getPerfectDashProps( + arrowDist, + sw, + shape.style.dash, + 2 + ) + + if (decorations.start) { + startArrowHead = getStraightArrowHeadPoints(start.point, end.point, arrowHeadLength) + } + + if (decorations.end) { + endArrowHead = getStraightArrowHeadPoints(end.point, start.point, arrowHeadLength) + } + + // Straight arrow path + shaftPath = + arrowDist > 2 ? ( + <> + + + + ) : null + } else { + const circle = getCtp(shape) + + const sw = strokeWidth * (isDraw ? 1.25 : 1.618) + + const path = Utils.getFromCache(this.pathCache, shape, () => + isDraw + ? renderCurvedFreehandArrowShaft(shape, circle) + : getArrowArcPath(start, end, circle, shape.bend) + ) + + const { center, radius, length } = getArrowArc(shape) + + const { strokeDasharray, strokeDashoffset } = getPerfectDashProps( + length - 1, + sw, + shape.style.dash, + 2 + ) + + if (decorations.start) { + startArrowHead = getCurvedArrowHeadPoints( + start.point, + arrowHeadLength, + center, + radius, + length < 0 + ) + } + + if (decorations.end) { + endArrowHead = getCurvedArrowHeadPoints( + end.point, + arrowHeadLength, + center, + radius, + length >= 0 + ) + } + + // Curved arrow path + shaftPath = ( + <> + + + + ) + } + + const sw = strokeWidth * 1.618 + + return ( + + {shaftPath} + {startArrowHead && ( + + )} + {endArrowHead && ( + + )} + + ) + } + + renderIndicator(shape: ArrowShape) { + const path = Utils.getFromCache(this.simplePathCache, shape.handles, () => getArrowPath(shape)) + + return + } + + getBounds = (shape: ArrowShape) => { + const bounds = Utils.getFromCache(this.boundsCache, shape, () => { + const { start, bend, end } = shape.handles + return Utils.getBoundsFromPoints([start.point, bend.point, end.point]) + }) + + return Utils.translateBounds(bounds, shape.point) + } + + getRotatedBounds = (shape: ArrowShape) => { + const { start, bend, end } = shape.handles + + return Utils.translateBounds( + Utils.getBoundsFromPoints([start.point, bend.point, end.point], shape.rotation), + shape.point + ) + } + + getCenter = (shape: ArrowShape) => { + const { start, end } = shape.handles + return Vec.add(shape.point, Vec.med(start.point, end.point)) + } + + hitTest = () => { + return true + } + + hitTestBounds = (shape: ArrowShape, brushBounds: TLBounds) => { + const { start, end, bend } = shape.handles + + const sp = Vec.add(shape.point, start.point) + const ep = Vec.add(shape.point, end.point) + + if (Utils.pointInBounds(sp, brushBounds) || Utils.pointInBounds(ep, brushBounds)) { + return true + } + + if (Vec.isEqual(Vec.med(start.point, end.point), bend.point)) { + return Intersect.lineSegment.bounds(sp, ep, brushBounds).length > 0 + } else { + const [cx, cy, r] = getCtp(shape) + const cp = Vec.add(shape.point, [cx, cy]) + + return Intersect.arc.bounds(cp, r, sp, ep, brushBounds).length > 0 + } + } + + transform = ( + _shape: ArrowShape, + bounds: TLBounds, + { initialShape, scaleX, scaleY }: TLTransformInfo + ): Partial => { + const initialShapeBounds = this.getBounds(initialShape) + + const handles: (keyof ArrowShape['handles'])[] = ['start', 'end'] + + const nextHandles = { ...initialShape.handles } + + handles.forEach((handle) => { + const [x, y] = nextHandles[handle].point + const nw = x / initialShapeBounds.width + const nh = y / initialShapeBounds.height + + nextHandles[handle] = { + ...nextHandles[handle], + point: [ + bounds.width * (scaleX < 0 ? 1 - nw : nw), + bounds.height * (scaleY < 0 ? 1 - nh : nh), + ], + } + }) + + const { start, bend, end } = nextHandles + + const dist = Vec.dist(start.point, end.point) + + const midPoint = Vec.med(start.point, end.point) + + const bendDist = (dist / 2) * initialShape.bend + + const u = Vec.uni(Vec.vec(start.point, end.point)) + + const point = Vec.add(midPoint, Vec.mul(Vec.per(u), bendDist)) + + nextHandles['bend'] = { + ...bend, + point: Math.abs(bendDist) < 10 ? midPoint : point, + } + + return { + point: [bounds.minX, bounds.minY], + handles: nextHandles, + } + } + + onDoubleClickHandle = (shape: ArrowShape, handle: Partial) => { + switch (handle) { + case 'bend': { + return { + bend: 0, + handles: { + ...shape.handles, + bend: { + ...shape.handles.bend, + point: getBendPoint(shape.handles, shape.bend), + }, + }, + } + } + case 'start': { + return { + decorations: { + ...shape.decorations, + start: shape.decorations?.start ? undefined : Decoration.Arrow, + }, + } + } + case 'end': { + return { + decorations: { + ...shape.decorations, + end: shape.decorations?.end ? undefined : Decoration.Arrow, + }, + } + } + } + + return this + } + + onBindingChange = ( + shape: ArrowShape, + binding: ArrowBinding, + target: TLDrawShape, + targetBounds: TLBounds, + center: number[] + ): void | Partial => { + const handle = shape.handles[binding.handleId] + const expandedBounds = Utils.expandBounds(targetBounds, 32) + + // The anchor is the "actual" point in the target shape + // (Remember that the binding.point is normalized) + const anchor = Vec.sub( + Vec.add( + [expandedBounds.minX, expandedBounds.minY], + Vec.mulV( + [expandedBounds.width, expandedBounds.height], + Vec.rotWith(binding.point, [0.5, 0.5], target.rotation || 0) + ) + ), + shape.point + ) + + // We're looking for the point to put the dragging handle + let handlePoint = anchor + + if (binding.distance) { + const intersectBounds = Utils.expandBounds(targetBounds, binding.distance) + + // The direction vector starts from the arrow's opposite handle + const origin = Vec.add( + shape.point, + shape.handles[handle.id === 'start' ? 'end' : 'start'].point + ) + + // And passes through the dragging handle + const direction = Vec.uni(Vec.sub(Vec.add(anchor, shape.point), origin)) + + if ([TLDrawShapeType.Rectangle, TLDrawShapeType.Text].includes(target.type)) { + let hits = Intersect.ray + .bounds(origin, direction, intersectBounds, target.rotation) + .filter((int) => int.didIntersect) + .map((int) => int.points[0]) + .sort((a, b) => Vec.dist(a, origin) - Vec.dist(b, origin)) + + if (hits.length < 2) { + hits = Intersect.ray + .bounds(origin, Vec.neg(direction), intersectBounds) + .filter((int) => int.didIntersect) + .map((int) => int.points[0]) + .sort((a, b) => Vec.dist(a, origin) - Vec.dist(b, origin)) + } + + if (!hits[0]) { + console.warn('No intersection.') + return + } + + handlePoint = Vec.sub(hits[0], shape.point) + } else if (target.type === TLDrawShapeType.Ellipse) { + const hits = Intersect.ray + .ellipse( + origin, + direction, + center, + target.radius[0] + binding.distance, + target.radius[1] + binding.distance, + target.rotation || 0 + ) + .points.sort((a, b) => Vec.dist(a, origin) - Vec.dist(b, origin)) + + if (!hits[0]) { + console.warn('No intersections') + } + + handlePoint = Vec.sub(hits[0], shape.point) + } + } + + return this.onHandleChange( + shape, + { + [handle.id]: { + ...handle, + point: Vec.round(handlePoint), + }, + }, + { shiftKey: false } + ) + } + + onHandleChange = ( + shape: ArrowShape, + handles: Partial, + { shiftKey }: Partial + ) => { + let nextHandles = Utils.deepMerge(shape.handles, handles) + let nextBend = shape.bend + + // If the user is holding shift, we want to snap the handles to angles + Object.values(handles).forEach((handle) => { + if ((handle.id === 'start' || handle.id === 'end') && shiftKey) { + const point = handle.point + const other = handle.id === 'start' ? shape.handles.end : shape.handles.start + const angle = Vec.angle(other.point, point) + const distance = Vec.dist(other.point, point) + const newAngle = Utils.clampToRotationToSegments(angle, 24) + handle.point = Vec.nudgeAtAngle(other.point, newAngle, distance) + } + }) + + nextHandles = { + ...nextHandles, + start: { + ...nextHandles.start, + point: Vec.round(nextHandles.start.point), + }, + end: { + ...nextHandles.end, + point: Vec.round(nextHandles.end.point), + }, + } + + // If the user is moving the bend handle, we want to move the bend point + if ('bend' in handles) { + const { start, end, bend } = nextHandles + + const distance = Vec.dist(start.point, end.point) + const midPoint = Vec.med(start.point, end.point) + const angle = Vec.angle(start.point, end.point) + const u = Vec.uni(Vec.vec(start.point, end.point)) + + // Create a line segment perendicular to the line between the start and end points + const ap = Vec.add(midPoint, Vec.mul(Vec.per(u), distance / 2)) + const bp = Vec.sub(midPoint, Vec.mul(Vec.per(u), distance / 2)) + + const bendPoint = Vec.nearestPointOnLineSegment(ap, bp, bend.point, true) + + // Find the distance between the midpoint and the nearest point on the + // line segment to the bend handle's dragged point + const bendDist = Vec.dist(midPoint, bendPoint) + + // The shape's "bend" is the ratio of the bend to the distance between + // the start and end points. If the bend is below a certain amount, the + // bend should be zero. + nextBend = Utils.clamp(bendDist / (distance / 2), -0.99, 0.99) + + // If the point is to the left of the line segment, we make the bend + // negative, otherwise it's positive. + const angleToBend = Vec.angle(start.point, bendPoint) + + // If resulting bend is low enough that the handle will snap to center, + // then also snap the bend to center + if (Vec.isEqual(midPoint, getBendPoint(nextHandles, nextBend))) { + nextBend = 0 + } else if (Utils.isAngleBetween(angle, angle + Math.PI, angleToBend)) { + // Otherwise, fix the bend direction + nextBend *= -1 + } + } + + const nextShape = { + point: shape.point, + bend: nextBend, + handles: { + ...nextHandles, + bend: { + ...nextHandles.bend, + point: getBendPoint(nextHandles, nextBend), + }, + }, + } + + // Zero out the handles to prevent handles with negative points. If a handle's x or y + // is below zero, we need to move the shape left or up to make it zero. + + const bounds = Utils.getBoundsFromPoints( + Object.values(nextShape.handles).map((handle) => handle.point) + ) + + const offset = [bounds.minX, bounds.minY] + + if (!Vec.isEqual(offset, [0, 0])) { + Object.values(nextShape.handles).forEach((handle) => { + handle.point = Vec.round(Vec.sub(handle.point, offset)) + }) + + nextShape.point = Vec.round(Vec.add(nextShape.point, offset)) + } + + return nextShape + } +} + +function getArrowArcPath(start: TLHandle, end: TLHandle, circle: number[], bend: number) { + return [ + 'M', + start.point[0], + start.point[1], + 'A', + circle[2], + circle[2], + 0, + 0, + bend < 0 ? 0 : 1, + end.point[0], + end.point[1], + ].join(' ') +} + +function getBendPoint(handles: ArrowShape['handles'], bend: number) { + const { start, end } = handles + + const dist = Vec.dist(start.point, end.point) + const midPoint = Vec.med(start.point, end.point) + const bendDist = (dist / 2) * bend + const u = Vec.uni(Vec.vec(start.point, end.point)) + + const point = Vec.round( + Math.abs(bendDist) < 10 ? midPoint : Vec.add(midPoint, Vec.mul(Vec.per(u), bendDist)) + ) + + return point +} + +function renderFreehandArrowShaft(shape: ArrowShape) { + const { style, id } = shape + const { start, end } = shape.handles + + const getRandom = Utils.rng(id) + + const strokeWidth = +getShapeStyle(style).strokeWidth * 2 + + const stroke = getStroke( + [...Vec.pointsBetween(start.point, end.point), end.point, end.point, end.point], + { + size: strokeWidth / 2, + thinning: 0.5 + getRandom() * 0.3, + easing: (t) => t * t, + end: shape.decorations?.end ? { cap: true } : { taper: strokeWidth * 20 }, + start: shape.decorations?.start ? { cap: true } : { taper: strokeWidth * 20 }, + simulatePressure: true, + last: true, + } + ) + + const path = Utils.getSvgPathFromStroke(stroke) + + return path +} + +function renderCurvedFreehandArrowShaft(shape: ArrowShape, circle: number[]) { + const { style, id } = shape + const { start, end } = shape.handles + + const getRandom = Utils.rng(id) + + const strokeWidth = +getShapeStyle(style).strokeWidth * 2 + + const center = [circle[0], circle[1]] + const radius = circle[2] + + const startAngle = Vec.angle(center, start.point) + + const endAngle = Vec.angle(center, end.point) + + const points: number[][] = [] + + for (let i = 0; i < 21; i++) { + const t = i / 20 + const angle = Utils.lerpAngles(startAngle, endAngle, t) + points.push(Vec.round(Vec.nudgeAtAngle(center, angle, radius))) + } + + const stroke = getStroke([...points, end.point, end.point, end.point], { + size: strokeWidth / 2, + thinning: 0.5 + getRandom() * 0.3, + easing: (t) => t * t, + end: shape.decorations?.end ? { cap: true } : { taper: strokeWidth * 20 }, + start: shape.decorations?.start ? { cap: true } : { taper: strokeWidth * 20 }, + simulatePressure: true, + streamline: 0.01, + last: true, + }) + + const path = Utils.getSvgPathFromStroke(stroke) + + return path +} + +function getCtp(shape: ArrowShape) { + const { start, end, bend } = shape.handles + return Utils.circleFromThreePoints(start.point, end.point, bend.point) +} + +function getArrowArc(shape: ArrowShape) { + const { start, end, bend } = shape.handles + const [cx, cy, radius] = Utils.circleFromThreePoints(start.point, end.point, bend.point) + const center = [cx, cy] + const length = Utils.getArcLength(center, radius, start.point, end.point) + return { center, radius, length } +} + +function getCurvedArrowHeadPoints( + A: number[], + r1: number, + C: number[], + r2: number, + sweep: boolean +) { + const ints = Intersect.circle.circle(A, r1 * 0.618, C, r2).points + if (!ints) { + console.warn('Could not find an intersection for the arrow head.') + return { left: A, right: A } + } + + const int = sweep ? ints[0] : ints[1] + const left = int ? Vec.nudge(Vec.rotWith(int, A, Math.PI / 6), A, r1 * -0.382) : A + const right = int ? Vec.nudge(Vec.rotWith(int, A, -Math.PI / 6), A, r1 * -0.382) : A + return { left, right } +} + +function getStraightArrowHeadPoints(A: number[], B: number[], r: number) { + const ints = Intersect.circle.lineSegment(A, r, A, B).points + if (!ints) { + console.warn('Could not find an intersection for the arrow head.') + return { left: A, right: A } + } + + const int = ints[0] + const left = int ? Vec.rotWith(int, A, Math.PI / 6) : A + const right = int ? Vec.rotWith(int, A, -Math.PI / 6) : A + return { left, right } +} + +function getCurvedArrowHeadPath(A: number[], r1: number, C: number[], r2: number, sweep: boolean) { + const { left, right } = getCurvedArrowHeadPoints(A, r1, C, r2, sweep) + return `M ${left} L ${A} ${right}` +} + +function getStraightArrowHeadPath(A: number[], B: number[], r: number) { + const { left, right } = getStraightArrowHeadPoints(A, B, r) + return `M ${left} L ${A} ${right}` +} + +function getArrowPath(shape: ArrowShape) { + const { + decorations, + handles: { start, end, bend: _bend }, + style, + } = shape + + const { strokeWidth } = getShapeStyle(style, false) + + const arrowDist = Vec.dist(start.point, end.point) + + const arrowHeadLength = Math.min(arrowDist / 3, strokeWidth * 8) + + const path: (string | number)[] = [] + + const isStraightLine = Vec.dist(_bend.point, Vec.round(Vec.med(start.point, end.point))) < 1 + + if (isStraightLine) { + // Path (line segment) + path.push(`M ${start.point} L ${end.point}`) + + // Start arrow head + if (decorations?.start) { + path.push(getStraightArrowHeadPath(start.point, end.point, arrowHeadLength)) + } + + // End arrow head + if (decorations?.end) { + path.push(getStraightArrowHeadPath(end.point, start.point, arrowHeadLength)) + } + } else { + const { center, radius, length } = getArrowArc(shape) + + // Path (arc) + path.push(`M ${start.point} A ${radius} ${radius} 0 0 ${length > 0 ? '1' : '0'} ${end.point}`) + + // Start Arrow head + if (decorations?.start) { + path.push(getCurvedArrowHeadPath(start.point, arrowHeadLength, center, radius, length < 0)) + } + + // End arrow head + if (decorations?.end) { + path.push(getCurvedArrowHeadPath(end.point, arrowHeadLength, center, radius, length >= 0)) + } + } + + return path.join(' ') +} diff --git a/packages/tldraw/src/shape/shapes/arrow/index.ts b/packages/tldraw/src/shape/shapes/arrow/index.ts new file mode 100644 index 000000000..3972a3181 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/arrow/index.ts @@ -0,0 +1 @@ +export * from './arrow' diff --git a/packages/tldraw/src/shape/shapes/draw/draw.spec.tsx b/packages/tldraw/src/shape/shapes/draw/draw.spec.tsx new file mode 100644 index 000000000..fb2c8bb0d --- /dev/null +++ b/packages/tldraw/src/shape/shapes/draw/draw.spec.tsx @@ -0,0 +1,7 @@ +import { Draw } from './draw' + +describe('Draw shape', () => { + it('Creates an instance', () => { + new Draw() + }) +}) diff --git a/packages/tldraw/src/shape/shapes/draw/draw.tsx b/packages/tldraw/src/shape/shapes/draw/draw.tsx new file mode 100644 index 000000000..553ceb3ca --- /dev/null +++ b/packages/tldraw/src/shape/shapes/draw/draw.tsx @@ -0,0 +1,361 @@ +import * as React from 'react' +import { TLBounds, Utils, Vec, TLTransformInfo, Intersect } from '@tldraw/core' +import getStroke, { getStrokePoints } from 'perfect-freehand' +import { defaultStyle, getShapeStyle } from '~shape/shape-styles' +import { + DrawShape, + DashStyle, + TLDrawShapeUtil, + TLDrawShapeType, + TLDrawToolType, + TLDrawRenderInfo, +} from '~types' + +export class Draw extends TLDrawShapeUtil { + type = TLDrawShapeType.Draw as const + toolType = TLDrawToolType.Draw + + pointsBoundsCache = new WeakMap([]) + rotatedCache = new WeakMap([]) + drawPathCache = new WeakMap([]) + simplePathCache = new WeakMap([]) + polygonCache = new WeakMap([]) + + defaultProps: DrawShape = { + id: 'id', + type: TLDrawShapeType.Draw as const, + name: 'Draw', + parentId: 'page', + childIndex: 1, + point: [0, 0], + points: [], + rotation: 0, + style: defaultStyle, + } + + shouldRender(prev: DrawShape, next: DrawShape): boolean { + return next.points !== prev.points || next.style !== prev.style + } + + render(shape: DrawShape, { meta, isEditing }: TLDrawRenderInfo): JSX.Element { + const { points, style } = shape + + const styles = getShapeStyle(style, meta.isDarkMode) + + const strokeWidth = styles.strokeWidth + + // For very short lines, draw a point instead of a line + const bounds = this.getBounds(shape) + + const verySmall = bounds.width < strokeWidth / 2 && bounds.height < strokeWidth / 2 + + if (!isEditing && verySmall) { + const sw = strokeWidth * 0.618 + + return ( + + ) + } + + const shouldFill = + style.isFilled && + points.length > 3 && + Vec.dist(points[0], points[points.length - 1]) < +styles.strokeWidth * 2 + + // For drawn lines, draw a line from the path cache + + if (shape.style.dash === DashStyle.Draw) { + const polygonPathData = Utils.getFromCache(this.polygonCache, points, () => + getFillPath(shape) + ) + + const drawPathData = isEditing + ? getDrawStrokePath(shape, true) + : Utils.getFromCache(this.drawPathCache, points, () => getDrawStrokePath(shape, false)) + + return ( + <> + {shouldFill && ( + + )} + + + ) + } + + // For solid, dash and dotted lines, draw a regular stroke path + + const strokeDasharray = { + [DashStyle.Draw]: 'none', + [DashStyle.Solid]: `none`, + [DashStyle.Dotted]: `${strokeWidth / 10} ${strokeWidth * 3}`, + [DashStyle.Dashed]: `${strokeWidth * 3} ${strokeWidth * 3}`, + }[style.dash] + + const strokeDashoffset = { + [DashStyle.Draw]: 'none', + [DashStyle.Solid]: `none`, + [DashStyle.Dotted]: `-${strokeWidth / 20}`, + [DashStyle.Dashed]: `-${strokeWidth}`, + }[style.dash] + + const path = Utils.getFromCache(this.simplePathCache, points, () => getSolidStrokePath(shape)) + + const sw = strokeWidth * 1.618 + + return ( + <> + + + + ) + } + + renderIndicator(shape: DrawShape): JSX.Element { + const { points } = shape + + const bounds = this.getBounds(shape) + + const verySmall = bounds.width < 4 && bounds.height < 4 + + if (verySmall) { + return + } + + const path = Utils.getFromCache(this.simplePathCache, points, () => getSolidStrokePath(shape)) + + return + } + + getBounds(shape: DrawShape): TLBounds { + return Utils.translateBounds( + Utils.getFromCache(this.pointsBoundsCache, shape.points, () => + Utils.getBoundsFromPoints(shape.points) + ), + shape.point + ) + } + + getRotatedBounds(shape: DrawShape): TLBounds { + return Utils.translateBounds( + Utils.getBoundsFromPoints(shape.points, shape.rotation), + shape.point + ) + } + + getCenter(shape: DrawShape): number[] { + return Utils.getBoundsCenter(this.getBounds(shape)) + } + + hitTest(): boolean { + return true + } + + hitTestBounds(shape: DrawShape, brushBounds: TLBounds): boolean { + // Test axis-aligned shape + if (!shape.rotation) { + const bounds = this.getBounds(shape) + + return ( + Utils.boundsContain(brushBounds, bounds) || + ((Utils.boundsContain(bounds, brushBounds) || + Intersect.bounds.bounds(bounds, brushBounds).length > 0) && + Intersect.polyline.bounds( + shape.points, + Utils.translateBounds(brushBounds, Vec.neg(shape.point)) + ).length > 0) + ) + } + + // Test rotated shape + const rBounds = this.getRotatedBounds(shape) + + const rotatedBounds = Utils.getFromCache(this.rotatedCache, shape, () => { + const c = Utils.getBoundsCenter(Utils.getBoundsFromPoints(shape.points)) + return shape.points.map((pt) => Vec.rotWith(pt, c, shape.rotation || 0)) + }) + + return ( + Utils.boundsContain(brushBounds, rBounds) || + Intersect.bounds.polyline( + Utils.translateBounds(brushBounds, Vec.neg(shape.point)), + rotatedBounds + ).length > 0 + ) + } + + transform( + shape: DrawShape, + bounds: TLBounds, + { initialShape, scaleX, scaleY }: TLTransformInfo + ): Partial { + const initialShapeBounds = Utils.getFromCache(this.boundsCache, initialShape, () => + Utils.getBoundsFromPoints(initialShape.points) + ) + + const points = initialShape.points.map(([x, y, r]) => { + return [ + bounds.width * + (scaleX < 0 // * sin? + ? 1 - x / initialShapeBounds.width + : x / initialShapeBounds.width), + bounds.height * + (scaleY < 0 // * cos? + ? 1 - y / initialShapeBounds.height + : y / initialShapeBounds.height), + r, + ] + }) + + const newBounds = Utils.getBoundsFromPoints(shape.points) + + const point = Vec.sub([bounds.minX, bounds.minY], [newBounds.minX, newBounds.minY]) + + return { + points, + point, + } + } + + transformSingle( + shape: DrawShape, + bounds: TLBounds, + info: TLTransformInfo + ): Partial { + return this.transform(shape, bounds, info) + } + + onSessionComplete(shape: DrawShape): Partial { + const bounds = this.getBounds(shape) + + const [x1, y1] = Vec.round(Vec.sub([bounds.minX, bounds.minY], shape.point)) + + const points = shape.points.map(([x0, y0, p]) => Vec.round([x0 - x1, y0 - y1]).concat(p)) + + return { + points, + point: Vec.add(shape.point, [x1, y1]), + } + } +} + +const simulatePressureSettings = { + simulatePressure: true, +} + +const realPressureSettings = { + easing: (t: number) => t * t, + simulatePressure: false, + start: { taper: 1 }, + end: { taper: 1 }, +} + +function getFillPath(shape: DrawShape) { + const styles = getShapeStyle(shape.style) + + if (shape.points.length < 2) { + return '' + } + + return Utils.getSvgPathFromStroke( + getStrokePoints(shape.points, { + size: 1 + styles.strokeWidth * 2, + thinning: 0.85, + end: { taper: +styles.strokeWidth * 10 }, + start: { taper: +styles.strokeWidth * 10 }, + }).map((pt) => pt.point) + ) +} + +function getDrawStrokePath(shape: DrawShape, isEditing: boolean) { + const styles = getShapeStyle(shape.style) + + if (shape.points.length < 2) { + return '' + } + + const options = shape.points[1][2] === 0.5 ? simulatePressureSettings : realPressureSettings + + const stroke = getStroke(shape.points.slice(2), { + size: 1 + styles.strokeWidth * 2, + thinning: 0.85, + end: { taper: +styles.strokeWidth * 50 }, + start: { taper: +styles.strokeWidth * 50 }, + ...options, + last: !isEditing, + }) + + const path = Utils.getSvgPathFromStroke(stroke) + + return path +} + +function getSolidStrokePath(shape: DrawShape) { + let { points } = shape + + let len = points.length + + if (len === 0) return 'M 0 0 L 0 0' + if (len < 3) return `M ${points[0][0]} ${points[0][1]}` + + points = getStrokePoints(points).map((pt) => pt.point) + + len = points.length + + const d = points.reduce( + (acc, [x0, y0], i, arr) => { + if (i === len - 1) { + acc.push('L', x0, y0) + return acc + } + + const [x1, y1] = arr[i + 1] + acc.push(x0.toFixed(2), y0.toFixed(2), ((x0 + x1) / 2).toFixed(2), ((y0 + y1) / 2).toFixed(2)) + return acc + }, + ['M', points[0][0], points[0][1], 'Q'] + ) + + const path = d.join(' ').replaceAll(/(\s[0-9]*\.[0-9]{2})([0-9]*)\b/g, '$1') + + return path +} diff --git a/packages/tldraw/src/shape/shapes/draw/index.ts b/packages/tldraw/src/shape/shapes/draw/index.ts new file mode 100644 index 000000000..edf595698 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/draw/index.ts @@ -0,0 +1 @@ +export * from './draw' diff --git a/packages/tldraw/src/shape/shapes/ellipse/ellipse.spec.tsx b/packages/tldraw/src/shape/shapes/ellipse/ellipse.spec.tsx new file mode 100644 index 000000000..f74d27537 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/ellipse/ellipse.spec.tsx @@ -0,0 +1,7 @@ +import { Ellipse } from './ellipse' + +describe('Ellipse shape', () => { + it('Creates an instance', () => { + new Ellipse() + }) +}) diff --git a/packages/tldraw/src/shape/shapes/ellipse/ellipse.tsx b/packages/tldraw/src/shape/shapes/ellipse/ellipse.tsx new file mode 100644 index 000000000..9328d2dac --- /dev/null +++ b/packages/tldraw/src/shape/shapes/ellipse/ellipse.tsx @@ -0,0 +1,355 @@ +import * as React from 'react' +import { Utils, TLTransformInfo, TLBounds, Intersect, Vec } from '@tldraw/core' +import { + ArrowShape, + DashStyle, + EllipseShape, + TLDrawRenderInfo, + TLDrawShapeType, + TLDrawShapeUtil, + TLDrawToolType, +} from '~types' +import { defaultStyle, getPerfectDashProps, getShapeStyle } from '~shape/shape-styles' +import getStroke from 'perfect-freehand' + +// TODO +// [ ] Improve indicator shape for drawn shapes + +export class Ellipse extends TLDrawShapeUtil { + type = TLDrawShapeType.Ellipse as const + toolType = TLDrawToolType.Bounds + pathCache = new WeakMap([]) + canBind = true + + defaultProps = { + id: 'id', + type: TLDrawShapeType.Ellipse as const, + name: 'Ellipse', + parentId: 'page', + childIndex: 1, + point: [0, 0], + radius: [1, 1], + rotation: 0, + style: defaultStyle, + } + + shouldRender(prev: EllipseShape, next: EllipseShape) { + return next.radius !== prev.radius || next.style !== prev.style + } + + render(shape: EllipseShape, { meta, isBinding }: TLDrawRenderInfo) { + const { + radius: [radiusX, radiusY], + style, + } = shape + + const styles = getShapeStyle(style, meta.isDarkMode) + const strokeWidth = +styles.strokeWidth + + const rx = Math.max(0, radiusX - strokeWidth / 2) + const ry = Math.max(0, radiusY - strokeWidth / 2) + + if (style.dash === DashStyle.Draw) { + const path = Utils.getFromCache(this.pathCache, shape, () => + renderPath(shape, this.getCenter(shape)) + ) + + return ( + <> + {isBinding && ( + + )} + + + + ) + } + + const h = Math.pow(rx - ry, 2) / Math.pow(rx + ry, 2) + + const perimeter = Math.PI * (rx + ry) * (1 + (3 * h) / (10 + Math.sqrt(4 - 3 * h))) + + const { strokeDasharray, strokeDashoffset } = getPerfectDashProps( + perimeter, + strokeWidth * 1.618, + shape.style.dash, + 4 + ) + + const sw = strokeWidth * 1.618 + + return ( + <> + {isBinding && ( + + )} + + + ) + } + + renderIndicator(shape: EllipseShape) { + const { + style, + radius: [rx, ry], + } = shape + + const styles = getShapeStyle(style, false) + const strokeWidth = +styles.strokeWidth + + const sw = strokeWidth + + return + } + + getBounds(shape: EllipseShape) { + return Utils.getFromCache(this.boundsCache, shape, () => { + return Utils.getRotatedEllipseBounds( + shape.point[0], + shape.point[1], + shape.radius[0], + shape.radius[1], + shape.rotation || 0 + ) + }) + } + + getRotatedBounds(shape: EllipseShape) { + return Utils.getBoundsFromPoints(Utils.getRotatedCorners(this.getBounds(shape), shape.rotation)) + } + + getCenter(shape: EllipseShape): number[] { + return [shape.point[0] + shape.radius[0], shape.point[1] + shape.radius[1]] + } + + hitTest(shape: EllipseShape, point: number[]) { + return Utils.pointInBounds(point, this.getBounds(shape)) + } + + hitTestBounds(shape: EllipseShape, bounds: TLBounds) { + const rotatedCorners = Utils.getRotatedCorners(this.getBounds(shape), shape.rotation) + + return ( + rotatedCorners.every((point) => Utils.pointInBounds(point, bounds)) || + Intersect.polyline.bounds(rotatedCorners, bounds).length > 0 + ) + } + + getBindingPoint( + shape: EllipseShape, + fromShape: ArrowShape, + point: number[], + origin: number[], + direction: number[], + padding: number, + anywhere: boolean + ) { + { + const bounds = this.getBounds(shape) + + const expandedBounds = Utils.expandBounds(bounds, padding) + + const center = this.getCenter(shape) + + let bindingPoint: number[] + let distance: number + + if (!Utils.pointInEllipse(point, center, shape.radius[0] + 32, shape.radius[1] + 32)) return + + if (anywhere) { + if (Vec.dist(point, this.getCenter(shape)) < 12) { + bindingPoint = [0.5, 0.5] + } else { + bindingPoint = Vec.divV(Vec.sub(point, [expandedBounds.minX, expandedBounds.minY]), [ + expandedBounds.width, + expandedBounds.height, + ]) + } + + distance = 0 + } else { + // Find furthest intersection between ray from + // origin through point and expanded bounds. + // const intersection = Intersect.ray + // .bounds(origin, direction, expandedBounds) + // .filter((int) => int.didIntersect) + // .map((int) => int.points[0]) + // .sort((a, b) => Vec.dist(b, origin) - Vec.dist(a, origin))[0] + + let intersection = Intersect.ray + .ellipse(origin, direction, center, shape.radius[0], shape.radius[1], shape.rotation || 0) + + .points.sort((a, b) => Vec.dist(a, origin) - Vec.dist(b, origin))[0] + + if (!intersection) { + intersection = Intersect.lineSegment + .ellipse(point, center, center, shape.radius[0], shape.radius[1], shape.rotation || 0) + .points.sort((a, b) => Vec.dist(a, point) - Vec.dist(b, point))[0] + } + + // The anchor is a point between the handle and the intersection + const anchor = Vec.med(point, intersection) + + if (Vec.distanceToLineSegment(point, anchor, this.getCenter(shape)) < 12) { + // If we're close to the center, snap to the center + bindingPoint = [0.5, 0.5] + } else { + // Or else calculate a normalized point + bindingPoint = Vec.divV(Vec.sub(anchor, [expandedBounds.minX, expandedBounds.minY]), [ + expandedBounds.width, + expandedBounds.height, + ]) + } + + if ( + Utils.pointInEllipse(point, center, shape.radius[0], shape.radius[1], shape.rotation || 0) + ) { + // Pad the arrow out by 16 points + distance = 16 + } else { + // Find the distance between the point and the ellipse + const innerIntersection = Intersect.lineSegment.ellipse( + point, + center, + center, + shape.radius[0], + shape.radius[1], + shape.rotation || 0 + ).points[0] + + if (!innerIntersection) { + return undefined + } + + distance = Math.max(16, Vec.dist(point, innerIntersection)) + } + } + + return { + point: bindingPoint, + distance, + } + } + } + + transform( + _shape: EllipseShape, + bounds: TLBounds, + { scaleX, scaleY, initialShape }: TLTransformInfo + ) { + const { rotation = 0 } = initialShape + + return { + point: [bounds.minX, bounds.minY], + radius: [bounds.width / 2, bounds.height / 2], + rotation: + (scaleX < 0 && scaleY >= 0) || (scaleY < 0 && scaleX >= 0) + ? -(rotation || 0) + : rotation || 0, + } + } + + transformSingle(shape: EllipseShape, bounds: TLBounds) { + return { + point: Vec.round([bounds.minX, bounds.minY]), + radius: Vec.div([bounds.width, bounds.height], 2), + } + } +} + +function renderPath(shape: EllipseShape, boundsCenter: number[]) { + const { + style, + id, + radius: [radiusX, radiusY], + point, + } = shape + + const getRandom = Utils.rng(id) + + const center = Vec.sub(boundsCenter, point) + + const strokeWidth = +getShapeStyle(style).strokeWidth + + const rx = radiusX + getRandom() * strokeWidth - strokeWidth / 2 + const ry = radiusY + getRandom() * strokeWidth - strokeWidth / 2 + + const points: number[][] = [] + const start = Math.PI + Math.PI * getRandom() + + const overlap = Math.PI / 12 + + for (let i = 2; i < 8; i++) { + const rads = start + overlap * 2 * (i / 8) + const x = rx * Math.cos(rads) + center[0] + const y = ry * Math.sin(rads) + center[1] + points.push([x, y]) + } + + for (let i = 5; i < 32; i++) { + const t = i / 35 + const rads = start + overlap * 2 + Math.PI * 2.5 * (t * t * t) + const x = rx * Math.cos(rads) + center[0] + const y = ry * Math.sin(rads) + center[1] + points.push([x, y]) + } + + for (let i = 0; i < 8; i++) { + const rads = start + overlap * 2 * (i / 4) + const x = rx * Math.cos(rads) + center[0] + const y = ry * Math.sin(rads) + center[1] + points.push([x, y]) + } + + const stroke = getStroke(points, { + size: 1 + strokeWidth, + thinning: 0.6, + easing: (t) => t * t * t * t, + end: { taper: strokeWidth * 20 }, + start: { taper: strokeWidth * 20 }, + simulatePressure: false, + }) + + return Utils.getSvgPathFromStroke(stroke) +} diff --git a/packages/tldraw/src/shape/shapes/ellipse/index.ts b/packages/tldraw/src/shape/shapes/ellipse/index.ts new file mode 100644 index 000000000..4978dc84d --- /dev/null +++ b/packages/tldraw/src/shape/shapes/ellipse/index.ts @@ -0,0 +1 @@ +export * from './ellipse' diff --git a/packages/tldraw/src/shape/shapes/group/group.spec.tsx b/packages/tldraw/src/shape/shapes/group/group.spec.tsx new file mode 100644 index 000000000..c7f4e75ec --- /dev/null +++ b/packages/tldraw/src/shape/shapes/group/group.spec.tsx @@ -0,0 +1,7 @@ +import { Group } from './group' + +describe('Group shape', () => { + it('Creates an instance', () => { + new Group() + }) +}) diff --git a/packages/tldraw/src/shape/shapes/group/group.tsx b/packages/tldraw/src/shape/shapes/group/group.tsx new file mode 100644 index 000000000..562808fbe --- /dev/null +++ b/packages/tldraw/src/shape/shapes/group/group.tsx @@ -0,0 +1,234 @@ +import * as React from 'react' +import { TLBounds, Utils, Vec, TLTransformInfo, Intersect } from '@tldraw/core' +import { defaultStyle, getPerfectDashProps } from '~shape/shape-styles' +import { + GroupShape, + TLDrawShapeUtil, + TLDrawShapeType, + TLDrawToolType, + TLDrawRenderInfo, + ColorStyle, + DashStyle, + ArrowShape, +} from '~types' + +// TODO +// [ ] - Find bounds based on common bounds of descendants + +export class Group extends TLDrawShapeUtil { + type = TLDrawShapeType.Group as const + toolType = TLDrawToolType.Bounds + canBind = true + + pathCache = new WeakMap([]) + + defaultProps: GroupShape = { + id: 'id', + type: TLDrawShapeType.Group as const, + name: 'Group', + parentId: 'page', + childIndex: 1, + point: [0, 0], + size: [100, 100], + rotation: 0, + children: [], + style: defaultStyle, + } + + shouldRender(prev: GroupShape, next: GroupShape) { + return next.size !== prev.size || next.style !== prev.style + } + + render(shape: GroupShape, { isBinding, isHovered, isSelected }: TLDrawRenderInfo) { + const { id, size } = shape + + const sw = 2 + const w = Math.max(0, size[0] - sw / 2) + const h = Math.max(0, size[1] - sw / 2) + + const strokes: [number[], number[], number][] = [ + [[sw / 2, sw / 2], [w, sw / 2], w - sw / 2], + [[w, sw / 2], [w, h], h - sw / 2], + [[w, h], [sw / 2, h], w - sw / 2], + [[sw / 2, h], [sw / 2, sw / 2], h - sw / 2], + ] + + const paths = strokes.map(([start, end, length], i) => { + const { strokeDasharray, strokeDashoffset } = getPerfectDashProps( + length, + sw, + DashStyle.Dotted + ) + + return ( + + ) + }) + + return ( + <> + {isBinding && ( + + )} + + {paths} + + ) + } + + renderIndicator(shape: GroupShape) { + const [width, height] = shape.size + + const sw = 2 + + return ( + + ) + } + + getBounds(shape: GroupShape) { + const bounds = Utils.getFromCache(this.boundsCache, shape, () => { + const [width, height] = shape.size + return { + minX: 0, + maxX: width, + minY: 0, + maxY: height, + width, + height, + } + }) + + return Utils.translateBounds(bounds, shape.point) + } + + getRotatedBounds(shape: GroupShape) { + return Utils.getBoundsFromPoints(Utils.getRotatedCorners(this.getBounds(shape), shape.rotation)) + } + + getCenter(shape: GroupShape): number[] { + return Utils.getBoundsCenter(this.getBounds(shape)) + } + + getBindingPoint( + shape: GroupShape, + fromShape: ArrowShape, + point: number[], + origin: number[], + direction: number[], + padding: number, + anywhere: boolean + ) { + const bounds = this.getBounds(shape) + + const expandedBounds = Utils.expandBounds(bounds, padding) + + let bindingPoint: number[] + let distance: number + + // The point must be inside of the expanded bounding box + if (!Utils.pointInBounds(point, expandedBounds)) return + + // The point is inside of the shape, so we'll assume the user is + // indicating a specific point inside of the shape. + if (anywhere) { + if (Vec.dist(point, this.getCenter(shape)) < 12) { + bindingPoint = [0.5, 0.5] + } else { + bindingPoint = Vec.divV(Vec.sub(point, [expandedBounds.minX, expandedBounds.minY]), [ + expandedBounds.width, + expandedBounds.height, + ]) + } + + distance = 0 + } else { + // Find furthest intersection between ray from + // origin through point and expanded bounds. + + // TODO: Make this a ray vs rounded rect intersection + const intersection = Intersect.ray + .bounds(origin, direction, expandedBounds) + .filter((int) => int.didIntersect) + .map((int) => int.points[0]) + .sort((a, b) => Vec.dist(b, origin) - Vec.dist(a, origin))[0] + + // The anchor is a point between the handle and the intersection + const anchor = Vec.med(point, intersection) + + // If we're close to the center, snap to the center + if (Vec.distanceToLineSegment(point, anchor, this.getCenter(shape)) < 12) { + bindingPoint = [0.5, 0.5] + } else { + // Or else calculate a normalized point + bindingPoint = Vec.divV(Vec.sub(anchor, [expandedBounds.minX, expandedBounds.minY]), [ + expandedBounds.width, + expandedBounds.height, + ]) + } + + if (Utils.pointInBounds(point, bounds)) { + distance = 16 + } else { + // If the binding point was close to the shape's center, snap to the center + // Find the distance between the point and the real bounds of the shape + distance = Math.max( + 16, + Utils.getBoundsSides(bounds) + .map((side) => Vec.distanceToLineSegment(side[1][0], side[1][1], point)) + .sort((a, b) => a - b)[0] + ) + } + } + + return { + point: Vec.clampV(bindingPoint, 0, 1), + distance, + } + } + + hitTest(shape: GroupShape, point: number[]) { + return Utils.pointInBounds(point, this.getBounds(shape)) + } + + hitTestBounds(shape: GroupShape, bounds: TLBounds) { + const rotatedCorners = Utils.getRotatedCorners(this.getBounds(shape), shape.rotation) + + return ( + rotatedCorners.every((point) => Utils.pointInBounds(point, bounds)) || + Intersect.polyline.bounds(rotatedCorners, bounds).length > 0 + ) + } + + transform() { + return {} + } + + transformSingle() { + return {} + } +} diff --git a/packages/tldraw/src/shape/shapes/group/index.ts b/packages/tldraw/src/shape/shapes/group/index.ts new file mode 100644 index 000000000..ff648b3b5 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/group/index.ts @@ -0,0 +1 @@ +export * from './group' diff --git a/packages/tldraw/src/shape/shapes/index.ts b/packages/tldraw/src/shape/shapes/index.ts new file mode 100644 index 000000000..559540f9a --- /dev/null +++ b/packages/tldraw/src/shape/shapes/index.ts @@ -0,0 +1,6 @@ +export * from './draw' +export * from './arrow' +export * from './rectangle' +export * from './ellipse' +export * from './text' +export * from './group' diff --git a/packages/tldraw/src/shape/shapes/rectangle/index.ts b/packages/tldraw/src/shape/shapes/rectangle/index.ts new file mode 100644 index 000000000..1bab6b8ef --- /dev/null +++ b/packages/tldraw/src/shape/shapes/rectangle/index.ts @@ -0,0 +1 @@ +export * from './rectangle' diff --git a/packages/tldraw/src/shape/shapes/rectangle/rectangle.spec.tsx b/packages/tldraw/src/shape/shapes/rectangle/rectangle.spec.tsx new file mode 100644 index 000000000..9df18e8c9 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/rectangle/rectangle.spec.tsx @@ -0,0 +1,7 @@ +import { Rectangle } from './rectangle' + +describe('Rectangle shape', () => { + it('Creates an instance', () => { + new Rectangle() + }) +}) diff --git a/packages/tldraw/src/shape/shapes/rectangle/rectangle.tsx b/packages/tldraw/src/shape/shapes/rectangle/rectangle.tsx new file mode 100644 index 000000000..2d350efe0 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/rectangle/rectangle.tsx @@ -0,0 +1,372 @@ +import * as React from 'react' +import { TLBounds, Utils, Vec, TLTransformInfo, Intersect } from '@tldraw/core' +import getStroke from 'perfect-freehand' +import { getPerfectDashProps, defaultStyle, getShapeStyle } from '~shape/shape-styles' +import { + RectangleShape, + DashStyle, + TLDrawShapeUtil, + TLDrawShapeType, + TLDrawToolType, + TLDrawRenderInfo, + ArrowShape, +} from '~types' + +// TODO +// [ ] - Make sure that fill does not extend drawn shape at corners + +export class Rectangle extends TLDrawShapeUtil { + type = TLDrawShapeType.Rectangle as const + toolType = TLDrawToolType.Bounds + canBind = true + + pathCache = new WeakMap([]) + + defaultProps: RectangleShape = { + id: 'id', + type: TLDrawShapeType.Rectangle as const, + name: 'Rectangle', + parentId: 'page', + childIndex: 1, + point: [0, 0], + size: [1, 1], + rotation: 0, + style: defaultStyle, + } + + shouldRender(prev: RectangleShape, next: RectangleShape) { + return next.size !== prev.size || next.style !== prev.style + } + + render(shape: RectangleShape, { isBinding, meta }: TLDrawRenderInfo) { + const { id, size, style } = shape + const styles = getShapeStyle(style, meta.isDarkMode) + const strokeWidth = +styles.strokeWidth + + if (style.dash === DashStyle.Draw) { + const pathData = Utils.getFromCache(this.pathCache, shape.size, () => renderPath(shape)) + + return ( + <> + {isBinding && ( + + )} + + + + ) + } + + const sw = strokeWidth * 1.618 + + const w = Math.max(0, size[0] - sw / 2) + const h = Math.max(0, size[1] - sw / 2) + + const strokes: [number[], number[], number][] = [ + [[sw / 2, sw / 2], [w, sw / 2], w - sw / 2], + [[w, sw / 2], [w, h], h - sw / 2], + [[w, h], [sw / 2, h], w - sw / 2], + [[sw / 2, h], [sw / 2, sw / 2], h - sw / 2], + ] + + const paths = strokes.map(([start, end, length], i) => { + const { strokeDasharray, strokeDashoffset } = getPerfectDashProps( + length, + sw, + shape.style.dash + ) + + return ( + + ) + }) + + return ( + <> + {isBinding && ( + + )} + + {paths} + + ) + } + + renderIndicator(shape: RectangleShape) { + const { + style, + size: [width, height], + } = shape + + const styles = getShapeStyle(style, false) + const strokeWidth = +styles.strokeWidth + + const sw = strokeWidth + + return ( + + ) + } + + getBounds(shape: RectangleShape) { + const bounds = Utils.getFromCache(this.boundsCache, shape, () => { + const [width, height] = shape.size + return { + minX: 0, + maxX: width, + minY: 0, + maxY: height, + width, + height, + } + }) + + return Utils.translateBounds(bounds, shape.point) + } + + getRotatedBounds(shape: RectangleShape) { + return Utils.getBoundsFromPoints(Utils.getRotatedCorners(this.getBounds(shape), shape.rotation)) + } + + getCenter(shape: RectangleShape): number[] { + return Utils.getBoundsCenter(this.getBounds(shape)) + } + + getBindingPoint( + shape: RectangleShape, + fromShape: ArrowShape, + point: number[], + origin: number[], + direction: number[], + padding: number, + anywhere: boolean + ) { + const bounds = this.getBounds(shape) + + const expandedBounds = Utils.expandBounds(bounds, padding) + + let bindingPoint: number[] + let distance: number + + // The point must be inside of the expanded bounding box + if (!Utils.pointInBounds(point, expandedBounds)) return + + // The point is inside of the shape, so we'll assume the user is + // indicating a specific point inside of the shape. + if (anywhere) { + if (Vec.dist(point, this.getCenter(shape)) < 12) { + bindingPoint = [0.5, 0.5] + } else { + bindingPoint = Vec.divV(Vec.sub(point, [expandedBounds.minX, expandedBounds.minY]), [ + expandedBounds.width, + expandedBounds.height, + ]) + } + + distance = 0 + } else { + // TODO: What if the shape has a curve? In that case, should we + // intersect the circle-from-three-points instead? + + // Find furthest intersection between ray from + // origin through point and expanded bounds. + + // TODO: Make this a ray vs rounded rect intersection + const intersection = Intersect.ray + .bounds(origin, direction, expandedBounds) + .filter((int) => int.didIntersect) + .map((int) => int.points[0]) + .sort((a, b) => Vec.dist(b, origin) - Vec.dist(a, origin))[0] + // The anchor is a point between the handle and the intersection + const anchor = Vec.med(point, intersection) + + // If we're close to the center, snap to the center + if (Vec.distanceToLineSegment(point, anchor, this.getCenter(shape)) < 12) { + bindingPoint = [0.5, 0.5] + } else { + // Or else calculate a normalized point + bindingPoint = Vec.divV(Vec.sub(anchor, [expandedBounds.minX, expandedBounds.minY]), [ + expandedBounds.width, + expandedBounds.height, + ]) + } + + if (Utils.pointInBounds(point, bounds)) { + distance = 16 + } else { + // If the binding point was close to the shape's center, snap to the center + // Find the distance between the point and the real bounds of the shape + distance = Math.max( + 16, + Utils.getBoundsSides(bounds) + .map((side) => Vec.distanceToLineSegment(side[1][0], side[1][1], point)) + .sort((a, b) => a - b)[0] + ) + } + } + + return { + point: Vec.clampV(bindingPoint, 0, 1), + distance, + } + } + + hitTest(shape: RectangleShape, point: number[]) { + return Utils.pointInBounds(point, this.getBounds(shape)) + } + + hitTestBounds(shape: RectangleShape, bounds: TLBounds) { + const rotatedCorners = Utils.getRotatedCorners(this.getBounds(shape), shape.rotation) + + return ( + rotatedCorners.every((point) => Utils.pointInBounds(point, bounds)) || + Intersect.polyline.bounds(rotatedCorners, bounds).length > 0 + ) + } + + transform( + shape: RectangleShape, + bounds: TLBounds, + { initialShape, transformOrigin, scaleX, scaleY }: TLTransformInfo + ) { + if (!shape.rotation && !shape.isAspectRatioLocked) { + return { + point: Vec.round([bounds.minX, bounds.minY]), + size: Vec.round([bounds.width, bounds.height]), + } + } else { + const size = Vec.round( + Vec.mul(initialShape.size, Math.min(Math.abs(scaleX), Math.abs(scaleY))) + ) + + const point = Vec.round([ + bounds.minX + + (bounds.width - shape.size[0]) * + (scaleX < 0 ? 1 - transformOrigin[0] : transformOrigin[0]), + bounds.minY + + (bounds.height - shape.size[1]) * + (scaleY < 0 ? 1 - transformOrigin[1] : transformOrigin[1]), + ]) + + const rotation = + (scaleX < 0 && scaleY >= 0) || (scaleY < 0 && scaleX >= 0) + ? initialShape.rotation + ? -initialShape.rotation + : 0 + : initialShape.rotation + + return { + size, + point, + rotation, + } + } + } + + transformSingle(_shape: RectangleShape, bounds: TLBounds) { + return { + size: Vec.round([bounds.width, bounds.height]), + point: Vec.round([bounds.minX, bounds.minY]), + } + } +} + +function renderPath(shape: RectangleShape) { + const styles = getShapeStyle(shape.style) + + const getRandom = Utils.rng(shape.id) + + const strokeWidth = +styles.strokeWidth + + const baseOffset = strokeWidth / 2 + + const offsets = Array.from(Array(4)).map(() => [ + getRandom() * baseOffset, + getRandom() * baseOffset, + ]) + + const sw = strokeWidth + + const w = Math.max(0, shape.size[0] - sw / 2) + const h = Math.max(0, shape.size[1] - sw / 2) + + const tl = Vec.add([sw / 2, sw / 2], offsets[0]) + const tr = Vec.add([w, sw / 2], offsets[1]) + const br = Vec.add([w, h], offsets[2]) + const bl = Vec.add([sw / 2, h], offsets[3]) + + const lines = Utils.shuffleArr( + [ + Vec.pointsBetween(tr, br), + Vec.pointsBetween(br, bl), + Vec.pointsBetween(bl, tl), + Vec.pointsBetween(tl, tr), + ], + Math.floor(5 + getRandom() * 4) + ) + + const stroke = getStroke([...lines.flat().slice(4), ...lines[0], ...lines[0].slice(4)], { + size: 1 + styles.strokeWidth, + thinning: 0.618, + easing: (t) => t * t * t * t, + end: { cap: true }, + start: { cap: true }, + simulatePressure: false, + last: true, + }) + + return Utils.getSvgPathFromStroke(stroke) +} diff --git a/packages/tldraw/src/shape/shapes/text/index.ts b/packages/tldraw/src/shape/shapes/text/index.ts new file mode 100644 index 000000000..1693b5809 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/text/index.ts @@ -0,0 +1 @@ +export * from './text' diff --git a/utils/text-area.ts b/packages/tldraw/src/shape/shapes/text/text-utils.ts similarity index 85% rename from utils/text-area.ts rename to packages/tldraw/src/shape/shapes/text/text-utils.ts index a41c33512..bc21a0b23 100644 --- a/utils/text-area.ts +++ b/packages/tldraw/src/shape/shapes/text/text-utils.ts @@ -6,10 +6,7 @@ type ReplacerCallback = (substring: string, ...args: any[]) => string const INDENT = ' ' export default class TextAreaUtils { - static insertTextFirefox( - field: HTMLTextAreaElement | HTMLInputElement, - text: string - ): void { + static insertTextFirefox(field: HTMLTextAreaElement | HTMLInputElement, text: string): void { // Found on https://www.everythingfrontend.com/posts/insert-text-into-textarea-at-cursor-position.html 🎈 field.setRangeText( text, @@ -28,10 +25,7 @@ export default class TextAreaUtils { } /** Inserts `text` at the cursor’s position, replacing any selection, with **undo** support and by firing the `input` event. */ - static insert( - field: HTMLTextAreaElement | HTMLInputElement, - text: string - ): void { + static insert(field: HTMLTextAreaElement | HTMLInputElement, text: string): void { const document = field.ownerDocument const initialFocus = document.activeElement if (initialFocus !== field) { @@ -50,17 +44,18 @@ export default class TextAreaUtils { } /** Replaces the entire content, equivalent to `field.value = text` but with **undo** support and by firing the `input` event. */ - static set( - field: HTMLTextAreaElement | HTMLInputElement, - text: string - ): void { + static set(field: HTMLTextAreaElement | HTMLInputElement, text: string): void { field.select() TextAreaUtils.insert(field, text) } /** Get the selected text in a field or an empty string if nothing is selected. */ static getSelection(field: HTMLTextAreaElement | HTMLInputElement): string { - return field.value.slice(field.selectionStart, field.selectionEnd) + const { selectionStart, selectionEnd } = field + return field.value.slice( + selectionStart ? selectionStart : undefined, + selectionEnd ? selectionEnd : undefined + ) } /** Adds the `wrappingText` before and after field’s selection (or cursor). If `endWrappingText` is provided, it will be used instead of `wrappingText` at on the right. */ @@ -74,8 +69,8 @@ export default class TextAreaUtils { TextAreaUtils.insert(field, wrap + selection + (wrapEnd ?? wrap)) // Restore the selection around the previously-selected text - field.selectionStart = selectionStart + wrap.length - field.selectionEnd = selectionEnd + wrap.length + field.selectionStart = (selectionStart || 0) + wrap.length + field.selectionEnd = (selectionEnd || 0) + wrap.length } /** Finds and replaces strings and regex in the field’s value, like `field.value = field.value.replace()` but better */ @@ -94,8 +89,7 @@ export default class TextAreaUtils { field.selectionStart = matchStart field.selectionEnd = matchStart + matchLength - const replacement = - typeof replacer === 'string' ? replacer : replacer(...args) + const replacement = typeof replacer === 'string' ? replacer : replacer(...args) TextAreaUtils.insert(field, replacement) // Select replacement. Without this, the cursor would be after the replacement @@ -124,7 +118,7 @@ export default class TextAreaUtils { // The last line should only be indented if includes any character after `\n` const lineBreakCount = /\n/g.exec(selectedText)?.length - if (lineBreakCount > 0) { + if (lineBreakCount && lineBreakCount > 0) { // Select full first line to replace everything at once const firstLineStart = value.lastIndexOf('\n', selectionStart - 1) + 1 @@ -140,10 +134,7 @@ export default class TextAreaUtils { TextAreaUtils.insert(element, indentedText) // Restore selection position, including the indentation - element.setSelectionRange( - selectionStart + 1, - selectionEnd + replacementsCount - ) + element.setSelectionRange(selectionStart + 1, selectionEnd + replacementsCount) } else { TextAreaUtils.insert(element, INDENT) } @@ -158,10 +149,7 @@ export default class TextAreaUtils { const firstLineStart = value.lastIndexOf('\n', selectionStart - 1) + 1 const minimumSelectionEnd = TextAreaUtils.findLineEnd(value, selectionEnd) - const newSelection = element.value.slice( - firstLineStart, - minimumSelectionEnd - ) + const newSelection = element.value.slice(firstLineStart, minimumSelectionEnd) const indentedText = newSelection.replace(/(^|\n)(\t| {1,2})/g, '$1') const replacementsCount = newSelection.length - indentedText.length @@ -170,9 +158,7 @@ export default class TextAreaUtils { TextAreaUtils.insert(element, indentedText) // Restore selection position, including the indentation - const firstLineIndentation = /\t| {1,2}/.exec( - value.slice(firstLineStart, selectionStart) - ) + const firstLineIndentation = /\t| {1,2}/.exec(value.slice(firstLineStart, selectionStart)) const difference = firstLineIndentation ? firstLineIndentation[0].length : 0 diff --git a/packages/tldraw/src/shape/shapes/text/text.spec.tsx b/packages/tldraw/src/shape/shapes/text/text.spec.tsx new file mode 100644 index 000000000..9d4140dec --- /dev/null +++ b/packages/tldraw/src/shape/shapes/text/text.spec.tsx @@ -0,0 +1,7 @@ +import { Text } from './text' + +describe('Text shape', () => { + it('Creates an instance', () => { + new Text() + }) +}) diff --git a/packages/tldraw/src/shape/shapes/text/text.tsx b/packages/tldraw/src/shape/shapes/text/text.tsx new file mode 100644 index 000000000..e460d374d --- /dev/null +++ b/packages/tldraw/src/shape/shapes/text/text.tsx @@ -0,0 +1,529 @@ +import * as React from 'react' +import { TLBounds, Utils, Vec, TLTransformInfo, Intersect } from '@tldraw/core' +import { getShapeStyle, getFontSize, getFontStyle, defaultStyle } from '~shape/shape-styles' +import { + TextShape, + TLDrawShapeUtil, + TLDrawShapeType, + TLDrawRenderInfo, + TLDrawToolType, + ArrowShape, +} from '~types' +import styled from '~styles' +import TextAreaUtils from './text-utils' + +const LETTER_SPACING = -1.5 + +function normalizeText(text: string) { + return text.replace(/\r?\n|\r/g, '\n') +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let melm: any + +function getMeasurementDiv() { + // A div used for measurement + document.getElementById('__textMeasure')?.remove() + + const pre = document.createElement('pre') + pre.id = '__textMeasure' + + Object.assign(pre.style, { + whiteSpace: 'pre', + width: 'auto', + border: '1px solid red', + padding: '4px', + margin: '0px', + letterSpacing: `${LETTER_SPACING}px`, + opacity: '0', + position: 'absolute', + top: '-500px', + left: '0px', + zIndex: '9999', + pointerEvents: 'none', + userSelect: 'none', + alignmentBaseline: 'mathematical', + dominantBaseline: 'mathematical', + }) + + pre.tabIndex = -1 + + document.body.appendChild(pre) + return pre +} + +if (typeof window !== 'undefined') { + melm = getMeasurementDiv() +} + +export class Text extends TLDrawShapeUtil { + type = TLDrawShapeType.Text as const + toolType = TLDrawToolType.Text + isAspectRatioLocked = true + isEditableText = true + canBind = true + + pathCache = new WeakMap([]) + + defaultProps = { + id: 'id', + type: TLDrawShapeType.Text as const, + name: 'Text', + parentId: 'page', + childIndex: 1, + point: [0, 0], + rotation: 0, + text: ' ', + style: defaultStyle, + } + + create(props: Partial): TextShape { + const shape = { ...this.defaultProps, ...props } + const bounds = this.getBounds(shape) + shape.point = Vec.sub(shape.point, [bounds.width / 2, bounds.height / 2]) + return shape + } + + shouldRender(prev: TextShape, next: TextShape): boolean { + return ( + next.text !== prev.text || next.style.scale !== prev.style.scale || next.style !== prev.style + ) + } + + render( + shape: TextShape, + { + ref, + meta, + isEditing, + isBinding, + onTextBlur, + onTextChange, + onTextFocus, + onTextKeyDown, + onTextKeyUp, + }: TLDrawRenderInfo + ): JSX.Element { + const { id, text, style } = shape + const styles = getShapeStyle(style, meta.isDarkMode) + const font = getFontStyle(shape.style) + const bounds = this.getBounds(shape) + + function handleChange(e: React.ChangeEvent) { + onTextChange?.(id, normalizeText(e.currentTarget.value)) + } + + function handleKeyDown(e: React.KeyboardEvent) { + onTextKeyDown?.(id, e.key) + + if (e.key === 'Escape') return + + e.stopPropagation() + + if (e.key === 'Tab') { + e.preventDefault() + if (e.shiftKey) { + TextAreaUtils.unindent(e.currentTarget) + } else { + TextAreaUtils.indent(e.currentTarget) + } + + onTextChange?.(id, normalizeText(e.currentTarget.value)) + } + } + + function handleKeyUp(e: React.KeyboardEvent) { + onTextKeyUp?.(id, e.key) + } + + function handleBlur(e: React.FocusEvent) { + if (isEditing) { + e.currentTarget.focus() + e.currentTarget.select() + return + } + + setTimeout(() => { + onTextBlur?.(id) + }, 0) + } + + function handleFocus(e: React.FocusEvent) { + if (document.activeElement === e.currentTarget) { + e.currentTarget.select() + onTextFocus?.(id) + } + } + + function handlePointerDown() { + if (ref && ref.current.selectionEnd !== 0) { + ref.current.selectionEnd = 0 + } + } + + const fontSize = getFontSize(shape.style.size) * (shape.style.scale || 1) + + const lineHeight = fontSize * 1.3 + + if (!isEditing) { + return ( + <> + {isBinding && ( + + )} + {text.split('\n').map((str, i) => ( + + {str} + + ))} + + ) + } + + if (ref === undefined) { + throw Error('This component should receive a ref when editing.') + } + + return ( + e.stopPropagation()} + > + } + style={{ + font, + color: styles.stroke, + }} + name="text" + defaultValue={text} + tabIndex={-1} + autoComplete="false" + autoCapitalize="false" + autoCorrect="false" + autoSave="false" + placeholder="" + color={styles.stroke} + autoFocus={true} + onFocus={handleFocus} + onBlur={handleBlur} + onKeyDown={handleKeyDown} + onKeyUp={handleKeyUp} + onChange={handleChange} + onPointerDown={handlePointerDown} + /> + + ) + } + + renderIndicator(): JSX.Element | null { + return null + // if (isEditing) return null + + // const { width, height } = this.getBounds(shape) + + // return + } + + getBounds(shape: TextShape): TLBounds { + const bounds = Utils.getFromCache(this.boundsCache, shape, () => { + if (!melm) { + // We're in SSR + return { minX: 0, minY: 0, maxX: 0, maxY: 0, width: 0, height: 0 } + } + + melm.innerHTML = `${shape.text}‍` + melm.style.font = getFontStyle(shape.style) + + const [width, height] = [melm.offsetWidth, melm.offsetHeight] + + return { + minX: 0, + maxX: width, + minY: 0, + maxY: height, + width, + height, + } + }) + + return Utils.translateBounds(bounds, shape.point) + } + + getRotatedBounds(shape: TextShape): TLBounds { + return Utils.getBoundsFromPoints(Utils.getRotatedCorners(this.getBounds(shape), shape.rotation)) + } + + getCenter(shape: TextShape): number[] { + return Utils.getBoundsCenter(this.getBounds(shape)) + } + + hitTest(shape: TextShape, point: number[]): boolean { + return Utils.pointInBounds(point, this.getBounds(shape)) + } + + hitTestBounds(shape: TextShape, bounds: TLBounds): boolean { + const rotatedCorners = Utils.getRotatedCorners(this.getBounds(shape), shape.rotation) + + return ( + rotatedCorners.every((point) => Utils.pointInBounds(point, bounds)) || + Intersect.polyline.bounds(rotatedCorners, bounds).length > 0 + ) + } + + transform( + _shape: TextShape, + bounds: TLBounds, + { initialShape, scaleX, scaleY, transformOrigin }: TLTransformInfo + ): Partial { + const { + rotation = 0, + style: { scale = 1 }, + } = initialShape + + const nextScale = scale * Math.abs(Math.min(scaleX, scaleY)) + + return { + point: [bounds.minX, bounds.minY], + rotation: + (scaleX < 0 && scaleY >= 0) || (scaleY < 0 && scaleX >= 0) ? -(rotation || 0) : rotation, + style: { + ...initialShape.style, + scale: nextScale, + }, + } + } + + transformSingle( + _shape: TextShape, + bounds: TLBounds, + { initialShape, scaleX, scaleY }: TLTransformInfo + ): Partial { + const { + style: { scale = 1 }, + } = initialShape + + return { + point: Vec.round([bounds.minX, bounds.minY]), + style: { + ...initialShape.style, + scale: scale * Math.max(Math.abs(scaleY), Math.abs(scaleX)), + }, + } + } + + onBoundsReset(shape: TextShape): Partial { + const center = this.getCenter(shape) + + this.boundsCache.delete(shape) + + const newCenter = this.getCenter(shape) + + return { + style: { + ...shape.style, + scale: 1, + }, + point: Vec.round(Vec.add(shape.point, Vec.sub(center, newCenter))), + } + } + + onStyleChange(shape: TextShape): Partial { + const center = this.getCenter(shape) + + this.boundsCache.delete(shape) + + const newCenter = this.getCenter(shape) + + return { + point: Vec.round(Vec.add(shape.point, Vec.sub(center, newCenter))), + } + } + + shouldDelete(shape: TextShape): boolean { + return shape.text.trim().length === 0 + } + + getBindingPoint( + shape: TextShape, + fromShape: ArrowShape, + point: number[], + origin: number[], + direction: number[], + padding: number, + anywhere: boolean + ) { + const bounds = this.getBounds(shape) + + const expandedBounds = Utils.expandBounds(bounds, padding) + + let bindingPoint: number[] + let distance: number + + // The point must be inside of the expanded bounding box + if (!Utils.pointInBounds(point, expandedBounds)) return + + // The point is inside of the shape, so we'll assume the user is + // indicating a specific point inside of the shape. + if (anywhere) { + if (Vec.dist(point, this.getCenter(shape)) < 12) { + bindingPoint = [0.5, 0.5] + } else { + bindingPoint = Vec.divV(Vec.sub(point, [expandedBounds.minX, expandedBounds.minY]), [ + expandedBounds.width, + expandedBounds.height, + ]) + } + + distance = 0 + } else { + // Find furthest intersection between ray from + // origin through point and expanded bounds. + + // TODO: Make this a ray vs rounded rect intersection + const intersection = Intersect.ray + .bounds(origin, direction, expandedBounds) + .filter((int) => int.didIntersect) + .map((int) => int.points[0]) + .sort((a, b) => Vec.dist(b, origin) - Vec.dist(a, origin))[0] + + // The anchor is a point between the handle and the intersection + const anchor = Vec.med(point, intersection) + + // If we're close to the center, snap to the center + if (Vec.distanceToLineSegment(point, anchor, this.getCenter(shape)) < 12) { + bindingPoint = [0.5, 0.5] + } else { + // Or else calculate a normalized point + bindingPoint = Vec.divV(Vec.sub(anchor, [expandedBounds.minX, expandedBounds.minY]), [ + expandedBounds.width, + expandedBounds.height, + ]) + } + + if (Utils.pointInBounds(point, bounds)) { + distance = 16 + } else { + // If the binding point was close to the shape's center, snap to the center + // Find the distance between the point and the real bounds of the shape + distance = Math.max( + 16, + Utils.getBoundsSides(bounds) + .map((side) => Vec.distanceToLineSegment(side[1][0], side[1][1], point)) + .sort((a, b) => a - b)[0] + ) + } + } + + return { + point: Vec.clampV(bindingPoint, 0, 1), + distance, + } + } + // getBindingPoint(shape, point, origin, direction, expandDistance) { + // const bounds = this.getBounds(shape) + + // const expandedBounds = expandBounds(bounds, expandDistance) + + // let bindingPoint: number[] + // let distance: number + + // if (!HitTest.bounds(point, expandedBounds)) return + + // // The point is inside of the box, so we'll assume the user is + // // indicating a specific point inside of the box. + // if (HitTest.bounds(point, bounds)) { + // bindingPoint = vec.divV(vec.sub(point, [expandedBounds.minX, expandedBounds.minY]), [ + // expandedBounds.width, + // expandedBounds.height, + // ]) + + // distance = 0 + // } else { + // // Find furthest intersection between ray from + // // origin through point and expanded bounds. + // const intersection = Intersect.ray + // .bounds(origin, direction, expandedBounds) + // .filter(int => int.didIntersect) + // .map(int => int.points[0]) + // .sort((a, b) => vec.dist(b, origin) - vec.dist(a, origin))[0] + + // // The anchor is a point between the handle and the intersection + // const anchor = vec.med(point, intersection) + + // // Find the distance between the point and the real bounds of the shape + // const distanceFromShape = getBoundsSides(bounds) + // .map(side => vec.distanceToLineSegment(side[1][0], side[1][1], point)) + // .sort((a, b) => a - b)[0] + + // if (vec.distanceToLineSegment(point, anchor, this.getCenter(shape)) < 12) { + // // If we're close to the center, snap to the center + // bindingPoint = [0.5, 0.5] + // } else { + // // Or else calculate a normalized point + // bindingPoint = vec.divV(vec.sub(anchor, [expandedBounds.minX, expandedBounds.minY]), [ + // expandedBounds.width, + // expandedBounds.height, + // ]) + // } + + // distance = distanceFromShape + // } + + // return { + // point: bindingPoint, + // distance, + // } + // } +} + +const StyledTextArea = styled('textarea', { + zIndex: 1, + width: '100%', + height: '100%', + border: 'none', + padding: '4px', + whiteSpace: 'pre', + alignmentBaseline: 'mathematical', + dominantBaseline: 'mathematical', + resize: 'none', + minHeight: 1, + minWidth: 1, + lineHeight: 1.4, + letterSpacing: LETTER_SPACING, + outline: 0, + fontWeight: '500', + backgroundColor: '$boundsBg', + overflow: 'hidden', + pointerEvents: 'all', + backfaceVisibility: 'hidden', + display: 'inline-block', + userSelect: 'text', + WebkitUserSelect: 'text', + WebkitTouchCallout: 'none', +}) diff --git a/packages/tldraw/src/state/__snapshots__/tlstate.spec.ts.snap b/packages/tldraw/src/state/__snapshots__/tlstate.spec.ts.snap new file mode 100644 index 000000000..ed667cca7 --- /dev/null +++ b/packages/tldraw/src/state/__snapshots__/tlstate.spec.ts.snap @@ -0,0 +1,5 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[` 1`] = `"[]"`; + +exports[` 2`] = `undefined`; diff --git a/packages/tldraw/src/state/command/align/align.command.spec.ts b/packages/tldraw/src/state/command/align/align.command.spec.ts new file mode 100644 index 000000000..2a07d6fd6 --- /dev/null +++ b/packages/tldraw/src/state/command/align/align.command.spec.ts @@ -0,0 +1,73 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { AlignType } from '~types' + +describe('Align command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + tlstate.align(AlignType.Top) + + expect(tlstate.getShape('rect2').point).toEqual([100, 0]) + + tlstate.undo() + + expect(tlstate.getShape('rect2').point).toEqual([100, 100]) + + tlstate.redo() + + expect(tlstate.getShape('rect2').point).toEqual([100, 0]) + }) + + it('aligns top', () => { + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + tlstate.align(AlignType.Top) + + expect(tlstate.getShape('rect2').point).toEqual([100, 0]) + }) + + it('aligns right', () => { + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + tlstate.align(AlignType.Right) + + expect(tlstate.getShape('rect1').point).toEqual([100, 0]) + }) + + it('aligns bottom', () => { + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + tlstate.align(AlignType.Bottom) + + expect(tlstate.getShape('rect1').point).toEqual([0, 100]) + }) + + it('aligns left', () => { + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + tlstate.align(AlignType.Left) + + expect(tlstate.getShape('rect2').point).toEqual([0, 100]) + }) + + it('aligns center horizontal', () => { + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + tlstate.align(AlignType.CenterHorizontal) + + expect(tlstate.getShape('rect1').point).toEqual([50, 0]) + expect(tlstate.getShape('rect2').point).toEqual([50, 100]) + }) + + it('aligns center vertical', () => { + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + tlstate.align(AlignType.CenterVertical) + + expect(tlstate.getShape('rect1').point).toEqual([0, 50]) + expect(tlstate.getShape('rect2').point).toEqual([100, 50]) + }) +}) diff --git a/packages/tldraw/src/state/command/align/align.command.ts b/packages/tldraw/src/state/command/align/align.command.ts new file mode 100644 index 000000000..9ee5bdd11 --- /dev/null +++ b/packages/tldraw/src/state/command/align/align.command.ts @@ -0,0 +1,73 @@ +import { Utils } from '@tldraw/core' +import { AlignType, TLDrawCommand } from '~types' +import type { Data } from '~types' +import { TLDR } from '~state/tldr' + +export function align(data: Data, ids: string[], type: AlignType): TLDrawCommand { + const { currentPageId } = data.appState + const initialShapes = ids.map((id) => TLDR.getShape(data, id, currentPageId)) + + const boundsForShapes = initialShapes.map((shape) => { + return { + id: shape.id, + point: [...shape.point], + bounds: TLDR.getShapeUtils(shape).getBounds(shape), + } + }) + + const commonBounds = Utils.getCommonBounds(boundsForShapes.map(({ bounds }) => bounds)) + + const midX = commonBounds.minX + commonBounds.width / 2 + const midY = commonBounds.minY + commonBounds.height / 2 + + const deltaMap = Object.fromEntries( + boundsForShapes.map(({ id, point, bounds }) => { + return [ + id, + { + prev: point, + next: { + [AlignType.CenterVertical]: [point[0], midY - bounds.height / 2], + [AlignType.CenterHorizontal]: [midX - bounds.width / 2, point[1]], + [AlignType.Top]: [point[0], commonBounds.minY], + [AlignType.Bottom]: [point[0], commonBounds.maxY - bounds.height], + [AlignType.Left]: [commonBounds.minX, point[1]], + [AlignType.Right]: [commonBounds.maxX - bounds.width, point[1]], + }[type], + }, + ] + }) + ) + + const { before, after } = TLDR.mutateShapes( + data, + ids, + (shape) => { + if (!deltaMap[shape.id]) return shape + return { point: deltaMap[shape.id].next } + }, + currentPageId + ) + + return { + id: 'align_shapes', + before: { + document: { + pages: { + [currentPageId]: { + shapes: before, + }, + }, + }, + }, + after: { + document: { + pages: { + [currentPageId]: { + shapes: after, + }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/align/index.ts b/packages/tldraw/src/state/command/align/index.ts new file mode 100644 index 000000000..aea979be5 --- /dev/null +++ b/packages/tldraw/src/state/command/align/index.ts @@ -0,0 +1 @@ +export * from './align.command' diff --git a/packages/tldraw/src/state/command/change-page/change-page.command.spec.ts b/packages/tldraw/src/state/command/change-page/change-page.command.spec.ts new file mode 100644 index 000000000..6f1379179 --- /dev/null +++ b/packages/tldraw/src/state/command/change-page/change-page.command.spec.ts @@ -0,0 +1,32 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' + +describe('Change page command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + + const initialId = tlstate.page.id + + tlstate.createPage() + + const nextId = tlstate.page.id + + tlstate.changePage(initialId) + + expect(tlstate.page.id).toBe(initialId) + + tlstate.changePage(nextId) + + expect(tlstate.page.id).toBe(nextId) + + tlstate.undo() + + expect(tlstate.page.id).toBe(initialId) + + tlstate.redo() + + expect(tlstate.page.id).toBe(nextId) + }) +}) diff --git a/packages/tldraw/src/state/command/change-page/change-page.command.ts b/packages/tldraw/src/state/command/change-page/change-page.command.ts new file mode 100644 index 000000000..a625b3000 --- /dev/null +++ b/packages/tldraw/src/state/command/change-page/change-page.command.ts @@ -0,0 +1,17 @@ +import type { Data, TLDrawCommand } from '~types' + +export function changePage(data: Data, pageId: string): TLDrawCommand { + return { + id: 'change_page', + before: { + appState: { + currentPageId: data.appState.currentPageId, + }, + }, + after: { + appState: { + currentPageId: pageId, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/change-page/index.ts b/packages/tldraw/src/state/command/change-page/index.ts new file mode 100644 index 000000000..9bb65fb23 --- /dev/null +++ b/packages/tldraw/src/state/command/change-page/index.ts @@ -0,0 +1 @@ +export * from './change-page.command' diff --git a/packages/tldraw/src/state/command/create-page/create-page.command.spec.ts b/packages/tldraw/src/state/command/create-page/create-page.command.spec.ts new file mode 100644 index 000000000..e25ff1a36 --- /dev/null +++ b/packages/tldraw/src/state/command/create-page/create-page.command.spec.ts @@ -0,0 +1,34 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' + +describe('Create page command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + + const initialId = tlstate.page.id + const initialPageState = tlstate.pageState + + tlstate.createPage() + + const nextId = tlstate.page.id + const nextPageState = tlstate.pageState + + expect(Object.keys(tlstate.document.pages).length).toBe(2) + expect(tlstate.page.id).toBe(nextId) + expect(tlstate.pageState).toEqual(nextPageState) + + tlstate.undo() + + expect(Object.keys(tlstate.document.pages).length).toBe(1) + expect(tlstate.page.id).toBe(initialId) + expect(tlstate.pageState).toEqual(initialPageState) + + tlstate.redo() + + expect(Object.keys(tlstate.document.pages).length).toBe(2) + expect(tlstate.page.id).toBe(nextId) + expect(tlstate.pageState).toEqual(nextPageState) + }) +}) diff --git a/packages/tldraw/src/state/command/create-page/create-page.command.ts b/packages/tldraw/src/state/command/create-page/create-page.command.ts new file mode 100644 index 000000000..746e6d930 --- /dev/null +++ b/packages/tldraw/src/state/command/create-page/create-page.command.ts @@ -0,0 +1,64 @@ +import type { Data, TLDrawCommand, TLDrawPage } from '~types' +import { Utils, TLPageState } from '@tldraw/core' + +export function createPage(data: Data, pageId = Utils.uniqueId()): TLDrawCommand { + const { currentPageId } = data.appState + + const topPage = Object.values(data.document.pages).sort( + (a, b) => (b.childIndex || 0) - (a.childIndex || 0) + )[0] + + const nextChildIndex = topPage?.childIndex ? topPage?.childIndex + 1 : 1 + + // TODO: Iterate the name better + const nextName = `Page ${nextChildIndex}` + + const page: TLDrawPage = { + id: pageId, + name: nextName, + shapes: {}, + childIndex: nextChildIndex, + bindings: {}, + } + + const pageState: TLPageState = { + id: pageId, + selectedIds: [], + camera: { point: [-window.innerWidth / 2, -window.innerHeight / 2], zoom: 1 }, + currentParentId: pageId, + editingId: undefined, + bindingId: undefined, + hoveredId: undefined, + pointedId: undefined, + } + + return { + id: 'create_page', + before: { + appState: { + currentPageId, + }, + document: { + pages: { + [pageId]: undefined, + }, + pageStates: { + [pageId]: undefined, + }, + }, + }, + after: { + appState: { + currentPageId: page.id, + }, + document: { + pages: { + [pageId]: page, + }, + pageStates: { + [pageId]: pageState, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/create-page/index.ts b/packages/tldraw/src/state/command/create-page/index.ts new file mode 100644 index 000000000..3a7e688ee --- /dev/null +++ b/packages/tldraw/src/state/command/create-page/index.ts @@ -0,0 +1 @@ +export * from './create-page.command' diff --git a/packages/tldraw/src/state/command/create/create.command.spec.ts b/packages/tldraw/src/state/command/create/create.command.spec.ts new file mode 100644 index 000000000..39adf2b77 --- /dev/null +++ b/packages/tldraw/src/state/command/create/create.command.spec.ts @@ -0,0 +1,22 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' + +describe('Create command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + const shape = { ...tlstate.getShape('rect1'), id: 'rect4' } + tlstate.create(shape) + + expect(tlstate.getShape('rect4')).toBeTruthy() + + tlstate.undo() + + expect(tlstate.getShape('rect4')).toBe(undefined) + + tlstate.redo() + + expect(tlstate.getShape('rect4')).toBeTruthy() + }) +}) diff --git a/packages/tldraw/src/state/command/create/create.command.ts b/packages/tldraw/src/state/command/create/create.command.ts new file mode 100644 index 000000000..12959acf4 --- /dev/null +++ b/packages/tldraw/src/state/command/create/create.command.ts @@ -0,0 +1,47 @@ +import type { Patch } from 'rko' +import { TLDR } from '~state/tldr' +import type { TLDrawShape, Data, TLDrawCommand } from '~types' + +export function create(data: Data, shapes: TLDrawShape[]): TLDrawCommand { + const { currentPageId } = data.appState + + const beforeShapes: Record | undefined> = {} + const afterShapes: Record | undefined> = {} + + shapes.forEach((shape) => { + beforeShapes[shape.id] = undefined + afterShapes[shape.id] = shape + }) + + return { + id: 'toggle_shapes', + before: { + document: { + pages: { + [currentPageId]: { + shapes: beforeShapes, + }, + }, + pageStates: { + [currentPageId]: { + selectedIds: [...TLDR.getSelectedIds(data, currentPageId)], + }, + }, + }, + }, + after: { + document: { + pages: { + [currentPageId]: { + shapes: afterShapes, + }, + }, + pageStates: { + [currentPageId]: { + selectedIds: shapes.map((shape) => shape.id), + }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/create/index.ts b/packages/tldraw/src/state/command/create/index.ts new file mode 100644 index 000000000..23c51abde --- /dev/null +++ b/packages/tldraw/src/state/command/create/index.ts @@ -0,0 +1 @@ +export * from './create.command' diff --git a/packages/tldraw/src/state/command/delete-page/delete-page.command.spec.ts b/packages/tldraw/src/state/command/delete-page/delete-page.command.spec.ts new file mode 100644 index 000000000..193d85c34 --- /dev/null +++ b/packages/tldraw/src/state/command/delete-page/delete-page.command.spec.ts @@ -0,0 +1,28 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' + +describe('Delete page', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + + const initialId = tlstate.currentPageId + + tlstate.createPage() + + const nextId = tlstate.currentPageId + + tlstate.deletePage() + + expect(tlstate.currentPageId).toBe(initialId) + + tlstate.undo() + + expect(tlstate.currentPageId).toBe(nextId) + + tlstate.redo() + + expect(tlstate.currentPageId).toBe(initialId) + }) +}) diff --git a/packages/tldraw/src/state/command/delete-page/delete-page.command.ts b/packages/tldraw/src/state/command/delete-page/delete-page.command.ts new file mode 100644 index 000000000..b54fd7d8b --- /dev/null +++ b/packages/tldraw/src/state/command/delete-page/delete-page.command.ts @@ -0,0 +1,53 @@ +import type { Data, TLDrawCommand } from '~types' + +export function deletePage(data: Data, pageId: string): TLDrawCommand { + const { currentPageId } = data.appState + + const pagesArr = Object.values(data.document.pages).sort( + (a, b) => (a.childIndex || 0) - (b.childIndex || 0) + ) + + const currentIndex = pagesArr.findIndex((page) => page.id === pageId) + + let nextCurrentPageId: string + + if (pageId === currentPageId) { + if (currentIndex === pagesArr.length - 1) { + nextCurrentPageId = pagesArr[pagesArr.length - 2].id + } else { + nextCurrentPageId = pagesArr[currentIndex + 1].id + } + } else { + nextCurrentPageId = currentPageId + } + + return { + id: 'delete_page', + before: { + appState: { + currentPageId: pageId, + }, + document: { + pages: { + [pageId]: { ...data.document.pages[pageId] }, + }, + pageStates: { + [pageId]: { ...data.document.pageStates[pageId] }, + }, + }, + }, + after: { + appState: { + currentPageId: nextCurrentPageId, + }, + document: { + pages: { + [pageId]: undefined, + }, + pageStates: { + [pageId]: undefined, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/delete-page/index.ts b/packages/tldraw/src/state/command/delete-page/index.ts new file mode 100644 index 000000000..e2cf32f75 --- /dev/null +++ b/packages/tldraw/src/state/command/delete-page/index.ts @@ -0,0 +1 @@ +export * from './delete-page.command' diff --git a/packages/tldraw/src/state/command/delete/delete.command.spec.ts b/packages/tldraw/src/state/command/delete/delete.command.spec.ts new file mode 100644 index 000000000..0051d0393 --- /dev/null +++ b/packages/tldraw/src/state/command/delete/delete.command.spec.ts @@ -0,0 +1,115 @@ +import { TLDR } from '~state/tldr' +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import type { TLDrawShape } from '~types' + +describe('Delete command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + tlstate.select('rect2') + tlstate.delete() + + expect(tlstate.getShape('rect2')).toBe(undefined) + expect(tlstate.getPageState().selectedIds.length).toBe(0) + + tlstate.undo() + + expect(tlstate.getShape('rect2')).toBeTruthy() + expect(tlstate.getPageState().selectedIds.length).toBe(1) + + tlstate.redo() + + expect(tlstate.getShape('rect2')).toBe(undefined) + expect(tlstate.getPageState().selectedIds.length).toBe(0) + }) + + it('deletes two shapes', () => { + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + tlstate.delete() + + expect(tlstate.getShape('rect1')).toBe(undefined) + expect(tlstate.getShape('rect2')).toBe(undefined) + + tlstate.undo() + + expect(tlstate.getShape('rect1')).toBeTruthy() + expect(tlstate.getShape('rect2')).toBeTruthy() + + tlstate.redo() + + expect(tlstate.getShape('rect1')).toBe(undefined) + expect(tlstate.getShape('rect2')).toBe(undefined) + }) + + it('deletes bound shapes', () => { + tlstate.loadDocument(mockDocument) + + expect(Object.values(tlstate.page.bindings)[0]).toBe(undefined) + + tlstate + .deselectAll() + .create( + TLDR.getShapeUtils({ type: 'arrow' } as TLDrawShape).create({ + id: 'arrow1', + parentId: 'page1', + }) + ) + .select('arrow1') + .startHandleSession([0, 0], 'start') + .updateHandleSession([110, 110]) + .completeSession() + + const binding = Object.values(tlstate.page.bindings)[0] + + expect(binding).toBeTruthy() + expect(binding.fromId).toBe('arrow1') + expect(binding.toId).toBe('rect3') + expect(binding.handleId).toBe('start') + expect(tlstate.getShape('arrow1').handles?.start.bindingId).toBe(binding.id) + + tlstate.select('rect3').delete() + + expect(Object.values(tlstate.page.bindings)[0]).toBe(undefined) + expect(tlstate.getShape('arrow1').handles?.start.bindingId).toBe(undefined) + + tlstate.undo() + + expect(Object.values(tlstate.page.bindings)[0]).toBeTruthy() + expect(tlstate.getShape('arrow1').handles?.start.bindingId).toBe(binding.id) + + tlstate.redo() + + expect(Object.values(tlstate.page.bindings)[0]).toBe(undefined) + expect(tlstate.getShape('arrow1').handles?.start.bindingId).toBe(undefined) + }) + + describe('when deleting grouped shapes', () => { + it('updates the group', () => { + tlstate + .loadDocument(mockDocument) + .group(['rect1', 'rect2', 'rect3'], 'newGroup') + .select('rect1') + .delete() + + expect(tlstate.getShape('rect1')).toBeUndefined() + expect(tlstate.getShape('newGroup').children).toStrictEqual(['rect2', 'rect3']) + }) + }) + + describe('when deleting shapes with children', () => { + it('also deletes the children', () => { + tlstate + .loadDocument(mockDocument) + .group(['rect1', 'rect2'], 'newGroup') + .select('newGroup') + .delete() + + expect(tlstate.getShape('rect1')).toBeUndefined() + expect(tlstate.getShape('rect2')).toBeUndefined() + expect(tlstate.getShape('newGroup')).toBeUndefined() + }) + }) +}) diff --git a/packages/tldraw/src/state/command/delete/delete.command.ts b/packages/tldraw/src/state/command/delete/delete.command.ts new file mode 100644 index 000000000..d9cf709e0 --- /dev/null +++ b/packages/tldraw/src/state/command/delete/delete.command.ts @@ -0,0 +1,37 @@ +import { TLDR } from '~state/tldr' +import type { Data, TLDrawCommand } from '~types' +import { removeShapesFromPage } from '../utils/removeShapesFromPage' + +// - [ ] Update parents and possibly delete parents + +export function deleteShapes( + data: Data, + ids: string[], + pageId = data.appState.currentPageId +): TLDrawCommand { + const { before, after } = removeShapesFromPage(data, ids, pageId) + + return { + id: 'delete_shapes', + before: { + document: { + pages: { + [pageId]: before, + }, + pageStates: { + [pageId]: { selectedIds: TLDR.getSelectedIds(data, pageId) }, + }, + }, + }, + after: { + document: { + pages: { + [pageId]: after, + }, + pageStates: { + [pageId]: { selectedIds: [] }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/delete/index.ts b/packages/tldraw/src/state/command/delete/index.ts new file mode 100644 index 000000000..8533b6a4d --- /dev/null +++ b/packages/tldraw/src/state/command/delete/index.ts @@ -0,0 +1 @@ +export * from './delete.command' diff --git a/packages/tldraw/src/state/command/distribute/distribute.command.spec.ts b/packages/tldraw/src/state/command/distribute/distribute.command.spec.ts new file mode 100644 index 000000000..15adad42c --- /dev/null +++ b/packages/tldraw/src/state/command/distribute/distribute.command.spec.ts @@ -0,0 +1,25 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { DistributeType } from '~types' + +describe('Distribute command', () => { + const tlstate = new TLDrawState() + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + + it('does, undoes and redoes command', () => { + tlstate.distribute(DistributeType.Horizontal) + expect(tlstate.getShape('rect3').point).toEqual([50, 20]) + tlstate.undo() + expect(tlstate.getShape('rect3').point).toEqual([20, 20]) + tlstate.redo() + expect(tlstate.getShape('rect3').point).toEqual([50, 20]) + }) + + it('distributes vertically', () => { + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + tlstate.distribute(DistributeType.Vertical) + expect(tlstate.getShape('rect3').point).toEqual([20, 50]) + }) +}) diff --git a/packages/tldraw/src/state/command/distribute/distribute.command.ts b/packages/tldraw/src/state/command/distribute/distribute.command.ts new file mode 100644 index 000000000..fa73a892e --- /dev/null +++ b/packages/tldraw/src/state/command/distribute/distribute.command.ts @@ -0,0 +1,132 @@ +import { Utils } from '@tldraw/core' +import { DistributeType, TLDrawShape, Data, TLDrawCommand } from '~types' +import { TLDR } from '~state/tldr' + +export function distribute(data: Data, ids: string[], type: DistributeType): TLDrawCommand { + const { currentPageId } = data.appState + const initialShapes = ids.map((id) => TLDR.getShape(data, id, currentPageId)) + const deltaMap = Object.fromEntries(getDistributions(initialShapes, type).map((d) => [d.id, d])) + + const { before, after } = TLDR.mutateShapes( + data, + ids, + (shape) => { + if (!deltaMap[shape.id]) return shape + return { point: deltaMap[shape.id].next } + }, + currentPageId + ) + + return { + id: 'distribute_shapes', + before: { + document: { + pages: { + [currentPageId]: { shapes: before }, + }, + }, + }, + after: { + document: { + pages: { + [currentPageId]: { shapes: after }, + }, + }, + }, + } +} + +function getDistributions(initialShapes: TLDrawShape[], type: DistributeType) { + const entries = initialShapes.map((shape) => { + const utils = TLDR.getShapeUtils(shape) + return { + id: shape.id, + point: [...shape.point], + bounds: utils.getBounds(shape), + center: utils.getCenter(shape), + } + }) + + const len = entries.length + const commonBounds = Utils.getCommonBounds(entries.map(({ bounds }) => bounds)) + + const results: { id: string; prev: number[]; next: number[] }[] = [] + + switch (type) { + case DistributeType.Horizontal: { + const span = entries.reduce((a, c) => a + c.bounds.width, 0) + + if (span > commonBounds.width) { + const left = entries.sort((a, b) => a.bounds.minX - b.bounds.minX)[0] + + const right = entries.sort((a, b) => b.bounds.maxX - a.bounds.maxX)[0] + + const entriesToMove = entries + .filter((a) => a !== left && a !== right) + .sort((a, b) => a.center[0] - b.center[0]) + + const step = (right.center[0] - left.center[0]) / (len - 1) + + const x = left.center[0] + step + + entriesToMove.forEach(({ id, point, bounds }, i) => { + results.push({ + id, + prev: point, + next: [x + step * i - bounds.width / 2, bounds.minY], + }) + }) + } else { + const entriesToMove = entries.sort((a, b) => a.center[0] - b.center[0]) + + let x = commonBounds.minX + const step = (commonBounds.width - span) / (len - 1) + + entriesToMove.forEach(({ id, point, bounds }) => { + results.push({ id, prev: point, next: [x, bounds.minY] }) + x += bounds.width + step + }) + } + break + } + case DistributeType.Vertical: { + const span = entries.reduce((a, c) => a + c.bounds.height, 0) + + if (span > commonBounds.height) { + const top = entries.sort((a, b) => a.bounds.minY - b.bounds.minY)[0] + + const bottom = entries.sort((a, b) => b.bounds.maxY - a.bounds.maxY)[0] + + const entriesToMove = entries + .filter((a) => a !== top && a !== bottom) + .sort((a, b) => a.center[1] - b.center[1]) + + const step = (bottom.center[1] - top.center[1]) / (len - 1) + + const y = top.center[1] + step + + entriesToMove.forEach(({ id, point, bounds }, i) => { + results.push({ + id, + prev: point, + next: [bounds.minX, y + step * i - bounds.height / 2], + }) + }) + } else { + const entriesToMove = entries.sort((a, b) => a.center[1] - b.center[1]) + + let y = commonBounds.minY + const step = (commonBounds.height - span) / (len - 1) + + entriesToMove.forEach(({ id, point, bounds }) => { + results.push({ id, prev: point, next: [bounds.minX, y] }) + y += bounds.height + step + }) + } + + break + } + } + + return results +} diff --git a/packages/tldraw/src/state/command/distribute/index.ts b/packages/tldraw/src/state/command/distribute/index.ts new file mode 100644 index 000000000..bfd88ac7f --- /dev/null +++ b/packages/tldraw/src/state/command/distribute/index.ts @@ -0,0 +1 @@ +export * from './distribute.command' diff --git a/packages/tldraw/src/state/command/duplicate-page/duplicate-page.command.spec.ts b/packages/tldraw/src/state/command/duplicate-page/duplicate-page.command.spec.ts new file mode 100644 index 000000000..8b215dbd2 --- /dev/null +++ b/packages/tldraw/src/state/command/duplicate-page/duplicate-page.command.spec.ts @@ -0,0 +1,24 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' + +describe('Duplicate page command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + + const initialId = tlstate.page.id + + tlstate.duplicatePage(tlstate.currentPageId) + + const nextId = tlstate.page.id + + tlstate.undo() + + expect(tlstate.page.id).toBe(initialId) + + tlstate.redo() + + expect(tlstate.page.id).toBe(nextId) + }) +}) diff --git a/packages/tldraw/src/state/command/duplicate-page/duplicate-page.command.ts b/packages/tldraw/src/state/command/duplicate-page/duplicate-page.command.ts new file mode 100644 index 000000000..935a77228 --- /dev/null +++ b/packages/tldraw/src/state/command/duplicate-page/duplicate-page.command.ts @@ -0,0 +1,65 @@ +import type { Data, TLDrawCommand } from '~types' +import { Utils } from '@tldraw/core' + +export function duplicatePage(data: Data, pageId: string): TLDrawCommand { + const newId = Utils.uniqueId() + const { currentPageId } = data.appState + + const page = data.document.pages[pageId] + + const nextPage = { + ...page, + id: newId, + shapes: Object.fromEntries( + Object.entries(page.shapes).map(([id, shape]) => { + return [ + id, + { + ...shape, + parentId: shape.parentId === pageId ? newId : shape.parentId, + }, + ] + }) + ), + } + + return { + id: 'duplicate_page', + before: { + appState: { + currentPageId, + }, + document: { + pages: { + [newId]: undefined, + }, + pageStates: { + [newId]: undefined, + }, + }, + }, + after: { + appState: { + currentPageId: newId, + }, + document: { + pages: { + [newId]: nextPage, + }, + pageStates: { + [newId]: { + ...page, + id: newId, + selectedIds: [], + camera: { point: [-window.innerWidth / 2, -window.innerHeight / 2], zoom: 1 }, + currentParentId: newId, + editingId: undefined, + bindingId: undefined, + hoveredId: undefined, + pointedId: undefined, + }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/duplicate-page/index.ts b/packages/tldraw/src/state/command/duplicate-page/index.ts new file mode 100644 index 000000000..88b563600 --- /dev/null +++ b/packages/tldraw/src/state/command/duplicate-page/index.ts @@ -0,0 +1 @@ +export * from './duplicate-page.command' diff --git a/packages/tldraw/src/state/command/duplicate/duplicate.command.spec.ts b/packages/tldraw/src/state/command/duplicate/duplicate.command.spec.ts new file mode 100644 index 000000000..12f2b1a1c --- /dev/null +++ b/packages/tldraw/src/state/command/duplicate/duplicate.command.spec.ts @@ -0,0 +1,161 @@ +/* eslint-disable @typescript-eslint/no-non-null-assertion */ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { ArrowShape, GroupShape, TLDrawShapeType } from '~types' + +describe('Duplicate command', () => { + const tlstate = new TLDrawState() + tlstate.loadDocument(mockDocument) + tlstate.select('rect1') + + it('does, undoes and redoes command', () => { + expect(Object.keys(tlstate.getPage().shapes).length).toBe(3) + + tlstate.duplicate() + + expect(Object.keys(tlstate.getPage().shapes).length).toBe(4) + + tlstate.undo() + + expect(Object.keys(tlstate.getPage().shapes).length).toBe(3) + + tlstate.redo() + + expect(Object.keys(tlstate.getPage().shapes).length).toBe(4) + }) + + describe('when duplicating a shape', () => { + it.todo('sets the correct props (parent and childIndex)') + }) + + describe('when duplicating a bound shape', () => { + it('removed the binding when the target is not selected', () => { + tlstate.resetDocument().createShapes( + { + id: 'target1', + type: TLDrawShapeType.Rectangle, + point: [0, 0], + size: [100, 100], + }, + { + type: TLDrawShapeType.Arrow, + id: 'arrow1', + point: [200, 200], + } + ) + + const beforeShapeIds = Object.keys(tlstate.page.shapes) + + tlstate + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([50, 50]) + .completeSession() + + const beforeArrow = tlstate.getShape('arrow1') + + expect(beforeArrow.handles.start.bindingId).toBeTruthy() + + tlstate.select('arrow1').duplicate() + + const afterShapeIds = Object.keys(tlstate.page.shapes) + + const newShapeIds = afterShapeIds.filter((id) => !beforeShapeIds.includes(id)) + + expect(newShapeIds.length).toBe(1) + + const duplicatedArrow = tlstate.getShape(newShapeIds[0]) + + expect(duplicatedArrow.handles.start.bindingId).toBeUndefined() + }) + + it('duplicates the binding when the target is selected', () => { + tlstate.resetDocument().createShapes( + { + id: 'target1', + type: TLDrawShapeType.Rectangle, + point: [0, 0], + size: [100, 100], + }, + { + type: TLDrawShapeType.Arrow, + id: 'arrow1', + point: [200, 200], + } + ) + + const beforeShapeIds = Object.keys(tlstate.page.shapes) + + tlstate + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([50, 50]) + .completeSession() + + const oldBindingId = tlstate.getShape('arrow1').handles.start.bindingId + expect(oldBindingId).toBeTruthy() + + tlstate.select('arrow1', 'target1').duplicate() + + const afterShapeIds = Object.keys(tlstate.page.shapes) + + const newShapeIds = afterShapeIds.filter((id) => !beforeShapeIds.includes(id)) + + expect(newShapeIds.length).toBe(2) + + const newBindingId = tlstate.getShape(newShapeIds[0]).handles.start.bindingId + + expect(newBindingId).toBeTruthy() + + tlstate.undo() + + expect(tlstate.getBinding(newBindingId!)).toBeUndefined() + expect(tlstate.getShape(newShapeIds[0])).toBeUndefined() + + tlstate.redo() + + expect(tlstate.getBinding(newBindingId!)).toBeTruthy() + expect(tlstate.getShape(newShapeIds[0]).handles.start.bindingId).toBe( + newBindingId + ) + }) + + it('duplicates groups', () => { + tlstate.loadDocument(mockDocument) + tlstate.group(['rect1', 'rect2'], 'newGroup').select('newGroup') + + const beforeShapeIds = Object.keys(tlstate.page.shapes) + + tlstate.duplicate() + + expect(Object.keys(tlstate.page.shapes).length).toBe(beforeShapeIds.length + 3) + + tlstate.undo() + + expect(Object.keys(tlstate.page.shapes).length).toBe(beforeShapeIds.length) + + tlstate.redo() + + expect(Object.keys(tlstate.page.shapes).length).toBe(beforeShapeIds.length + 3) + }) + + it('duplicates grouped shapes', () => { + tlstate.loadDocument(mockDocument) + tlstate.group(['rect1', 'rect2'], 'newGroup').select('rect1') + + const beforeShapeIds = Object.keys(tlstate.page.shapes) + + tlstate.duplicate() + + expect(Object.keys(tlstate.page.shapes).length).toBe(beforeShapeIds.length + 1) + + tlstate.undo() + + expect(Object.keys(tlstate.page.shapes).length).toBe(beforeShapeIds.length) + + tlstate.redo() + + expect(Object.keys(tlstate.page.shapes).length).toBe(beforeShapeIds.length + 1) + }) + }) +}) diff --git a/packages/tldraw/src/state/command/duplicate/duplicate.command.ts b/packages/tldraw/src/state/command/duplicate/duplicate.command.ts new file mode 100644 index 000000000..ffc6ccf5e --- /dev/null +++ b/packages/tldraw/src/state/command/duplicate/duplicate.command.ts @@ -0,0 +1,150 @@ +/* eslint-disable @typescript-eslint/no-non-null-assertion */ +import { Utils, Vec } from '@tldraw/core' +import { TLDR } from '~state/tldr' +import type { Data, PagePartial, TLDrawCommand } from '~types' + +export function duplicate(data: Data, ids: string[]): TLDrawCommand { + const { currentPageId } = data.appState + + const page = TLDR.getPage(data, currentPageId) + + const delta = Vec.div([16, 16], TLDR.getCamera(data, currentPageId).zoom) + + const before: PagePartial = { + shapes: {}, + bindings: {}, + } + + const after: PagePartial = { + shapes: {}, + bindings: {}, + } + + const shapes = TLDR.getSelectedIds(data, currentPageId).map((id) => + TLDR.getShape(data, id, currentPageId) + ) + + const duplicateMap: Record = {} + + // Create duplicates + shapes + .filter((shape) => !ids.includes(shape.parentId)) + .forEach((shape) => { + const duplicatedId = Utils.uniqueId() + before.shapes[duplicatedId] = undefined + + after.shapes[duplicatedId] = { + ...Utils.deepClone(shape), + id: duplicatedId, + point: Vec.round(Vec.add(shape.point, delta)), + childIndex: TLDR.getChildIndexAbove(data, shape.id, currentPageId), + } + + if (shape.children) { + after.shapes[duplicatedId]!.children = [] + } + + if (shape.parentId !== currentPageId) { + const parent = TLDR.getShape(data, shape.parentId, currentPageId) + + before.shapes[parent.id] = { + ...before.shapes[parent.id], + children: parent.children, + } + + after.shapes[parent.id] = { + ...after.shapes[parent.id], + children: [...(after.shapes[parent.id] || parent).children!, duplicatedId], + } + } + + duplicateMap[shape.id] = duplicatedId + }) + + // If the shapes have children, then duplicate those too + shapes.forEach((shape) => { + if (shape.children) { + shape.children.forEach((childId) => { + const child = TLDR.getShape(data, childId, currentPageId) + const duplicatedId = Utils.uniqueId() + const duplicatedParentId = duplicateMap[shape.id] + before.shapes[duplicatedId] = undefined + after.shapes[duplicatedId] = { + ...Utils.deepClone(child), + id: duplicatedId, + parentId: duplicatedParentId, + point: Vec.round(Vec.add(child.point, delta)), + childIndex: TLDR.getChildIndexAbove(data, child.id, currentPageId), + } + duplicateMap[childId] = duplicatedId + after.shapes[duplicateMap[shape.id]]?.children?.push(duplicatedId) + }) + } + }) + + // Which ids did we end up duplicating? + const duplicatedShapeIds = Object.keys(duplicateMap) + + // Handle bindings that effect duplicated shapes + Object.values(page.bindings).forEach((binding) => { + if (duplicatedShapeIds.includes(binding.fromId)) { + if (duplicatedShapeIds.includes(binding.toId)) { + // If the binding is between two duplicating shapes then + // duplicate the binding, too + const duplicatedBindingId = Utils.uniqueId() + + const duplicatedBinding = { + ...Utils.deepClone(binding), + id: duplicatedBindingId, + fromId: duplicateMap[binding.fromId], + toId: duplicateMap[binding.toId], + } + + before.bindings[duplicatedBindingId] = undefined + after.bindings[duplicatedBindingId] = duplicatedBinding + + // Change the duplicated shape's handle so that it reference + // the duplicated binding + const boundShape = after.shapes[duplicatedBinding.fromId] + Object.values(boundShape!.handles!).forEach((handle) => { + if (handle!.bindingId === binding.id) { + handle!.bindingId = duplicatedBindingId + } + }) + } else { + // If only the fromId is selected, delete the binding on + // the duplicated shape's handles + const boundShape = after.shapes[duplicateMap[binding.fromId]] + Object.values(boundShape!.handles!).forEach((handle) => { + if (handle!.bindingId === binding.id) { + handle!.bindingId = undefined + } + }) + } + } + }) + + return { + id: 'duplicate', + before: { + document: { + pages: { + [currentPageId]: before, + }, + pageStates: { + [currentPageId]: { selectedIds: ids }, + }, + }, + }, + after: { + document: { + pages: { + [currentPageId]: after, + }, + pageStates: { + [currentPageId]: { selectedIds: duplicatedShapeIds.map((id) => duplicateMap[id]) }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/duplicate/index.ts b/packages/tldraw/src/state/command/duplicate/index.ts new file mode 100644 index 000000000..fb794578c --- /dev/null +++ b/packages/tldraw/src/state/command/duplicate/index.ts @@ -0,0 +1 @@ +export * from './duplicate.command' diff --git a/packages/tldraw/src/state/command/flip/flip.command.spec.ts b/packages/tldraw/src/state/command/flip/flip.command.spec.ts new file mode 100644 index 000000000..0ceba4b9c --- /dev/null +++ b/packages/tldraw/src/state/command/flip/flip.command.spec.ts @@ -0,0 +1,39 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import type { RectangleShape } from '~types' + +describe('Flip command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + tlstate.select('rect1', 'rect2') + tlstate.flipHorizontal() + + expect(tlstate.getShape('rect1').point).toStrictEqual([100, 0]) + + tlstate.undo() + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + + tlstate.redo() + + expect(tlstate.getShape('rect1').point).toStrictEqual([100, 0]) + }) + + it('flips horizontally', () => { + tlstate.loadDocument(mockDocument) + tlstate.select('rect1', 'rect2') + tlstate.flipHorizontal() + + expect(tlstate.getShape('rect1').point).toStrictEqual([100, 0]) + }) + + it('flips vertically', () => { + tlstate.loadDocument(mockDocument) + tlstate.select('rect1', 'rect2') + tlstate.flipVertical() + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 100]) + }) +}) diff --git a/packages/tldraw/src/state/command/flip/flip.command.ts b/packages/tldraw/src/state/command/flip/flip.command.ts new file mode 100644 index 000000000..1756b2ad2 --- /dev/null +++ b/packages/tldraw/src/state/command/flip/flip.command.ts @@ -0,0 +1,77 @@ +import { FlipType } from '~types' +import { TLBoundsCorner, Utils } from '@tldraw/core' +import type { Data, TLDrawCommand } from '~types' +import { TLDR } from '~state/tldr' + +export function flip(data: Data, ids: string[], type: FlipType): TLDrawCommand { + const { currentPageId } = data.appState + const initialShapes = ids.map((id) => TLDR.getShape(data, id, currentPageId)) + + const boundsForShapes = initialShapes.map((shape) => TLDR.getBounds(shape)) + + const commonBounds = Utils.getCommonBounds(boundsForShapes) + + const { before, after } = TLDR.mutateShapes( + data, + ids, + (shape) => { + const shapeBounds = TLDR.getBounds(shape) + + switch (type) { + case FlipType.Horizontal: { + const newShapeBounds = Utils.getRelativeTransformedBoundingBox( + commonBounds, + commonBounds, + shapeBounds, + true, + false + ) + + return TLDR.getShapeUtils(shape).transform(shape, newShapeBounds, { + type: TLBoundsCorner.TopLeft, + scaleX: -1, + scaleY: 1, + initialShape: shape, + transformOrigin: [0.5, 0.5], + }) + } + case FlipType.Vertical: { + const newShapeBounds = Utils.getRelativeTransformedBoundingBox( + commonBounds, + commonBounds, + shapeBounds, + false, + true + ) + + return TLDR.getShapeUtils(shape).transform(shape, newShapeBounds, { + type: TLBoundsCorner.TopLeft, + scaleX: 1, + scaleY: -1, + initialShape: shape, + transformOrigin: [0.5, 0.5], + }) + } + } + }, + currentPageId + ) + + return { + id: 'flip_shapes', + before: { + document: { + pages: { + [data.appState.currentPageId]: { shapes: before }, + }, + }, + }, + after: { + document: { + pages: { + [data.appState.currentPageId]: { shapes: after }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/flip/index.ts b/packages/tldraw/src/state/command/flip/index.ts new file mode 100644 index 000000000..d2efac785 --- /dev/null +++ b/packages/tldraw/src/state/command/flip/index.ts @@ -0,0 +1 @@ +export * from './flip.command' diff --git a/packages/tldraw/src/state/command/group/group.command.spec.ts b/packages/tldraw/src/state/command/group/group.command.spec.ts new file mode 100644 index 000000000..36be3f23a --- /dev/null +++ b/packages/tldraw/src/state/command/group/group.command.spec.ts @@ -0,0 +1,411 @@ +/* eslint-disable @typescript-eslint/ban-ts-comment */ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { GroupShape, TLDrawShape, TLDrawShapeType } from '~types' + +describe('Group command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + tlstate.group(['rect1', 'rect2'], 'newGroup') + + expect(tlstate.getShape('newGroup')).toBeTruthy() + + tlstate.undo() + + expect(tlstate.getShape('newGroup')).toBeUndefined() + + tlstate.redo() + + expect(tlstate.getShape('newGroup')).toBeTruthy() + }) + + describe('when less than two shapes are selected', () => { + it('does nothing', () => { + tlstate.loadDocument(mockDocument) + tlstate.deselectAll() + + // @ts-ignore + const stackLength = tlstate.stack.length + + tlstate.group([], 'newGroup') + expect(tlstate.getShape('newGroup')).toBeUndefined() + // @ts-ignore + expect(tlstate.stack.length).toBe(stackLength) + + tlstate.group(['rect1'], 'newGroup') + expect(tlstate.getShape('newGroup')).toBeUndefined() + // @ts-ignore + expect(tlstate.stack.length).toBe(stackLength) + }) + }) + + describe('when grouping shapes on the page', () => { + /* + When the parent is a page, the group is created as a child of the page + and the shapes are reparented to the group. The group's child + index should be the minimum child index of the selected shapes. + */ + + it('creates a group with the correct props', () => { + tlstate.loadDocument(mockDocument) + + tlstate.updateShapes( + { + id: 'rect1', + point: [300, 300], + childIndex: 3, + }, + { + id: 'rect2', + point: [20, 20], + childIndex: 4, + } + ) + + tlstate.group(['rect1', 'rect2'], 'newGroup') + const group = tlstate.getShape('newGroup') + expect(group).toBeTruthy() + expect(group.parentId).toBe('page1') + expect(group.childIndex).toBe(3) + expect(group.point).toStrictEqual([20, 20]) + expect(group.children).toStrictEqual(['rect1', 'rect2']) + }) + + it('reparents the grouped shapes', () => { + tlstate.loadDocument(mockDocument) + + tlstate.updateShapes( + { + id: 'rect1', + childIndex: 2.5, + }, + { + id: 'rect2', + childIndex: 4.7, + } + ) + + tlstate.group(['rect1', 'rect2'], 'newGroup') + + let rect1: TLDrawShape + let rect2: TLDrawShape + + rect1 = tlstate.getShape('rect1') + rect2 = tlstate.getShape('rect2') + // Reparents the shapes + expect(rect1.parentId).toBe('newGroup') + expect(rect2.parentId).toBe('newGroup') + // Sets and preserves the order of the grouped shapes + expect(rect1.childIndex).toBe(1) + expect(rect2.childIndex).toBe(2) + + tlstate.undo() + + rect1 = tlstate.getShape('rect1') + rect2 = tlstate.getShape('rect2') + // Restores the shapes' parentIds + expect(rect1.parentId).toBe('page1') + expect(rect2.parentId).toBe('page1') + // Restores the shapes' childIndexs + expect(rect1.childIndex).toBe(2.5) + expect(rect2.childIndex).toBe(4.7) + }) + }) + + describe('when grouping shapes that are the child of another group', () => { + /* + Do not allow groups to nest. All groups should be the parent of + the page: a group should never be the child of a different group. + This is a UX decision as much as a technical one. + */ + + it('creates a new group on the page', () => { + /* + When the selected shapes are the children of another group, and so + long as the children do not represent ALL of the group's children, + then a new group should be created that is a child of the parent group. + */ + + tlstate.resetDocument().createShapes( + { + id: 'rect1', + type: TLDrawShapeType.Rectangle, + childIndex: 1, + }, + { + id: 'rect2', + type: TLDrawShapeType.Rectangle, + childIndex: 2, + }, + { + id: 'rect3', + type: TLDrawShapeType.Rectangle, + childIndex: 3, + }, + { + id: 'rect4', + type: TLDrawShapeType.Rectangle, + childIndex: 4, + } + ) + + tlstate.group(['rect1', 'rect2', 'rect3', 'rect4'], 'newGroupA') + + expect(tlstate.getShape('newGroupA')).toBeTruthy() + expect(tlstate.getShape('rect1').childIndex).toBe(1) + expect(tlstate.getShape('rect2').childIndex).toBe(2) + expect(tlstate.getShape('rect3').childIndex).toBe(3) + expect(tlstate.getShape('rect4').childIndex).toBe(4) + expect(tlstate.getShape('newGroupA').children).toStrictEqual([ + 'rect1', + 'rect2', + 'rect3', + 'rect4', + ]) + + tlstate.group(['rect1', 'rect3'], 'newGroupB') + + expect(tlstate.getShape('newGroupA')).toBeTruthy() + expect(tlstate.getShape('rect2').childIndex).toBe(2) + expect(tlstate.getShape('rect4').childIndex).toBe(4) + expect(tlstate.getShape('newGroupA').children).toStrictEqual(['rect2', 'rect4']) + + expect(tlstate.getShape('newGroupB')).toBeTruthy() + expect(tlstate.getShape('rect1').childIndex).toBe(1) + expect(tlstate.getShape('rect3').childIndex).toBe(2) + expect(tlstate.getShape('newGroupB').children).toStrictEqual(['rect1', 'rect3']) + + tlstate.undo() + + expect(tlstate.getShape('newGroupA')).toBeTruthy() + expect(tlstate.getShape('rect1').childIndex).toBe(1) + expect(tlstate.getShape('rect2').childIndex).toBe(2) + expect(tlstate.getShape('rect3').childIndex).toBe(3) + expect(tlstate.getShape('rect4').childIndex).toBe(4) + expect(tlstate.getShape('newGroupA').children).toStrictEqual([ + 'rect1', + 'rect2', + 'rect3', + 'rect4', + ]) + + expect(tlstate.getShape('newGroupB')).toBeUndefined() + + tlstate.redo() + + expect(tlstate.getShape('newGroupA')).toBeTruthy() + expect(tlstate.getShape('rect2').childIndex).toBe(2) + expect(tlstate.getShape('rect4').childIndex).toBe(4) + expect(tlstate.getShape('newGroupA').children).toStrictEqual(['rect2', 'rect4']) + + expect(tlstate.getShape('newGroupB')).toBeTruthy() + expect(tlstate.getShape('rect1').childIndex).toBe(1) + expect(tlstate.getShape('rect3').childIndex).toBe(2) + expect(tlstate.getShape('newGroupB').children).toStrictEqual(['rect1', 'rect3']) + }) + + it('does not group shapes if shapes are all the groups children', () => { + /* + If the selected shapes represent ALL of the children of the a + group, then no effect should occur. + */ + tlstate.resetDocument().createShapes( + { + id: 'rect1', + type: TLDrawShapeType.Rectangle, + childIndex: 1, + }, + { + id: 'rect2', + type: TLDrawShapeType.Rectangle, + childIndex: 2, + }, + { + id: 'rect3', + type: TLDrawShapeType.Rectangle, + childIndex: 3, + } + ) + + tlstate.group(['rect1', 'rect2', 'rect3'], 'newGroupA') + tlstate.group(['rect1', 'rect2', 'rect3'], 'newGroupB') + expect(tlstate.getShape('newGroupB')).toBeUndefined() + }) + + it('deletes any groups that no longer have children', () => { + /* + If the selected groups included the children of another group + in addition to other shapes then that group should be destroyed. + Other rules around deleted shapes should here apply: bindings + connected to the group should be deleted, etc. + */ + tlstate.resetDocument().createShapes( + { + id: 'rect1', + type: TLDrawShapeType.Rectangle, + childIndex: 1, + }, + { + id: 'rect2', + type: TLDrawShapeType.Rectangle, + childIndex: 2, + }, + { + id: 'rect3', + type: TLDrawShapeType.Rectangle, + childIndex: 3, + } + ) + + tlstate.group(['rect1', 'rect2'], 'newGroupA') + tlstate.group(['rect1', 'rect2', 'rect3'], 'newGroupB') + expect(tlstate.getShape('newGroupA')).toBeUndefined() + expect(tlstate.getShape('newGroupB').children).toStrictEqual([ + 'rect1', + 'rect2', + 'rect3', + ]) + }) + + it('marges selected groups that no longer have children', () => { + /* + If the user is creating a group while having selected other + groups, then the selected groups should be destroyed and a new + group created with the selected shapes and the group(s)' children. + */ + tlstate.resetDocument().createShapes( + { + id: 'rect1', + type: TLDrawShapeType.Rectangle, + childIndex: 1, + }, + { + id: 'rect2', + type: TLDrawShapeType.Rectangle, + childIndex: 2, + }, + { + id: 'rect3', + type: TLDrawShapeType.Rectangle, + childIndex: 3, + } + ) + + tlstate.group(['rect1', 'rect2'], 'newGroupA') + tlstate.group(['newGroupA', 'rect3'], 'newGroupB') + expect(tlstate.getShape('newGroupA')).toBeUndefined() + expect(tlstate.getShape('newGroupB').children).toStrictEqual([ + 'rect1', + 'rect2', + 'rect3', + ]) + + tlstate.undo() + + expect(tlstate.getShape('newGroupB')).toBeUndefined() + expect(tlstate.getShape('newGroupA')).toBeDefined() + expect(tlstate.getShape('newGroupA').children).toStrictEqual(['rect1', 'rect2']) + + tlstate.redo() + + expect(tlstate.getShape('newGroupA')).toBeUndefined() + expect(tlstate.getShape('newGroupB')).toBeDefined() + expect(tlstate.getShape('newGroupB').children).toStrictEqual([ + 'rect1', + 'rect2', + 'rect3', + ]) + }) + + /* + The layers should be in the same order as the original layers as + they would have appeared on a layers tree (lowest child index + first, parent inclusive). + */ + + it.todo('preserves the child index order') + + /* --------------------- Nesting -------------------- */ + + // it.todo('creates the new group as a child of the parent group') + /* + The new group should be a child of the parent group. + */ + + // it.todo('moves the selected layers to the new group') + /* + The new group should have the selected children. The old parents + should no longer have the selected shapes among their children. + All of the selected shapes should be assigned the new parent. + */ + }) + + // describe('when grouping shapes with different parents', () => { + /* + When two shapes with different parents are grouped, the new parent + group should have the same parent as the shape nearest to the top + of the layer tree. The new group's child index should be that + shape's child index. + + For example, if the shapes are grouped in the following order: + + - page1 + - group1 + - arrow1 + - rect1 (x) + - arrow2 + - rect2 (x) + + The new parent group should have the same parent as rect1. + + - page1 + - group1 + - arrow1 + - group2 + - rect1 (x) + - rect2 (x) + - arrow2 + + If, instead, the shapes are grouped in the following order: + + - page1 + - arrow1 + - rect1 (x) + - group1 + - arrow2 + - rect2 (x) + + Then the new parent group should have the same parent as + rect2. + + - page1 + - arrow1 + - group2 (x) + - rect1 + - rect2 + - group1 + - arrow2 + + We can find this by searching the tree for the nearest shape to + the top. + */ + + // it.todo('creates a group in the correct place') + /* + The new group should be a child of the nearest shape to the top + of the tree. + */ + + /* + If the selected groups included the children of another group, then + that group should be destroyed. Other rules around deleted + shapes should here apply: bindings connected to the group + should be deleted, etc. + */ + + // it.todo('deletes any groups that no longer have children') + + // }) +}) diff --git a/packages/tldraw/src/state/command/group/group.command.ts b/packages/tldraw/src/state/command/group/group.command.ts new file mode 100644 index 000000000..733629c13 --- /dev/null +++ b/packages/tldraw/src/state/command/group/group.command.ts @@ -0,0 +1,224 @@ +import { TLDrawBinding, TLDrawShape, TLDrawShapeType } from '~types' +import { Utils } from '@tldraw/core' +import type { Data, TLDrawCommand } from '~types' +import { TLDR } from '~state/tldr' +import type { Patch } from 'rko' + +export function group( + data: Data, + ids: string[], + groupId = Utils.uniqueId() +): TLDrawCommand | undefined { + const beforeShapes: Record> = {} + const afterShapes: Record> = {} + + const beforeBindings: Record> = {} + const afterBindings: Record> = {} + + const { currentPageId } = data.appState + + const idsToGroup = [...ids] + const shapesToGroup: TLDrawShape[] = [] + const deletedGroupIds: string[] = [] + const otherEffectedGroups: TLDrawShape[] = [] + + // Collect all of the shapes to group (and their ids) + for (const id of ids) { + const shape = TLDR.getShape(data, id, currentPageId) + if (shape.children === undefined) { + shapesToGroup.push(shape) + } else { + otherEffectedGroups.push(shape) + idsToGroup.push(...shape.children) + shapesToGroup.push(...shape.children.map((id) => TLDR.getShape(data, id, currentPageId))) + } + } + + // 1. Can we create this group? + + // Do the shapes have the same parent? + if (shapesToGroup.every((shape) => shape.parentId === shapesToGroup[0].parentId)) { + // Is the common parent a shape (not the page)? + if (shapesToGroup[0].parentId !== currentPageId) { + const commonParent = TLDR.getShape(data, shapesToGroup[0].parentId, currentPageId) + // Are all of the common parent's shapes selected? + if (commonParent.children?.length === idsToGroup.length) { + // Don't create a group if that group would be the same as the + // existing group. + return + } + } + } + + // A flattened array of shapes from the page + const flattenedShapes = TLDR.flattenPage(data, currentPageId) + + // A map of shapes to their index in flattendShapes + const shapeIndexMap = Object.fromEntries( + shapesToGroup.map((shape) => [shape.id, flattenedShapes.indexOf(shape)]) + ) + + // An array of shapes in order by their index in flattendShapes + const sortedShapes = shapesToGroup.sort((a, b) => shapeIndexMap[a.id] - shapeIndexMap[b.id]) + + // The parentId is always the current page + const groupParentId = currentPageId // sortedShapes[0].parentId + + // The childIndex should be the lowest index of the selected shapes + // with a parent that is the current page; or else the child index + // of the lowest selected shape. + const groupChildIndex = ( + sortedShapes.filter((shape) => shape.parentId === currentPageId)[0] || sortedShapes[0] + ).childIndex + + // The shape's point is the min point of its childrens' common bounds + const groupBounds = Utils.getCommonBounds(shapesToGroup.map((shape) => TLDR.getBounds(shape))) + + // Create the group + beforeShapes[groupId] = undefined + + afterShapes[groupId] = TLDR.getShapeUtils({ type: TLDrawShapeType.Group } as TLDrawShape).create({ + id: groupId, + childIndex: groupChildIndex, + parentId: groupParentId, + point: [groupBounds.minX, groupBounds.minY], + size: [groupBounds.width, groupBounds.height], + children: sortedShapes.map((shape) => shape.id), + }) + + // Reparent shapes to the new group + sortedShapes.forEach((shape, index) => { + // If the shape is part of a different group, mark the parent shape for cleanup + if (shape.parentId !== currentPageId) { + const parentShape = TLDR.getShape(data, shape.parentId, currentPageId) + otherEffectedGroups.push(parentShape) + } + + beforeShapes[shape.id] = { + ...beforeShapes[shape.id], + parentId: shape.parentId, + childIndex: shape.childIndex, + } + + afterShapes[shape.id] = { + ...afterShapes[shape.id], + parentId: groupId, + childIndex: index + 1, + } + }) + + // Clean up effected parents + while (otherEffectedGroups.length > 0) { + const shape = otherEffectedGroups.pop() + if (!shape) break + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const nextChildren = (beforeShapes[shape.id]?.children || shape.children)!.filter( + (childId) => childId && !(idsToGroup.includes(childId) || deletedGroupIds.includes(childId)) + ) + + // If the parent has no children, remove it + if (nextChildren.length === 0) { + beforeShapes[shape.id] = shape + afterShapes[shape.id] = undefined + + // And if that parent is part of a different group, mark it for cleanup + // (This is necessary only when we implement nested groups.) + if (shape.parentId !== currentPageId) { + deletedGroupIds.push(shape.id) + otherEffectedGroups.push(TLDR.getShape(data, shape.parentId, currentPageId)) + } + } else { + beforeShapes[shape.id] = { + ...beforeShapes[shape.id], + children: shape.children, + } + + afterShapes[shape.id] = { + ...afterShapes[shape.id], + children: nextChildren, + } + } + } + + // TODO: This code is copied from delete.command. Create a shared helper! + + const page = TLDR.getPage(data, currentPageId) + + // We also need to delete bindings that reference the deleted shapes + Object.values(page.bindings).forEach((binding) => { + for (const id of [binding.toId, binding.fromId]) { + // If the binding references a deleted shape... + if (afterShapes[id] === undefined) { + // Delete this binding + beforeBindings[binding.id] = binding + afterBindings[binding.id] = undefined + + // Let's also look each the bound shape... + const shape = TLDR.getShape(data, id, currentPageId) + + // If the bound shape has a handle that references the deleted binding... + if (shape.handles) { + Object.values(shape.handles) + .filter((handle) => handle.bindingId === binding.id) + .forEach((handle) => { + // Save the binding reference in the before patch + beforeShapes[id] = { + ...beforeShapes[id], + handles: { + ...beforeShapes[id]?.handles, + [handle.id]: { bindingId: binding.id }, + }, + } + + // Unless we're currently deleting the shape, remove the + // binding reference from the after patch + if (!deletedGroupIds.includes(id)) { + afterShapes[id] = { + ...afterShapes[id], + handles: { + ...afterShapes[id]?.handles, + [handle.id]: { bindingId: undefined }, + }, + } + } + }) + } + } + } + }) + + return { + id: 'group_shapes', + before: { + document: { + pages: { + [currentPageId]: { + shapes: beforeShapes, + bindings: beforeBindings, + }, + }, + pageStates: { + [currentPageId]: { + selectedIds: TLDR.getSelectedIds(data, currentPageId), + }, + }, + }, + }, + after: { + document: { + pages: { + [currentPageId]: { + shapes: afterShapes, + bindings: beforeBindings, + }, + }, + pageStates: { + [currentPageId]: { + selectedIds: [groupId], + }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/group/index.ts b/packages/tldraw/src/state/command/group/index.ts new file mode 100644 index 000000000..44b50d441 --- /dev/null +++ b/packages/tldraw/src/state/command/group/index.ts @@ -0,0 +1 @@ +export * from './group.command' diff --git a/packages/tldraw/src/state/command/index.ts b/packages/tldraw/src/state/command/index.ts new file mode 100644 index 000000000..74a91480a --- /dev/null +++ b/packages/tldraw/src/state/command/index.ts @@ -0,0 +1,21 @@ +export * from './align' +export * from './change-page' +export * from './create-page' +export * from './create' +export * from './delete-page' +export * from './delete' +export * from './distribute' +export * from './duplicate-page' +export * from './duplicate' +export * from './flip' +export * from './group' +export * from './move' +export * from './rename-page' +export * from './rotate' +export * from './stretch' +export * from './style' +export * from './toggle-decoration' +export * from './toggle' +export * from './translate' +export * from './update' +export * from './move-to-page' diff --git a/packages/tldraw/src/state/command/move-to-page/index.ts b/packages/tldraw/src/state/command/move-to-page/index.ts new file mode 100644 index 000000000..21ecc899c --- /dev/null +++ b/packages/tldraw/src/state/command/move-to-page/index.ts @@ -0,0 +1 @@ +export * from './move-to-page.command' diff --git a/packages/tldraw/src/state/command/move-to-page/move-to-page.command.spec.ts b/packages/tldraw/src/state/command/move-to-page/move-to-page.command.spec.ts new file mode 100644 index 000000000..05dd9d995 --- /dev/null +++ b/packages/tldraw/src/state/command/move-to-page/move-to-page.command.spec.ts @@ -0,0 +1,250 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { ArrowShape, TLDrawShapeType } from '~types' + +describe('Move to page command', () => { + const tlstate = new TLDrawState() + + /* + Moving shapes to a new page should remove those shapes from the + current page and add them to the specifed page. If bindings exist + that effect the moved shapes, then the bindings should be destroyed + on the old page and created on the new page only if both the "to" + and "from" shapes were moved. The app should then change pages to + the new page. + */ + + it('does, undoes and redoes command', () => { + tlstate + .loadDocument(mockDocument) + .createPage('page2') + .changePage('page1') + .select('rect1', 'rect2') + .moveToPage('page2') + + expect(tlstate.currentPageId).toBe('page2') + expect(tlstate.getShape('rect1', 'page1')).toBeUndefined() + expect(tlstate.getShape('rect1', 'page2')).toBeDefined() + expect(tlstate.getShape('rect2', 'page1')).toBeUndefined() + expect(tlstate.getShape('rect2', 'page2')).toBeDefined() + expect(tlstate.selectedIds).toStrictEqual(['rect1', 'rect2']) + + tlstate.undo() + + expect(tlstate.getShape('rect1', 'page1')).toBeDefined() + expect(tlstate.getShape('rect1', 'page2')).toBeUndefined() + expect(tlstate.getShape('rect2', 'page1')).toBeDefined() + expect(tlstate.getShape('rect2', 'page2')).toBeUndefined() + expect(tlstate.selectedIds).toStrictEqual(['rect1', 'rect2']) + expect(tlstate.currentPageId).toBe('page1') + + tlstate.redo() + + expect(tlstate.getShape('rect1', 'page1')).toBeUndefined() + expect(tlstate.getShape('rect1', 'page2')).toBeDefined() + expect(tlstate.getShape('rect2', 'page1')).toBeUndefined() + expect(tlstate.getShape('rect2', 'page2')).toBeDefined() + expect(tlstate.selectedIds).toStrictEqual(['rect1', 'rect2']) + expect(tlstate.currentPageId).toBe('page2') + }) + + describe('when moving shapes with bindings', () => { + it('deletes bindings when only the bound-to shape is moved', () => { + tlstate + .loadDocument(mockDocument) + .selectAll() + .delete() + .createShapes( + { type: TLDrawShapeType.Rectangle, id: 'target1', size: [100, 100] }, + { type: TLDrawShapeType.Arrow, id: 'arrow1', point: [200, 200] } + ) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([50, 50]) + .completeSession() + + const bindingId = tlstate.bindings[0].id + expect(tlstate.getShape('arrow1').handles.start.bindingId).toBe(bindingId) + + tlstate.createPage('page2').changePage('page1').select('target1').moveToPage('page2') + + expect( + tlstate.getShape('arrow1', 'page1').handles.start.bindingId + ).toBeUndefined() + expect(tlstate.document.pages['page1'].bindings[bindingId]).toBeUndefined() + expect(tlstate.document.pages['page2'].bindings[bindingId]).toBeUndefined() + + tlstate.undo() + + expect(tlstate.getShape('arrow1', 'page1').handles.start.bindingId).toBe( + bindingId + ) + expect(tlstate.document.pages['page1'].bindings[bindingId]).toBeDefined() + expect(tlstate.document.pages['page2'].bindings[bindingId]).toBeUndefined() + + tlstate.redo() + + expect( + tlstate.getShape('arrow1', 'page1').handles.start.bindingId + ).toBeUndefined() + expect(tlstate.document.pages['page1'].bindings[bindingId]).toBeUndefined() + expect(tlstate.document.pages['page2'].bindings[bindingId]).toBeUndefined() + }) + + it('deletes bindings when only the bound-from shape is moved', () => { + tlstate + .loadDocument(mockDocument) + .selectAll() + .delete() + .createShapes( + { type: TLDrawShapeType.Rectangle, id: 'target1', size: [100, 100] }, + { type: TLDrawShapeType.Arrow, id: 'arrow1', point: [200, 200] } + ) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([50, 50]) + .completeSession() + + const bindingId = tlstate.bindings[0].id + expect(tlstate.getShape('arrow1').handles.start.bindingId).toBe(bindingId) + + tlstate.createPage('page2').changePage('page1').select('arrow1').moveToPage('page2') + + expect( + tlstate.getShape('arrow1', 'page2').handles.start.bindingId + ).toBeUndefined() + expect(tlstate.document.pages['page1'].bindings[bindingId]).toBeUndefined() + expect(tlstate.document.pages['page2'].bindings[bindingId]).toBeUndefined() + + tlstate.undo() + + expect(tlstate.getShape('arrow1', 'page1').handles.start.bindingId).toBe( + bindingId + ) + expect(tlstate.document.pages['page1'].bindings[bindingId]).toBeDefined() + expect(tlstate.document.pages['page2'].bindings[bindingId]).toBeUndefined() + + tlstate.redo() + + expect( + tlstate.getShape('arrow1', 'page2').handles.start.bindingId + ).toBeUndefined() + expect(tlstate.document.pages['page1'].bindings[bindingId]).toBeUndefined() + expect(tlstate.document.pages['page2'].bindings[bindingId]).toBeUndefined() + }) + + it('moves bindings when both shapes are moved', () => { + tlstate + .loadDocument(mockDocument) + .selectAll() + .delete() + .createShapes( + { type: TLDrawShapeType.Rectangle, id: 'target1', size: [100, 100] }, + { type: TLDrawShapeType.Arrow, id: 'arrow1', point: [200, 200] } + ) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([50, 50]) + .completeSession() + + const bindingId = tlstate.bindings[0].id + expect(tlstate.getShape('arrow1').handles.start.bindingId).toBe(bindingId) + + tlstate + .createPage('page2') + .changePage('page1') + .select('arrow1', 'target1') + .moveToPage('page2') + + expect(tlstate.getShape('arrow1', 'page2').handles.start.bindingId).toBe( + bindingId + ) + expect(tlstate.document.pages['page1'].bindings[bindingId]).toBeUndefined() + expect(tlstate.document.pages['page2'].bindings[bindingId]).toBeDefined() + + tlstate.undo() + + expect(tlstate.getShape('arrow1', 'page1').handles.start.bindingId).toBe( + bindingId + ) + expect(tlstate.document.pages['page1'].bindings[bindingId]).toBeDefined() + expect(tlstate.document.pages['page2'].bindings[bindingId]).toBeUndefined() + + tlstate.redo() + + expect(tlstate.getShape('arrow1', 'page2').handles.start.bindingId).toBe( + bindingId + ) + expect(tlstate.document.pages['page1'].bindings[bindingId]).toBeUndefined() + expect(tlstate.document.pages['page2'].bindings[bindingId]).toBeDefined() + }) + }) + + describe('when moving grouped shapes', () => { + it('moves groups and their children', () => { + tlstate + .loadDocument(mockDocument) + .createPage('page2') + .changePage('page1') + .group(['rect1', 'rect2'], 'groupA') + .moveToPage('page2') + + expect(tlstate.getShape('rect1', 'page1')).toBeUndefined() + expect(tlstate.getShape('rect2', 'page1')).toBeUndefined() + expect(tlstate.getShape('groupA', 'page1')).toBeUndefined() + + expect(tlstate.getShape('rect1', 'page2')).toBeDefined() + expect(tlstate.getShape('rect2', 'page2')).toBeDefined() + expect(tlstate.getShape('groupA', 'page2')).toBeDefined() + + tlstate.undo() + + expect(tlstate.getShape('rect1', 'page2')).toBeUndefined() + expect(tlstate.getShape('rect2', 'page2')).toBeUndefined() + expect(tlstate.getShape('groupA', 'page2')).toBeUndefined() + + expect(tlstate.getShape('rect1', 'page1')).toBeDefined() + expect(tlstate.getShape('rect2', 'page1')).toBeDefined() + expect(tlstate.getShape('groupA', 'page1')).toBeDefined() + + tlstate.redo() + + expect(tlstate.getShape('rect1', 'page1')).toBeUndefined() + expect(tlstate.getShape('rect2', 'page1')).toBeUndefined() + expect(tlstate.getShape('groupA', 'page1')).toBeUndefined() + + expect(tlstate.getShape('rect1', 'page2')).toBeDefined() + expect(tlstate.getShape('rect2', 'page2')).toBeDefined() + expect(tlstate.getShape('groupA', 'page2')).toBeDefined() + }) + + it('deletes groups shapes if the groups children were all moved', () => { + // ... + }) + + it('reparents grouped shapes if the group is not moved', () => { + tlstate + .loadDocument(mockDocument) + .createPage('page2') + .changePage('page1') + .group(['rect1', 'rect2', 'rect3'], 'groupA') + .select('rect1') + .moveToPage('page2') + + expect(tlstate.getShape('rect1', 'page1')).toBeUndefined() + expect(tlstate.getShape('rect1', 'page2')).toBeDefined() + expect(tlstate.getShape('rect1', 'page2').parentId).toBe('page2') + expect(tlstate.getShape('groupA', 'page1').children).toStrictEqual(['rect2', 'rect3']) + + tlstate.undo() + + expect(tlstate.getShape('rect1', 'page2')).toBeUndefined() + expect(tlstate.getShape('rect1', 'page1').parentId).toBe('groupA') + expect(tlstate.getShape('groupA', 'page1').children).toStrictEqual([ + 'rect1', + 'rect2', + 'rect3', + ]) + }) + }) +}) diff --git a/packages/tldraw/src/state/command/move-to-page/move-to-page.command.ts b/packages/tldraw/src/state/command/move-to-page/move-to-page.command.ts new file mode 100644 index 000000000..a0cbbe97e --- /dev/null +++ b/packages/tldraw/src/state/command/move-to-page/move-to-page.command.ts @@ -0,0 +1,211 @@ +/* eslint-disable @typescript-eslint/no-non-null-assertion */ +import type { ArrowShape, Data, PagePartial, TLDrawCommand, TLDrawShape } from '~types' +import { TLDR } from '~state/tldr' +import { Utils, Vec } from '@tldraw/core' + +export function moveToPage( + data: Data, + ids: string[], + fromPageId: string, + toPageId: string +): TLDrawCommand { + const { currentPageId } = data.appState + + const page = TLDR.getPage(data, currentPageId) + + const fromPage: Record = { + before: { + shapes: {}, + bindings: {}, + }, + after: { + shapes: {}, + bindings: {}, + }, + } + + const toPage: Record = { + before: { + shapes: {}, + bindings: {}, + }, + after: { + shapes: {}, + bindings: {}, + }, + } + + // Collect all the shapes to move and their keys. + const movingShapeIds = new Set() + const shapesToMove = new Set() + + ids + .map((id) => TLDR.getShape(data, id, fromPageId)) + .forEach((shape) => { + movingShapeIds.add(shape.id) + shapesToMove.add(shape) + if (shape.children !== undefined) { + shape.children.forEach((childId) => { + movingShapeIds.add(childId) + shapesToMove.add(TLDR.getShape(data, childId, fromPageId)) + }) + } + }) + + // Where should we put start putting shapes on the "to" page? + const startingChildIndex = TLDR.getTopChildIndex(data, toPageId) + + // Which shapes are we moving? + const movingShapes = Array.from(shapesToMove.values()) + + movingShapes.forEach((shape, i) => { + // Remove the shape from the fromPage + fromPage.before.shapes[shape.id] = shape + fromPage.after.shapes[shape.id] = undefined + + // But the moved shape on the "to" page + toPage.before.shapes[shape.id] = undefined + toPage.after.shapes[shape.id] = shape + + // If the shape's parent isn't moving too, reparent the shape to + // the "to" page, at the top of the z stack + if (!movingShapeIds.has(shape.parentId)) { + toPage.after.shapes[shape.id] = { + ...shape, + parentId: toPageId, + childIndex: startingChildIndex + i, + } + + // If the shape was in a group, then pull the shape from the + // parent's children array. + if (shape.parentId !== fromPageId) { + const parent = TLDR.getShape(data, shape.parentId, fromPageId) + fromPage.before.shapes[parent.id] = { + children: parent.children, + } + + fromPage.after.shapes[parent.id] = { + children: parent.children!.filter((childId) => childId !== shape.id), + } + } + } + }) + + // Handle bindings that effect duplicated shapes + Object.values(page.bindings) + .filter((binding) => movingShapeIds.has(binding.fromId) || movingShapeIds.has(binding.toId)) + .forEach((binding) => { + // Always delete the binding from the from page + + fromPage.before.bindings[binding.id] = binding + fromPage.after.bindings[binding.id] = undefined + + // Delete the reference from the binding's fromShape + + const fromBoundShape = TLDR.getShape(data, binding.fromId, fromPageId) + + // Will we be copying this binding to the new page? + + const shouldCopy = movingShapeIds.has(binding.fromId) && movingShapeIds.has(binding.toId) + + if (shouldCopy) { + // Just move the binding to the new page + toPage.before.bindings[binding.id] = undefined + toPage.after.bindings[binding.id] = binding + } else { + if (movingShapeIds.has(binding.fromId)) { + // If we are only moving the "from" shape, we need to delete + // the binding reference from the "from" shapes handles + const fromShape = TLDR.getShape(data, binding.fromId, fromPageId) + const handle = Object.values(fromBoundShape.handles!).find( + (handle) => handle.bindingId === binding.id + )! + + // Remove the handle from the shape on the toPage + + const handleId = handle.id as keyof ArrowShape['handles'] + + const toPageShape = toPage.after.shapes[fromShape.id]! + + toPageShape.handles = { + ...toPageShape.handles, + [handleId]: { + ...toPageShape.handles![handleId], + bindingId: undefined, + }, + } + } else { + // If we are only moving the "to" shape, we need to delete + // the binding reference from the "from" shape's handles + const fromShape = TLDR.getShape(data, binding.fromId, fromPageId) + const handle = Object.values(fromBoundShape.handles!).find( + (handle) => handle.bindingId === binding.id + )! + + fromPage.before.shapes[fromShape.id] = { + handles: { [handle.id]: { bindingId: binding.id } }, + } + + fromPage.after.shapes[fromShape.id] = { + handles: { [handle.id]: { bindingId: undefined } }, + } + } + } + }) + + // Finally, center camera on selection + + const toPageState = data.document.pageStates[toPageId] + const bounds = Utils.getCommonBounds(movingShapes.map((shape) => TLDR.getBounds(shape))) + const zoom = TLDR.getCameraZoom( + window.innerWidth < window.innerHeight + ? (window.innerWidth - 128) / bounds.width + : (window.innerHeight - 128) / bounds.height + ) + const mx = (window.innerWidth - bounds.width * zoom) / 2 / zoom + const my = (window.innerHeight - bounds.height * zoom) / 2 / zoom + const point = Vec.round(Vec.add([-bounds.minX, -bounds.minY], [mx, my])) + + return { + id: 'move_to_page', + before: { + appState: { + currentPageId: fromPageId, + }, + document: { + pages: { + [fromPageId]: fromPage.before, + [toPageId]: toPage.before, + }, + pageStates: { + [fromPageId]: { selectedIds: ids }, + [toPageId]: { + selectedIds: toPageState.selectedIds, + camera: toPageState.camera, + }, + }, + }, + }, + after: { + appState: { + currentPageId: toPageId, + }, + document: { + pages: { + [fromPageId]: fromPage.after, + [toPageId]: toPage.after, + }, + pageStates: { + [fromPageId]: { selectedIds: [] }, + [toPageId]: { + selectedIds: ids, + camera: { + zoom, + point, + }, + }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/move/index.ts b/packages/tldraw/src/state/command/move/index.ts new file mode 100644 index 000000000..3a288b43a --- /dev/null +++ b/packages/tldraw/src/state/command/move/index.ts @@ -0,0 +1 @@ +export * from './move.command' diff --git a/packages/tldraw/src/state/command/move/move.command.spec.ts b/packages/tldraw/src/state/command/move/move.command.spec.ts new file mode 100644 index 000000000..9afff6b97 --- /dev/null +++ b/packages/tldraw/src/state/command/move/move.command.spec.ts @@ -0,0 +1,184 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { Utils } from '@tldraw/core' +import type { Data } from '~types' +import { TLDR } from '~state/tldr' + +const doc = Utils.deepClone(mockDocument) + +doc.pages.page1.shapes['a'] = { + ...doc.pages.page1.shapes['rect1'], + id: 'a', + childIndex: 1, +} +doc.pages.page1.shapes['b'] = { + ...doc.pages.page1.shapes['rect1'], + id: 'b', + childIndex: 2, +} +doc.pages.page1.shapes['c'] = { + ...doc.pages.page1.shapes['rect1'], + id: 'c', + childIndex: 3, +} +doc.pages.page1.shapes['d'] = { + ...doc.pages.page1.shapes['rect1'], + id: 'd', + childIndex: 4, +} +doc.pageStates.page1.selectedIds = ['a'] + +delete doc.pages.page1.shapes['rect1'] +delete doc.pages.page1.shapes['rect2'] +delete doc.pages.page1.shapes['rect3'] + +function getSortedShapeIds(data: Data) { + return TLDR.getShapes(data, data.appState.currentPageId) + .sort((a, b) => a.childIndex - b.childIndex) + .map((shape) => shape.id) + .join('') +} + +describe('Move command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(doc) + tlstate.select('b') + tlstate.moveToBack() + expect(getSortedShapeIds(tlstate.state)).toBe('bacd') + tlstate.undo() + expect(getSortedShapeIds(tlstate.state)).toBe('abcd') + tlstate.redo() + expect(getSortedShapeIds(tlstate.state)).toBe('bacd') + }) + + describe('to back', () => { + it('moves a shape to back', () => { + tlstate.loadDocument(doc) + tlstate.select('b') + tlstate.moveToBack() + expect(getSortedShapeIds(tlstate.state)).toBe('bacd') + }) + + it('moves two adjacent siblings to back', () => { + tlstate.loadDocument(doc) + tlstate.select('b', 'c') + tlstate.moveToBack() + expect(getSortedShapeIds(tlstate.state)).toBe('bcad') + }) + + it('moves two non-adjacent siblings to back', () => { + tlstate.loadDocument(doc) + tlstate.select('b', 'd') + tlstate.moveToBack() + expect(getSortedShapeIds(tlstate.state)).toBe('bdac') + }) + }) + + describe('backward', () => { + it('moves a shape backward', () => { + tlstate.loadDocument(doc) + tlstate.select('c') + tlstate.moveBackward() + expect(getSortedShapeIds(tlstate.state)).toBe('acbd') + }) + + it('moves a shape at first index backward', () => { + tlstate.loadDocument(doc) + tlstate.select('a') + tlstate.moveBackward() + expect(getSortedShapeIds(tlstate.state)).toBe('abcd') + }) + + it('moves two adjacent siblings backward', () => { + tlstate.loadDocument(doc) + tlstate.select('c', 'd') + tlstate.moveBackward() + expect(getSortedShapeIds(tlstate.state)).toBe('acdb') + }) + + it('moves two non-adjacent siblings backward', () => { + tlstate.loadDocument(doc) + tlstate.select('b', 'd') + tlstate.moveBackward() + expect(getSortedShapeIds(tlstate.state)).toBe('badc') + }) + + it('moves two adjacent siblings backward at zero index', () => { + tlstate.loadDocument(doc) + tlstate.select('a', 'b') + tlstate.moveBackward() + expect(getSortedShapeIds(tlstate.state)).toBe('abcd') + }) + }) + + describe('forward', () => { + it('moves a shape forward', () => { + tlstate.loadDocument(doc) + tlstate.select('c') + tlstate.moveForward() + expect(getSortedShapeIds(tlstate.state)).toBe('abdc') + }) + + it('moves a shape forward at the top index', () => { + tlstate.loadDocument(doc) + tlstate.select('b') + tlstate.moveForward() + tlstate.moveForward() + tlstate.moveForward() + expect(getSortedShapeIds(tlstate.state)).toBe('acdb') + }) + + it('moves two adjacent siblings forward', () => { + tlstate.loadDocument(doc) + tlstate.select('a', 'b') + tlstate.moveForward() + expect(getSortedShapeIds(tlstate.state)).toBe('cabd') + }) + + it('moves two non-adjacent siblings forward', () => { + tlstate.loadDocument(doc) + tlstate.select('a', 'c') + tlstate.moveForward() + expect(getSortedShapeIds(tlstate.state)).toBe('badc') + }) + + it('moves two adjacent siblings forward at top index', () => { + tlstate.loadDocument(doc) + tlstate.select('c', 'd') + tlstate.moveForward() + expect(getSortedShapeIds(tlstate.state)).toBe('abcd') + }) + }) + + describe('to front', () => { + it('moves a shape to front', () => { + tlstate.loadDocument(doc) + tlstate.select('b') + tlstate.moveToFront() + expect(getSortedShapeIds(tlstate.state)).toBe('acdb') + }) + + it('moves two adjacent siblings to front', () => { + tlstate.loadDocument(doc) + tlstate.select('a', 'b') + tlstate.moveToFront() + expect(getSortedShapeIds(tlstate.state)).toBe('cdab') + }) + + it('moves two non-adjacent siblings to front', () => { + tlstate.loadDocument(doc) + tlstate.select('a', 'c') + tlstate.moveToFront() + expect(getSortedShapeIds(tlstate.state)).toBe('bdac') + }) + + it('moves siblings already at front to front', () => { + tlstate.loadDocument(doc) + tlstate.select('c', 'd') + tlstate.moveToFront() + expect(getSortedShapeIds(tlstate.state)).toBe('abcd') + }) + }) +}) diff --git a/packages/tldraw/src/state/command/move/move.command.ts b/packages/tldraw/src/state/command/move/move.command.ts new file mode 100644 index 000000000..fa97d6290 --- /dev/null +++ b/packages/tldraw/src/state/command/move/move.command.ts @@ -0,0 +1,223 @@ +import { MoveType, Data, TLDrawShape, TLDrawCommand } from '~types' +import { TLDR } from '~state/tldr' + +export function move(data: Data, ids: string[], type: MoveType): TLDrawCommand { + const { currentPageId } = data.appState + + // Get the unique parent ids for the selected elements + const parentIds = new Set(ids.map((id) => TLDR.getShape(data, id, currentPageId).parentId)) + + let result: { + before: Record> + after: Record> + } = { before: {}, after: {} } + + let startIndex: number + let startChildIndex: number + let step: number + + const page = TLDR.getPage(data, currentPageId) + + // Collect shapes with common parents into a table under their parent id + Array.from(parentIds.values()).forEach((parentId) => { + let sortedChildren: TLDrawShape[] = [] + if (parentId === page.id) { + sortedChildren = Object.values(page.shapes).sort((a, b) => a.childIndex - b.childIndex) + } else { + const parent = TLDR.getShape(data, parentId, currentPageId) + if (!parent.children) throw Error('No children in parent!') + + sortedChildren = parent.children + .map((childId) => TLDR.getShape(data, childId, currentPageId)) + .sort((a, b) => a.childIndex - b.childIndex) + } + + const sortedChildIds = sortedChildren.map((shape) => shape.id) + + const sortedIndicesToMove = ids + .filter((id) => sortedChildIds.includes(id)) + .map((id) => sortedChildIds.indexOf(id)) + .sort((a, b) => a - b) + + if (sortedIndicesToMove.length === sortedChildIds.length) return + + switch (type) { + case MoveType.ToBack: { + // a b c + // Initial 1 2 3 4 5 6 7 + // Final .25 .5 .75 1 3 6 7 + // a b c + + // Find the lowest "open" index + for (let i = 0; i < sortedChildIds.length; i++) { + if (sortedIndicesToMove.includes(i)) continue + startIndex = i + break + } + + // Find the lowest child index that isn't in sortedIndicesToMove + startChildIndex = sortedChildren[startIndex].childIndex + + // Find the step for each additional child + step = startChildIndex / (sortedIndicesToMove.length + 1) + + // Get the results of moving the selected shapes below the first open index's shape + result = TLDR.mutateShapes( + data, + sortedIndicesToMove.map((i) => sortedChildren[i].id).reverse(), + (_shape, i) => ({ + childIndex: startChildIndex - (i + 1) * step, + }), + currentPageId + ) + + break + } + case MoveType.ToFront: { + // a b c + // Initial 1 2 3 4 5 6 7 + // Final 1 3 6 7 8 9 10 + // a b c + + // Find the highest "open" index + for (let i = sortedChildIds.length - 1; i >= 0; i--) { + if (sortedIndicesToMove.includes(i)) continue + startIndex = i + break + } + + // Find the lowest child index that isn't in sortedIndicesToMove + startChildIndex = sortedChildren[startIndex].childIndex + + // Find the step for each additional child + step = 1 + + // Get the results of moving the selected shapes below the first open index's shape + result = TLDR.mutateShapes( + data, + sortedIndicesToMove.map((i) => sortedChildren[i].id), + (_shape, i) => ({ + childIndex: startChildIndex + (i + 1), + }), + currentPageId + ) + + break + } + case MoveType.Backward: { + // a b c + // Initial 1 2 3 4 5 6 7 + // Final .5 1 1.66 2.33 3 6 7 + // a b c + + const indexMap: Record = {} + + // Starting from the top... + for (let i = sortedChildIds.length - 1; i >= 0; i--) { + // If we found a moving index... + if (sortedIndicesToMove.includes(i)) { + for (let j = i; j >= 0; j--) { + // iterate downward until we find an open spot + if (!sortedIndicesToMove.includes(j)) { + // i = the index of the first closed spot + // j = the index of the first open spot + + startChildIndex = + j === 0 ? sortedChildren[j].childIndex / 2 : sortedChildren[j - 1].childIndex + + const step = (sortedChildren[j].childIndex - startChildIndex) / (i - j + 1) + + for (let k = 0; k < i - j; k++) { + indexMap[sortedChildren[j + k + 1].id] = startChildIndex + step * (k + 1) + } + + break + } + } + } + } + + if (Object.values(indexMap).length > 0) { + // Get the results of moving the selected shapes below the first open index's shape + result = TLDR.mutateShapes( + data, + sortedIndicesToMove.map((i) => sortedChildren[i].id), + (shape) => ({ + childIndex: indexMap[shape.id], + }), + currentPageId + ) + } + + break + } + case MoveType.Forward: { + // a b c + // Initial 1 2 3 4 5 6 7 + // Final 1 3 3.5 6 7 8 9 + // a b c + + const indexMap: Record = {} + + // Starting from the top... + for (let i = 0; i < sortedChildIds.length; i++) { + // If we found a moving index... + if (sortedIndicesToMove.includes(i)) { + // Search for the first open spot above this one + for (let j = i; j < sortedChildIds.length; j++) { + if (!sortedIndicesToMove.includes(j)) { + // i = the low index of the first closed spot + // j = the high index of the first open spot + + startChildIndex = sortedChildren[j].childIndex + + const step = + j === sortedChildIds.length - 1 + ? 1 + : (sortedChildren[j + 1].childIndex - startChildIndex) / (j - i + 1) + + for (let k = 0; k < j - i; k++) { + indexMap[sortedChildren[i + k].id] = startChildIndex + step * (k + 1) + } + + break + } + } + } + } + + if (Object.values(indexMap).length > 0) { + // Get the results of moving the selected shapes below the first open index's shape + result = TLDR.mutateShapes( + data, + sortedIndicesToMove.map((i) => sortedChildren[i].id), + (shape) => ({ + childIndex: indexMap[shape.id], + }), + currentPageId + ) + } + + break + } + } + }) + + return { + id: 'move_shapes', + before: { + document: { + pages: { + [data.appState.currentPageId]: { shapes: result.before }, + }, + }, + }, + after: { + document: { + pages: { + [data.appState.currentPageId]: { shapes: result.after }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/rename-page/index.ts b/packages/tldraw/src/state/command/rename-page/index.ts new file mode 100644 index 000000000..950267b07 --- /dev/null +++ b/packages/tldraw/src/state/command/rename-page/index.ts @@ -0,0 +1 @@ +export * from './rename-page.command' diff --git a/packages/tldraw/src/state/command/rename-page/rename-page.command.spec.ts b/packages/tldraw/src/state/command/rename-page/rename-page.command.spec.ts new file mode 100644 index 000000000..ffa84024d --- /dev/null +++ b/packages/tldraw/src/state/command/rename-page/rename-page.command.spec.ts @@ -0,0 +1,25 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' + +describe('Rename page command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + + const initialId = tlstate.page.id + const initialName = tlstate.page.name + + tlstate.renamePage(initialId, 'My Special Page') + + expect(tlstate.page.name).toBe('My Special Page') + + tlstate.undo() + + expect(tlstate.page.name).toBe(initialName) + + tlstate.redo() + + expect(tlstate.page.name).toBe('My Special Page') + }) +}) diff --git a/packages/tldraw/src/state/command/rename-page/rename-page.command.ts b/packages/tldraw/src/state/command/rename-page/rename-page.command.ts new file mode 100644 index 000000000..a694bd8eb --- /dev/null +++ b/packages/tldraw/src/state/command/rename-page/rename-page.command.ts @@ -0,0 +1,22 @@ +import type { Data, TLDrawCommand } from '~types' + +export function renamePage(data: Data, pageId: string, name: string): TLDrawCommand { + const page = data.document.pages[pageId] + return { + id: 'rename_page', + before: { + document: { + pages: { + [pageId]: { name: page.name }, + }, + }, + }, + after: { + document: { + pages: { + [pageId]: { name: name }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/rotate/index.ts b/packages/tldraw/src/state/command/rotate/index.ts new file mode 100644 index 000000000..3c348e7b0 --- /dev/null +++ b/packages/tldraw/src/state/command/rotate/index.ts @@ -0,0 +1 @@ +export * from './rotate.command' diff --git a/packages/tldraw/src/state/command/rotate/rotate.command.spec.ts b/packages/tldraw/src/state/command/rotate/rotate.command.spec.ts new file mode 100644 index 000000000..911cabd87 --- /dev/null +++ b/packages/tldraw/src/state/command/rotate/rotate.command.spec.ts @@ -0,0 +1,24 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' + +describe('Rotate command', () => { + const tlstate = new TLDrawState() + tlstate.loadDocument(mockDocument) + tlstate.select('rect1') + + it('does, undoes and redoes command', () => { + expect(tlstate.getShape('rect1').rotation).toBe(undefined) + + tlstate.rotate() + + expect(tlstate.getShape('rect1').rotation).toBe(Math.PI * (6 / 4)) + + tlstate.undo() + + expect(tlstate.getShape('rect1').rotation).toBe(undefined) + + tlstate.redo() + + expect(tlstate.getShape('rect1').rotation).toBe(Math.PI * (6 / 4)) + }) +}) diff --git a/packages/tldraw/src/state/command/rotate/rotate.command.ts b/packages/tldraw/src/state/command/rotate/rotate.command.ts new file mode 100644 index 000000000..15318b76b --- /dev/null +++ b/packages/tldraw/src/state/command/rotate/rotate.command.ts @@ -0,0 +1,69 @@ +import { Utils, Vec } from '@tldraw/core' +import type { TLDrawCommand, Data } from '~types' +import { TLDR } from '~state/tldr' + +const PI2 = Math.PI * 2 + +export function rotate(data: Data, ids: string[], delta = -PI2 / 4): TLDrawCommand { + const { currentPageId } = data.appState + const initialShapes = ids.map((id) => TLDR.getShape(data, id, currentPageId)) + + const boundsForShapes = initialShapes.map((shape) => { + const utils = TLDR.getShapeUtils(shape) + return { + id: shape.id, + point: [...shape.point], + bounds: utils.getBounds(shape), + center: utils.getCenter(shape), + rotation: shape.rotation, + } + }) + + const commonBounds = Utils.getCommonBounds(boundsForShapes.map(({ bounds }) => bounds)) + const commonBoundsCenter = Utils.getBoundsCenter(commonBounds) + + const rotations = Object.fromEntries( + boundsForShapes.map(({ id, point, center, rotation }) => { + const offset = Vec.sub(center, point) + const nextPoint = Vec.sub(Vec.rotWith(center, commonBoundsCenter, -(PI2 / 4)), offset) + const nextRotation = (PI2 + ((rotation || 0) + delta)) % PI2 + + return [id, { point: nextPoint, rotation: nextRotation }] + }) + ) + + const pageState = TLDR.getPageState(data, currentPageId) + const prevBoundsRotation = pageState.boundsRotation + const nextBoundsRotation = (PI2 + ((pageState.boundsRotation || 0) + delta)) % PI2 + + const { before, after } = TLDR.mutateShapes( + data, + ids, + (shape) => rotations[shape.id], + currentPageId + ) + + return { + id: 'toggle_shapes', + before: { + document: { + pages: { + [currentPageId]: { shapes: before }, + }, + pageStates: { + [currentPageId]: { boundsRotation: prevBoundsRotation }, + }, + }, + }, + after: { + document: { + pages: { + [currentPageId]: { shapes: after }, + }, + pageStates: { + [currentPageId]: { boundsRotation: nextBoundsRotation }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/stretch/index.ts b/packages/tldraw/src/state/command/stretch/index.ts new file mode 100644 index 000000000..5dd282e9e --- /dev/null +++ b/packages/tldraw/src/state/command/stretch/index.ts @@ -0,0 +1 @@ +export * from './stretch.command' diff --git a/packages/tldraw/src/state/command/stretch/stretch.command.spec.ts b/packages/tldraw/src/state/command/stretch/stretch.command.spec.ts new file mode 100644 index 000000000..899b58a19 --- /dev/null +++ b/packages/tldraw/src/state/command/stretch/stretch.command.spec.ts @@ -0,0 +1,54 @@ +import { StretchType, RectangleShape } from '~types' +import { TLDrawState } from '~state' +import { mockDocument } from '~test' + +describe('Stretch command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + tlstate.select('rect1', 'rect2') + tlstate.stretch(StretchType.Horizontal) + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + expect(tlstate.getShape('rect1').size).toStrictEqual([200, 100]) + expect(tlstate.getShape('rect2').point).toStrictEqual([0, 100]) + expect(tlstate.getShape('rect2').size).toStrictEqual([200, 100]) + + tlstate.undo() + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + expect(tlstate.getShape('rect1').size).toStrictEqual([100, 100]) + expect(tlstate.getShape('rect2').point).toStrictEqual([100, 100]) + expect(tlstate.getShape('rect2').size).toStrictEqual([100, 100]) + + tlstate.redo() + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + expect(tlstate.getShape('rect1').size).toStrictEqual([200, 100]) + expect(tlstate.getShape('rect2').point).toStrictEqual([0, 100]) + expect(tlstate.getShape('rect2').size).toStrictEqual([200, 100]) + }) + + it('stretches horizontally', () => { + tlstate.loadDocument(mockDocument) + tlstate.select('rect1', 'rect2') + tlstate.stretch(StretchType.Horizontal) + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + expect(tlstate.getShape('rect1').size).toStrictEqual([200, 100]) + expect(tlstate.getShape('rect2').point).toStrictEqual([0, 100]) + expect(tlstate.getShape('rect2').size).toStrictEqual([200, 100]) + }) + + it('stretches vertically', () => { + tlstate.loadDocument(mockDocument) + tlstate.select('rect1', 'rect2') + tlstate.stretch(StretchType.Vertical) + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + expect(tlstate.getShape('rect1').size).toStrictEqual([100, 200]) + expect(tlstate.getShape('rect2').point).toStrictEqual([100, 0]) + expect(tlstate.getShape('rect2').size).toStrictEqual([100, 200]) + }) +}) diff --git a/packages/tldraw/src/state/command/stretch/stretch.command.ts b/packages/tldraw/src/state/command/stretch/stretch.command.ts new file mode 100644 index 000000000..755a41785 --- /dev/null +++ b/packages/tldraw/src/state/command/stretch/stretch.command.ts @@ -0,0 +1,76 @@ +import { TLBoundsCorner, Utils } from '@tldraw/core' +import { StretchType } from '~types' +import type { Data, TLDrawCommand } from '~types' +import { TLDR } from '~state/tldr' + +export function stretch(data: Data, ids: string[], type: StretchType): TLDrawCommand { + const { currentPageId } = data.appState + + const initialShapes = ids.map((id) => TLDR.getShape(data, id, currentPageId)) + + const boundsForShapes = initialShapes.map((shape) => TLDR.getBounds(shape)) + + const commonBounds = Utils.getCommonBounds(boundsForShapes) + + const { before, after } = TLDR.mutateShapes( + data, + ids, + (shape) => { + const bounds = TLDR.getBounds(shape) + + switch (type) { + case StretchType.Horizontal: { + const newBounds = { + ...bounds, + minX: commonBounds.minX, + maxX: commonBounds.maxX, + width: commonBounds.width, + } + + return TLDR.getShapeUtils(shape).transformSingle(shape, newBounds, { + type: TLBoundsCorner.TopLeft, + scaleX: newBounds.width / bounds.width, + scaleY: 1, + initialShape: shape, + transformOrigin: [0.5, 0.5], + }) + } + case StretchType.Vertical: { + const newBounds = { + ...bounds, + minY: commonBounds.minY, + maxY: commonBounds.maxY, + height: commonBounds.height, + } + + return TLDR.getShapeUtils(shape).transformSingle(shape, newBounds, { + type: TLBoundsCorner.TopLeft, + scaleX: 1, + scaleY: newBounds.height / bounds.height, + initialShape: shape, + transformOrigin: [0.5, 0.5], + }) + } + } + }, + currentPageId + ) + + return { + id: 'stretch_shapes', + before: { + document: { + pages: { + [currentPageId]: { shapes: before }, + }, + }, + }, + after: { + document: { + pages: { + [currentPageId]: { shapes: after }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/style/index.ts b/packages/tldraw/src/state/command/style/index.ts new file mode 100644 index 000000000..d6904ca34 --- /dev/null +++ b/packages/tldraw/src/state/command/style/index.ts @@ -0,0 +1 @@ +export * from './style.command' diff --git a/packages/tldraw/src/state/command/style/style.command.spec.ts b/packages/tldraw/src/state/command/style/style.command.spec.ts new file mode 100644 index 000000000..c622f6c79 --- /dev/null +++ b/packages/tldraw/src/state/command/style/style.command.spec.ts @@ -0,0 +1,49 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { SizeStyle } from '~types' + +describe('Style command', () => { + const tlstate = new TLDrawState() + tlstate.loadDocument(mockDocument) + tlstate.select('rect1') + + it('does, undoes and redoes command', () => { + expect(tlstate.getShape('rect1').style.size).toEqual(SizeStyle.Medium) + + tlstate.style({ size: SizeStyle.Small }) + + expect(tlstate.getShape('rect1').style.size).toEqual(SizeStyle.Small) + + tlstate.undo() + + expect(tlstate.getShape('rect1').style.size).toEqual(SizeStyle.Medium) + + tlstate.redo() + + expect(tlstate.getShape('rect1').style.size).toEqual(SizeStyle.Small) + }) + + describe('When styling groups', () => { + it('applies style to all group children', () => { + const tlstate = new TLDrawState() + tlstate + .loadDocument(mockDocument) + .group(['rect1', 'rect2'], 'groupA') + .select('groupA') + .style({ size: SizeStyle.Small }) + + expect(tlstate.getShape('rect1').style.size).toEqual(SizeStyle.Small) + expect(tlstate.getShape('rect2').style.size).toEqual(SizeStyle.Small) + + tlstate.undo() + + expect(tlstate.getShape('rect1').style.size).toEqual(SizeStyle.Medium) + expect(tlstate.getShape('rect2').style.size).toEqual(SizeStyle.Medium) + + tlstate.redo() + + expect(tlstate.getShape('rect1').style.size).toEqual(SizeStyle.Small) + expect(tlstate.getShape('rect2').style.size).toEqual(SizeStyle.Small) + }) + }) +}) diff --git a/packages/tldraw/src/state/command/style/style.command.ts b/packages/tldraw/src/state/command/style/style.command.ts new file mode 100644 index 000000000..36bb23ed0 --- /dev/null +++ b/packages/tldraw/src/state/command/style/style.command.ts @@ -0,0 +1,43 @@ +import type { ShapeStyles, TLDrawCommand, Data } from '~types' +import { TLDR } from '~state/tldr' + +export function style(data: Data, ids: string[], changes: Partial): TLDrawCommand { + const { currentPageId } = data.appState + + const shapeIdsToMutate = ids.flatMap((id) => TLDR.getDocumentBranch(data, id, currentPageId)) + + const { before, after } = TLDR.mutateShapes( + data, + shapeIdsToMutate, + (shape) => ({ style: { ...shape.style, ...changes } }), + currentPageId + ) + + return { + id: 'style_shapes', + before: { + document: { + pages: { + [currentPageId]: { + shapes: before, + }, + }, + }, + appState: { + currentStyle: { ...data.appState.currentStyle }, + }, + }, + after: { + document: { + pages: { + [currentPageId]: { + shapes: after, + }, + }, + }, + appState: { + currentStyle: { ...data.appState.currentStyle, ...changes }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/toggle-decoration/index.ts b/packages/tldraw/src/state/command/toggle-decoration/index.ts new file mode 100644 index 000000000..42d32c22e --- /dev/null +++ b/packages/tldraw/src/state/command/toggle-decoration/index.ts @@ -0,0 +1 @@ +export * from './toggle-decoration.command' diff --git a/packages/tldraw/src/state/command/toggle-decoration/toggle-decoration.command.spec.ts b/packages/tldraw/src/state/command/toggle-decoration/toggle-decoration.command.spec.ts new file mode 100644 index 000000000..0f2301595 --- /dev/null +++ b/packages/tldraw/src/state/command/toggle-decoration/toggle-decoration.command.spec.ts @@ -0,0 +1,34 @@ +import { TLDR } from '~state/tldr' +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { ArrowShape, Decoration, TLDrawShape } from '~types' + +describe('Toggle decoration command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate + .loadDocument(mockDocument) + .create( + TLDR.getShapeUtils({ type: 'arrow' } as TLDrawShape).create({ + id: 'arrow1', + parentId: 'page1', + }) + ) + .select('arrow1') + + expect(tlstate.getShape('arrow1').decorations?.end).toBe(Decoration.Arrow) + + tlstate.toggleDecoration('end') + + expect(tlstate.getShape('arrow1').decorations?.end).toBe(undefined) + + tlstate.undo() + + expect(tlstate.getShape('arrow1').decorations?.end).toBe(Decoration.Arrow) + + tlstate.redo() + + expect(tlstate.getShape('arrow1').decorations?.end).toBe(undefined) + }) +}) diff --git a/packages/tldraw/src/state/command/toggle-decoration/toggle-decoration.command.ts b/packages/tldraw/src/state/command/toggle-decoration/toggle-decoration.command.ts new file mode 100644 index 000000000..370513fa7 --- /dev/null +++ b/packages/tldraw/src/state/command/toggle-decoration/toggle-decoration.command.ts @@ -0,0 +1,48 @@ +import { Decoration } from '~types' +import type { ArrowShape, TLDrawCommand, Data } from '~types' +import { TLDR } from '~state/tldr' + +export function toggleDecoration( + data: Data, + ids: string[], + handleId: 'start' | 'end' +): TLDrawCommand { + const { currentPageId } = data.appState + const { before, after } = TLDR.mutateShapes( + data, + ids, + (shape) => { + const decorations = shape.decorations + ? { + ...shape.decorations, + [handleId]: shape.decorations[handleId] ? undefined : Decoration.Arrow, + } + : { + [handleId]: Decoration.Arrow, + } + + return { + decorations, + } + }, + currentPageId + ) + + return { + id: 'toggle_decorations', + before: { + document: { + pages: { + [currentPageId]: { shapes: before }, + }, + }, + }, + after: { + document: { + pages: { + [currentPageId]: { shapes: after }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/toggle/index.ts b/packages/tldraw/src/state/command/toggle/index.ts new file mode 100644 index 000000000..e2901ec38 --- /dev/null +++ b/packages/tldraw/src/state/command/toggle/index.ts @@ -0,0 +1 @@ +export * from './toggle.command' diff --git a/packages/tldraw/src/state/command/toggle/toggle.command.spec.ts b/packages/tldraw/src/state/command/toggle/toggle.command.spec.ts new file mode 100644 index 000000000..c545bbd84 --- /dev/null +++ b/packages/tldraw/src/state/command/toggle/toggle.command.spec.ts @@ -0,0 +1,43 @@ +import type { RectangleShape } from '~types' +import { TLDrawState } from '~state' +import { mockDocument } from '~test' + +describe('Toggle command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + + expect(tlstate.getShape('rect2').isAspectRatioLocked).toBe(undefined) + + tlstate.toggleAspectRatioLocked() + + expect(tlstate.getShape('rect2').isAspectRatioLocked).toBe(true) + + tlstate.undo() + + expect(tlstate.getShape('rect2').isAspectRatioLocked).toBe(undefined) + + tlstate.redo() + + expect(tlstate.getShape('rect2').isAspectRatioLocked).toBe(true) + }) + + it('toggles on before off when mixed values', () => { + tlstate.loadDocument(mockDocument) + tlstate.select('rect2') + expect(tlstate.getShape('rect1').isAspectRatioLocked).toBe(undefined) + expect(tlstate.getShape('rect2').isAspectRatioLocked).toBe(undefined) + tlstate.toggleAspectRatioLocked() + expect(tlstate.getShape('rect1').isAspectRatioLocked).toBe(undefined) + expect(tlstate.getShape('rect2').isAspectRatioLocked).toBe(true) + tlstate.selectAll() + tlstate.toggleAspectRatioLocked() + expect(tlstate.getShape('rect1').isAspectRatioLocked).toBe(true) + expect(tlstate.getShape('rect1').isAspectRatioLocked).toBe(true) + tlstate.toggleAspectRatioLocked() + expect(tlstate.getShape('rect1').isAspectRatioLocked).toBe(false) + expect(tlstate.getShape('rect1').isAspectRatioLocked).toBe(false) + }) +}) diff --git a/packages/tldraw/src/state/command/toggle/toggle.command.ts b/packages/tldraw/src/state/command/toggle/toggle.command.ts new file mode 100644 index 000000000..980312117 --- /dev/null +++ b/packages/tldraw/src/state/command/toggle/toggle.command.ts @@ -0,0 +1,39 @@ +import type { TLDrawShape, Data, TLDrawCommand } from '~types' +import { TLDR } from '~state/tldr' + +export function toggle(data: Data, ids: string[], prop: keyof TLDrawShape): TLDrawCommand { + const { currentPageId } = data.appState + const initialShapes = ids.map((id) => TLDR.getShape(data, id, currentPageId)) + const isAllToggled = initialShapes.every((shape) => shape[prop]) + + const { before, after } = TLDR.mutateShapes( + data, + TLDR.getSelectedIds(data, currentPageId), + () => ({ + [prop]: !isAllToggled, + }), + currentPageId + ) + + return { + id: 'toggle_shapes', + before: { + document: { + pages: { + [currentPageId]: { + shapes: before, + }, + }, + }, + }, + after: { + document: { + pages: { + [currentPageId]: { + shapes: after, + }, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/translate/index.ts b/packages/tldraw/src/state/command/translate/index.ts new file mode 100644 index 000000000..04a2748d6 --- /dev/null +++ b/packages/tldraw/src/state/command/translate/index.ts @@ -0,0 +1 @@ +export * from './translate.command' diff --git a/packages/tldraw/src/state/command/translate/translate.command.spec.ts b/packages/tldraw/src/state/command/translate/translate.command.spec.ts new file mode 100644 index 000000000..4cac8f46d --- /dev/null +++ b/packages/tldraw/src/state/command/translate/translate.command.spec.ts @@ -0,0 +1,111 @@ +/* eslint-disable @typescript-eslint/no-non-null-assertion */ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { ArrowShape, TLDrawShapeType } from '~types' + +describe('Translate command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + tlstate.nudge([1, 2]) + + expect(tlstate.getShape('rect2').point).toEqual([101, 102]) + + tlstate.undo() + + expect(tlstate.getShape('rect2').point).toEqual([100, 100]) + + tlstate.redo() + + expect(tlstate.getShape('rect2').point).toEqual([101, 102]) + }) + + it('major nudges', () => { + tlstate.loadDocument(mockDocument) + tlstate.selectAll() + tlstate.nudge([1, 2], true) + expect(tlstate.getShape('rect2').point).toEqual([110, 120]) + }) + + describe('when nudging shapes with bindings', () => { + it('deleted bindings if nudging shape is bound to other shapes', () => { + tlstate + .resetDocument() + .createShapes( + { + id: 'target1', + type: TLDrawShapeType.Rectangle, + point: [0, 0], + size: [100, 100], + }, + { + type: TLDrawShapeType.Arrow, + id: 'arrow1', + point: [200, 200], + } + ) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([50, 50]) + .completeSession() + + const bindingId = tlstate.getShape('arrow1').handles.start.bindingId! + + tlstate.select('arrow1').nudge([10, 10]) + + expect(tlstate.getBinding(bindingId)).toBeUndefined() + expect(tlstate.getShape('arrow1').handles.start.bindingId).toBeUndefined() + + tlstate.undo() + + expect(tlstate.getBinding(bindingId)).toBeDefined() + expect(tlstate.getShape('arrow1').handles.start.bindingId).toBe(bindingId) + + tlstate.redo() + + expect(tlstate.getBinding(bindingId)).toBeUndefined() + expect(tlstate.getShape('arrow1').handles.start.bindingId).toBeUndefined() + }) + + it('does not delete bindings if both bound and bound-to shapes are nudged', () => { + tlstate + .resetDocument() + .createShapes( + { + id: 'target1', + type: TLDrawShapeType.Rectangle, + point: [0, 0], + size: [100, 100], + }, + { + type: TLDrawShapeType.Arrow, + id: 'arrow1', + point: [200, 200], + } + ) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([50, 50]) + .completeSession() + + const bindingId = tlstate.getShape('arrow1').handles.start.bindingId! + + tlstate.select('arrow1', 'target1').nudge([10, 10]) + + expect(tlstate.getBinding(bindingId)).toBeDefined() + expect(tlstate.getShape('arrow1').handles.start.bindingId).toBe(bindingId) + + tlstate.undo() + + expect(tlstate.getBinding(bindingId)).toBeDefined() + expect(tlstate.getShape('arrow1').handles.start.bindingId).toBe(bindingId) + + tlstate.redo() + + expect(tlstate.getBinding(bindingId)).toBeDefined() + expect(tlstate.getShape('arrow1').handles.start.bindingId).toBe(bindingId) + }) + }) +}) diff --git a/packages/tldraw/src/state/command/translate/translate.command.ts b/packages/tldraw/src/state/command/translate/translate.command.ts new file mode 100644 index 000000000..5d58cb831 --- /dev/null +++ b/packages/tldraw/src/state/command/translate/translate.command.ts @@ -0,0 +1,82 @@ +import { Vec } from '@tldraw/core' +import type { Data, TLDrawCommand, PagePartial } from '~types' +import { TLDR } from '~state/tldr' + +export function translate(data: Data, ids: string[], delta: number[]): TLDrawCommand { + const { currentPageId } = data.appState + + const before: PagePartial = { + shapes: {}, + bindings: {}, + } + + const after: PagePartial = { + shapes: {}, + bindings: {}, + } + + const change = TLDR.mutateShapes( + data, + ids, + (shape) => ({ + point: Vec.round(Vec.add(shape.point, delta)), + }), + currentPageId + ) + + before.shapes = change.before + after.shapes = change.after + + // Delete bindings from nudged shapes, unless both bound and bound-to shapes are selected + const bindingsToDelete = TLDR.getBindings(data, currentPageId).filter( + (binding) => ids.includes(binding.fromId) && !ids.includes(binding.toId) + ) + + bindingsToDelete.forEach((binding) => { + before.bindings[binding.id] = binding + after.bindings[binding.id] = undefined + + for (const id of [binding.toId, binding.fromId]) { + // Let's also look at the bound shape... + const shape = TLDR.getShape(data, id, data.appState.currentPageId) + + if (!shape.handles) continue + + // If the bound shape has a handle that references the deleted binding, delete that reference + + Object.values(shape.handles) + .filter((handle) => handle.bindingId === binding.id) + .forEach((handle) => { + before.shapes[id] = { + ...before.shapes[id], + handles: { + ...before.shapes[id]?.handles, + [handle.id]: { bindingId: binding.id }, + }, + } + after.shapes[id] = { + ...after.shapes[id], + handles: { ...after.shapes[id]?.handles, [handle.id]: { bindingId: undefined } }, + } + }) + } + }) + + return { + id: 'translate_shapes', + before: { + document: { + pages: { + [data.appState.currentPageId]: before, + }, + }, + }, + after: { + document: { + pages: { + [data.appState.currentPageId]: after, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/update/index.ts b/packages/tldraw/src/state/command/update/index.ts new file mode 100644 index 000000000..cc22385b2 --- /dev/null +++ b/packages/tldraw/src/state/command/update/index.ts @@ -0,0 +1 @@ +export * from './update.command' diff --git a/packages/tldraw/src/state/command/update/update.command.spec.ts b/packages/tldraw/src/state/command/update/update.command.spec.ts new file mode 100644 index 000000000..3a8efb687 --- /dev/null +++ b/packages/tldraw/src/state/command/update/update.command.spec.ts @@ -0,0 +1,19 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { Utils } from '@tldraw/core' + +const doc = Utils.deepClone(mockDocument) + +describe('Update command', () => { + const tlstate = new TLDrawState() + + it('does, undoes and redoes command', () => { + tlstate.loadDocument(doc) + tlstate.updateShapes({ id: 'rect1', point: [100, 100] }) + expect(tlstate.getShape('rect1').point).toStrictEqual([100, 100]) + tlstate.undo() + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + tlstate.redo() + expect(tlstate.getShape('rect1').point).toStrictEqual([100, 100]) + }) +}) diff --git a/packages/tldraw/src/state/command/update/update.command.ts b/packages/tldraw/src/state/command/update/update.command.ts new file mode 100644 index 000000000..4e2b43cda --- /dev/null +++ b/packages/tldraw/src/state/command/update/update.command.ts @@ -0,0 +1,47 @@ +import type { Data, TLDrawCommand, PagePartial, TLDrawShape } from '~types' +import { TLDR } from '~state/tldr' + +export function update( + data: Data, + updates: ({ id: string } & Partial)[] +): TLDrawCommand { + const ids = updates.map((update) => update.id) + + const before: PagePartial = { + shapes: {}, + bindings: {}, + } + + const after: PagePartial = { + shapes: {}, + bindings: {}, + } + + const change = TLDR.mutateShapes( + data, + ids, + (_shape, i) => updates[i], + data.appState.currentPageId + ) + + before.shapes = change.before + after.shapes = change.after + + return { + id: 'translate_shapes', + before: { + document: { + pages: { + [data.appState.currentPageId]: before, + }, + }, + }, + after: { + document: { + pages: { + [data.appState.currentPageId]: after, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/command/utils/removeShapesFromPage.ts b/packages/tldraw/src/state/command/utils/removeShapesFromPage.ts new file mode 100644 index 000000000..11eda540d --- /dev/null +++ b/packages/tldraw/src/state/command/utils/removeShapesFromPage.ts @@ -0,0 +1,95 @@ +import { TLDR } from '~state/tldr' +import type { Data, GroupShape, PagePartial } from '~types' + +export function removeShapesFromPage(data: Data, ids: string[], pageId: string) { + const before: PagePartial = { + shapes: {}, + bindings: {}, + } + + const after: PagePartial = { + shapes: {}, + bindings: {}, + } + + const parentsToUpdate: GroupShape[] = [] + + const deletedIds = new Set() + + // These are the shapes we're definitely going to delete + + ids.forEach((id) => { + deletedIds.add(id) + const shape = TLDR.getShape(data, id, pageId) + before.shapes[id] = shape + after.shapes[id] = undefined + + // Also delete the shape's children + + if (shape.children !== undefined) { + shape.children.forEach((childId) => { + deletedIds.add(childId) + const child = TLDR.getShape(data, childId, pageId) + before.shapes[childId] = child + after.shapes[childId] = undefined + }) + } + + if (shape.parentId !== pageId) { + parentsToUpdate.push(TLDR.getShape(data, shape.parentId, pageId)) + } + }) + + parentsToUpdate.forEach((parent) => { + if (ids.includes(parent.id)) return + deletedIds.add(parent.id) + before.shapes[parent.id] = { children: parent.children } + after.shapes[parent.id] = { children: parent.children.filter((id) => !ids.includes(id)) } + }) + + // Recursively check for empty parents? + + const page = TLDR.getPage(data, pageId) + + // We also need to delete bindings that reference the deleted shapes + Object.values(page.bindings).forEach((binding) => { + for (const id of [binding.toId, binding.fromId]) { + // If the binding references a deleted shape... + if (after.shapes[id] === undefined) { + // Delete this binding + before.bindings[binding.id] = binding + after.bindings[binding.id] = undefined + + // Let's also look each the bound shape... + const shape = TLDR.getShape(data, id, pageId) + + // If the bound shape has a handle that references the deleted binding... + if (shape.handles) { + Object.values(shape.handles) + .filter((handle) => handle.bindingId === binding.id) + .forEach((handle) => { + // Save the binding reference in the before patch + before.shapes[id] = { + ...before.shapes[id], + handles: { + ...before.shapes[id]?.handles, + [handle.id]: { bindingId: binding.id }, + }, + } + + // Unless we're currently deleting the shape, remove the + // binding reference from the after patch + if (!deletedIds.has(id)) { + after.shapes[id] = { + ...after.shapes[id], + handles: { ...after.shapes[id]?.handles, [handle.id]: { bindingId: undefined } }, + } + } + }) + } + } + } + }) + + return { before, after } +} diff --git a/packages/tldraw/src/state/index.ts b/packages/tldraw/src/state/index.ts new file mode 100644 index 000000000..45d3420c7 --- /dev/null +++ b/packages/tldraw/src/state/index.ts @@ -0,0 +1 @@ +export * from './tlstate' diff --git a/packages/tldraw/src/state/notes.md b/packages/tldraw/src/state/notes.md new file mode 100644 index 000000000..fbc30612c --- /dev/null +++ b/packages/tldraw/src/state/notes.md @@ -0,0 +1,45 @@ +# Notes + +- [x] Remap style panel +- [x] Remap zoom panel +- [x] Remap undo / redo panel +- [x] Remap tool panel +- [x] Migrate commands +- [x] Migrate sessions + +## History + +The app's history is an array of [Command](#command) objects, together with a pointer indicating the current position in the stack. If the pointer is above the lowest (zeroth) position, a user may _undo_ to move the pointer down. If the pointer is below the highest position, a user may _redo_ to move the pointer up. When the pointer changes to a new position, it will either _redo_ the command at that position if moving up or _undo_ the command at its previous position if moving down. + +## Commands + +Commands are entries in the app's [History](#history) stack. have two methods: `do` and `undo`. Each method should return a `Partial`. + +The `do` method is called under two circumstances: first, when executing a command for the first time; and second, when executing a "redo". The method receives a boolean (`isRedo`) as its second argument indiciating whether it is being called as a "do" or a "redo". + +## Sessions + +Sessions have two methods: `start`, `update`, `cancel` and `complete`. The `start`, `update`, and `cancel` methods should return a `Partial`. The `complete` method should return a [Command](#commands). + +## Mutations + +When we mutate shapes inside of a command, we: + +- Gather a unique set of all shapes that _will_ be mutated: the initial shapes directly effected by the change, plus their descendants (if any), plus their parents (if any), plus other shapes that are "bound to" the shapes / parents. Repeat this check until an iteration returns the same size set as the previous iteration, indicating that we've found all shapes effected by the mutation. +- Serialize a snapshot of the mutation. This data will be used to perform the "undo". +- Using a reducer that returns the `Data` object, iterate through the initial shapes, mutating first the shape, then its bindings, and then the shape's parents beginning with the direct parent and moving upward toward the root (a page). If _n_ shapes share the same parent, then the parent will be updated _n_ times. If the initial set of shapes includes _n_ shapes that are bound to eachother, then the binding will be updated _n_ times. +- Finally, serialize a snapshot of all effected shapes. This data will be used to perform the "redo". +- Return both the "undo" and "redo" data. This should be saved to the history stack. It can also be saved to storage as part of the document. +- When the history "does" the command, merge the "redo" data into the current `Data`. +- When the history "undoes" the command, merge the "undo" data into the current `Data`. +- When the history "redoes" the command, merge the "redo" data into the current `Data`. + +## onChange Events + +When something changes in the state, we need to produce an onChange event that is compatible with multiplayer implementations. This still requires some research, however at minimum we want to include: + +- The current user's id +- The current document id +- The event patch (what's changed) + +The first step would be to implement onChange events for commands. These are already set up as patches and always produce a history entry. diff --git a/packages/tldraw/src/state/session/index.ts b/packages/tldraw/src/state/session/index.ts new file mode 100644 index 000000000..c84341f27 --- /dev/null +++ b/packages/tldraw/src/state/session/index.ts @@ -0,0 +1 @@ +export * from './sessions' diff --git a/packages/tldraw/src/state/session/sessions/arrow/arrow.session.spec.ts b/packages/tldraw/src/state/session/sessions/arrow/arrow.session.spec.ts new file mode 100644 index 000000000..7cbc4a618 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/arrow/arrow.session.spec.ts @@ -0,0 +1,154 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { ArrowShape, TLDrawShapeType, TLDrawStatus } from '~types' + +describe('Arrow session', () => { + const tlstate = new TLDrawState() + tlstate + .loadDocument(mockDocument) + .selectAll() + .delete() + .createShapes( + { type: TLDrawShapeType.Rectangle, id: 'target1', point: [0, 0], size: [100, 100] }, + { type: TLDrawShapeType.Arrow, id: 'arrow1', point: [200, 200] } + ) + + const restoreDoc = tlstate.document + + it('begins, updates and completes session', () => { + tlstate + .loadDocument(restoreDoc) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([50, 50]) + .completeSession() + + const binding = tlstate.bindings[0] + + expect(binding).toBeTruthy() + expect(binding.fromId).toBe('arrow1') + expect(binding.toId).toBe('target1') + expect(binding.handleId).toBe('start') + expect(tlstate.appState.status.current).toBe(TLDrawStatus.Idle) + expect(tlstate.getShape('arrow1').handles?.start.bindingId).toBe(binding.id) + + tlstate.undo() + + expect(tlstate.bindings[0]).toBe(undefined) + expect(tlstate.getShape('arrow1').handles?.start.bindingId).toBe(undefined) + + tlstate.redo() + + expect(tlstate.bindings[0]).toBeTruthy() + expect(tlstate.getShape('arrow1').handles?.start.bindingId).toBe(binding.id) + }) + + it('cancels session', () => { + tlstate + .loadDocument(restoreDoc) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([50, 50]) + .cancelSession() + + expect(tlstate.bindings[0]).toBe(undefined) + expect(tlstate.getShape('arrow1').handles?.start.bindingId).toBe(undefined) + }) + + describe('arrow binding', () => { + it('points to the center', () => { + tlstate + .loadDocument(restoreDoc) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([50, 50]) + expect(tlstate.bindings[0].point).toStrictEqual([0.5, 0.5]) + }) + + it('Snaps to the center', () => { + tlstate + .loadDocument(restoreDoc) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([55, 55]) + expect(tlstate.bindings[0].point).toStrictEqual([0.5, 0.5]) + }) + + it('Binds at the bottom left', () => { + tlstate + .loadDocument(restoreDoc) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([132, -32]) + expect(tlstate.bindings[0].point).toStrictEqual([1, 0]) + }) + + it('Cancels the bind when off of the expanded bounds', () => { + tlstate + .loadDocument(restoreDoc) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([133, 133]) + + expect(tlstate.bindings[0]).toBe(undefined) + }) + + it('binds on the inside of a shape while meta is held', () => { + tlstate + .loadDocument(restoreDoc) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([91, 9]) + + expect(tlstate.bindings[0].point).toStrictEqual([0.67839, 0.125]) + + tlstate.updateHandleSession([91, 9], false, false, true) + }) + + it('snaps to the center when the point is close to the center', () => { + tlstate + .loadDocument(restoreDoc) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([91, 9]) + + expect(tlstate.bindings[0].point).toStrictEqual([0.67839, 0.125]) + + tlstate.updateHandleSession([91, 9], false, false, true) + + expect(tlstate.bindings[0].point).toStrictEqual([0.75, 0.25]) + }) + + it('ignores binding when alt is held', () => { + tlstate + .loadDocument(restoreDoc) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([55, 45]) + + expect(tlstate.bindings[0].point).toStrictEqual([0.5, 0.5]) + + tlstate.updateHandleSession([55, 45], false, false, true) + + expect(tlstate.bindings[0].point).toStrictEqual([0.5, 0.5]) + }) + }) + + describe('when dragging a bound shape', () => { + it('updates the arrow', () => { + tlstate.loadDocument(restoreDoc) + // Select the arrow and begin a session on the handle's start handle + tlstate.select('arrow1').startHandleSession([200, 200], 'start') + // Move to [50,50] + tlstate.updateHandleSession([50, 50]).completeSession() + // Both handles will keep the same screen positions, but their points will have changed. + expect(tlstate.getShape('arrow1').point).toStrictEqual([116, 116]) + expect(tlstate.getShape('arrow1').handles.start.point).toStrictEqual([0, 0]) + expect(tlstate.getShape('arrow1').handles.end.point).toStrictEqual([85, 85]) + }) + + it.todo('updates the arrow when bound on both sides') + + it.todo('snaps the bend to zero when dragging the bend handle toward the center') + }) +}) diff --git a/packages/tldraw/src/state/session/sessions/arrow/arrow.session.ts b/packages/tldraw/src/state/session/sessions/arrow/arrow.session.ts new file mode 100644 index 000000000..278f4321e --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/arrow/arrow.session.ts @@ -0,0 +1,319 @@ +import { + ArrowBinding, + ArrowShape, + TLDrawShape, + TLDrawBinding, + Data, + Session, + TLDrawStatus, +} from '~types' +import { Vec, Utils, TLHandle } from '@tldraw/core' +import { TLDR } from '~state/tldr' + +export class ArrowSession implements Session { + id = 'transform_single' + status = TLDrawStatus.TranslatingHandle + newBindingId = Utils.uniqueId() + delta = [0, 0] + offset = [0, 0] + origin: number[] + initialShape: ArrowShape + handleId: 'start' | 'end' + bindableShapeIds: string[] + initialBinding: TLDrawBinding | undefined + didBind = false + + constructor(data: Data, handleId: 'start' | 'end', point: number[]) { + const { currentPageId } = data.appState + const page = data.document.pages[currentPageId] + const pageState = data.document.pageStates[currentPageId] + + const shapeId = pageState.selectedIds[0] + this.origin = point + this.handleId = handleId + this.initialShape = TLDR.getShape(data, shapeId, data.appState.currentPageId) + this.bindableShapeIds = TLDR.getBindableShapeIds(data) + + const initialBindingId = this.initialShape.handles[this.handleId].bindingId + + if (initialBindingId) { + this.initialBinding = page.bindings[initialBindingId] + } else { + // Explicitly set this handle to undefined, so that it gets deleted on undo + this.initialShape.handles[this.handleId].bindingId = undefined + } + } + + start = () => void null + + update = (data: Data, point: number[], shiftKey: boolean, altKey: boolean, metaKey: boolean) => { + const page = TLDR.getPage(data, data.appState.currentPageId) + + const { initialShape } = this + + const shape = TLDR.getShape(data, initialShape.id, data.appState.currentPageId) + + const handles = shape.handles + + const handleId = this.handleId as keyof typeof handles + + const delta = Vec.sub(point, handles[handleId].point) + + const handle = { + ...handles[handleId], + point: Vec.sub(Vec.add(handles[handleId].point, delta), shape.point), + } + + // First update the handle's next point + const change = TLDR.getShapeUtils(shape).onHandleChange( + shape, + { + [handleId]: handle, + }, + { delta, shiftKey, altKey, metaKey } + ) + + // If the handle changed produced no change, bail here + if (!change) return + + // If we've made it this far, the shape should be a new objet reference + // that incorporates the changes we've made due to the handle movement. + let nextShape = { ...shape, ...change } + + // If nothing changes, we want this to be the same object reference as + // before. If it does change, we'll redefine this later on. + let nextBindings: Record = page.bindings + + // If the handle can bind, then we need to search bindable shapes for + // a binding. If the handle already has a binding, then we will either + // update that binding or delete it (if no binding is found). + if (handle.canBind) { + // const { binding, target } = findBinding( + // data, + // initialShape, + // handle, + // this.newBindingId, + // this.bindableShapeIds, + // page.bindings, + // altKey, + // metaKey + // ) + + let binding: ArrowBinding | undefined = undefined + let target: TLDrawShape | undefined = undefined + + // Alt key skips binding + if (!altKey) { + const oppositeHandle = handles[handle.id === 'start' ? 'end' : 'start'] + + // Find the origin and direction of the handle + const rayOrigin = Vec.add(oppositeHandle.point, shape.point) + const rayPoint = Vec.add(handle.point, shape.point) + const rayDirection = Vec.uni(Vec.sub(rayPoint, rayOrigin)) + + const oppositeBinding = oppositeHandle.bindingId + ? page.bindings[oppositeHandle.bindingId] + : undefined + + // From all bindable shapes on the page... + for (const id of this.bindableShapeIds) { + if (id === initialShape.id) continue + if (id === shape.parentId) continue + if (id === oppositeBinding?.toId) continue + + target = TLDR.getShape(data, id, data.appState.currentPageId) + + const util = TLDR.getShapeUtils(target) + + const bindingPoint = util.getBindingPoint( + target, + nextShape, + rayPoint, + rayOrigin, + rayDirection, + 32, + metaKey + ) + + // Not all shapes will produce a binding point + if (!bindingPoint) continue + + binding = { + id: this.newBindingId, + type: 'arrow', + fromId: initialShape.id, + handleId: this.handleId, + toId: target.id, + point: Vec.round(bindingPoint.point), + distance: bindingPoint.distance, + } + + break + } + } + + // If we didn't find a target... + if (binding === undefined) { + this.didBind = false + + if (handle.bindingId) { + nextBindings = { ...nextBindings } + nextBindings[handle.bindingId] = undefined + } + nextShape.handles[handleId].bindingId = undefined + } else if (target) { + this.didBind = true + nextBindings = { ...nextBindings } + + if (handle.bindingId && handle.bindingId !== this.newBindingId) { + nextBindings[handle.bindingId] = undefined + nextShape.handles[handleId].bindingId = undefined + } + + // If we found a new binding, add its id to the shape's handle... + nextShape = { + ...nextShape, + handles: { + ...nextShape.handles, + [handleId]: { + ...nextShape.handles[handleId], + bindingId: binding.id, + }, + }, + } + + // and add it to the page's bindings + nextBindings = { + ...nextBindings, + [binding.id]: binding, + } + + // Now update the arrow in response to the new binding + const targetUtils = TLDR.getShapeUtils(target) + const arrowChange = TLDR.getShapeUtils(nextShape).onBindingChange( + nextShape, + binding, + target, + targetUtils.getBounds(target), + targetUtils.getCenter(target) + ) + + if (arrowChange) { + nextShape = { + ...nextShape, + ...arrowChange, + } + } + } + } + + return { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: { + [shape.id]: nextShape, + }, + bindings: nextBindings, + }, + }, + pageStates: { + [data.appState.currentPageId]: { + bindingId: nextShape.handles[handleId].bindingId, + }, + }, + }, + } + } + + cancel = (data: Data) => { + const { initialShape, newBindingId } = this + + return { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: { + [initialShape.id]: initialShape, + }, + bindings: { + [newBindingId]: undefined, + }, + }, + }, + pageStates: { + [data.appState.currentPageId]: { + bindingId: undefined, + }, + }, + }, + } + } + + complete(data: Data) { + const { initialShape, initialBinding, handleId } = this + const page = TLDR.getPage(data, data.appState.currentPageId) + + const beforeBindings: Partial> = {} + const afterBindings: Partial> = {} + + const currentShape = TLDR.getShape( + data, + initialShape.id, + data.appState.currentPageId + ) + const currentBindingId = currentShape.handles[handleId].bindingId + + if (initialBinding) { + beforeBindings[initialBinding.id] = initialBinding + afterBindings[initialBinding.id] = undefined + } + + if (currentBindingId) { + beforeBindings[currentBindingId] = undefined + afterBindings[currentBindingId] = page.bindings[currentBindingId] + } + + return { + id: 'arrow', + before: { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: { + [initialShape.id]: initialShape, + }, + bindings: beforeBindings, + }, + }, + pageStates: { + [data.appState.currentPageId]: { + bindingId: undefined, + }, + }, + }, + }, + after: { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: { + [initialShape.id]: TLDR.onSessionComplete( + data, + TLDR.getShape(data, initialShape.id, data.appState.currentPageId), + data.appState.currentPageId + ), + }, + bindings: afterBindings, + }, + }, + pageStates: { + [data.appState.currentPageId]: { + bindingId: undefined, + }, + }, + }, + }, + } + } +} diff --git a/packages/tldraw/src/state/session/sessions/arrow/index.ts b/packages/tldraw/src/state/session/sessions/arrow/index.ts new file mode 100644 index 000000000..31fb65b5b --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/arrow/index.ts @@ -0,0 +1 @@ +export * from './arrow.session' diff --git a/packages/tldraw/src/state/session/sessions/brush/brush.session.spec.ts b/packages/tldraw/src/state/session/sessions/brush/brush.session.spec.ts new file mode 100644 index 000000000..83fc754aa --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/brush/brush.session.spec.ts @@ -0,0 +1,52 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { TLDrawStatus } from '~types' + +describe('Brush session', () => { + const tlstate = new TLDrawState() + tlstate.loadDocument(mockDocument) + + it('begins, updates and completes session', () => { + tlstate.deselectAll() + tlstate.startBrushSession([-10, -10]) + tlstate.updateBrushSession([10, 10]) + tlstate.completeSession() + expect(tlstate.appState.status.current).toBe(TLDrawStatus.Idle) + expect(tlstate.selectedIds.length).toBe(1) + }) + + it('selects multiple shapes', () => { + tlstate.deselectAll() + tlstate.startBrushSession([-10, -10]) + tlstate.updateBrushSession([110, 110]) + tlstate.completeSession() + expect(tlstate.selectedIds.length).toBe(3) + }) + + it('does not de-select original shapes', () => { + tlstate.deselectAll() + tlstate + .select('rect1') + .startBrushSession([300, 300]) + .updateBrushSession([301, 301]) + .completeSession() + expect(tlstate.selectedIds.length).toBe(1) + }) + + it('does not select hidden shapes', () => { + tlstate.toggleHidden(['rect1']) + tlstate.deselectAll() + tlstate.startBrushSession([-10, -10]) + tlstate.updateBrushSession([10, 10]) + tlstate.completeSession() + expect(tlstate.selectedIds.length).toBe(0) + }) + + it('when command is held, require the entire shape to be selected', () => { + tlstate.loadDocument(mockDocument) + tlstate.deselectAll() + tlstate.startBrushSession([-10, -10]) + tlstate.updateBrushSession([10, 10]) + tlstate.completeSession() + }) +}) diff --git a/packages/tldraw/src/state/session/sessions/brush/brush.session.ts b/packages/tldraw/src/state/session/sessions/brush/brush.session.ts new file mode 100644 index 000000000..2b93b8279 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/brush/brush.session.ts @@ -0,0 +1,136 @@ +import { brushUpdater, Utils, Vec } from '@tldraw/core' +import { Data, Session, TLDrawPatch, TLDrawStatus } from '~types' +import { getShapeUtils } from '~shape' +import { TLDR } from '~state/tldr' + +export class BrushSession implements Session { + id = 'brush' + status = TLDrawStatus.Brushing + origin: number[] + snapshot: BrushSnapshot + + constructor(data: Data, point: number[]) { + this.origin = Vec.round(point) + this.snapshot = getBrushSnapshot(data) + } + + start = () => void null + + update = (data: Data, point: number[], containMode = false): TLDrawPatch => { + const { snapshot, origin } = this + const { currentPageId } = data.appState + + // Create a bounding box between the origin and the new point + const brush = Utils.getBoundsFromPoints([origin, point]) + + brushUpdater.set(brush) + + // Find ids of brushed shapes + const hits = new Set() + const selectedIds = new Set(snapshot.selectedIds) + + const page = TLDR.getPage(data, currentPageId) + const pageState = TLDR.getPageState(data, currentPageId) + + snapshot.shapesToTest.forEach(({ id, util, selectId }) => { + if (selectedIds.has(id)) return + + const shape = page.shapes[id] + + if (!hits.has(selectId)) { + if ( + containMode + ? Utils.boundsContain(brush, util.getBounds(shape)) + : util.hitTestBounds(shape, brush) + ) { + hits.add(selectId) + + // When brushing a shape, select its top group parent. + if (!selectedIds.has(selectId)) { + selectedIds.add(selectId) + } + } else if (selectedIds.has(selectId)) { + selectedIds.delete(selectId) + } + } + }) + + if ( + selectedIds.size === pageState.selectedIds.length && + pageState.selectedIds.every((id) => selectedIds.has(id)) + ) { + return {} + } + + return { + document: { + pageStates: { + [currentPageId]: { + selectedIds: Array.from(selectedIds.values()), + }, + }, + }, + } + } + + cancel(data: Data) { + const { currentPageId } = data.appState + return { + document: { + pageStates: { + [currentPageId]: { + selectedIds: this.snapshot.selectedIds, + }, + }, + }, + } + } + + complete(data: Data) { + const { currentPageId } = data.appState + const pageState = TLDR.getPageState(data, currentPageId) + return { + document: { + pageStates: { + [currentPageId]: { + selectedIds: [...pageState.selectedIds], + }, + }, + }, + } + } +} + +/** + * Get a snapshot of the current selected ids, for each shape that is + * not already selected, the shape's id and a test to see whether the + * brush will intersect that shape. For tests, start broad -> fine. + */ +export function getBrushSnapshot(data: Data) { + const { currentPageId } = data.appState + const selectedIds = [...TLDR.getSelectedIds(data, currentPageId)] + + const shapesToTest = TLDR.getShapes(data, currentPageId) + .filter( + (shape) => + !( + shape.isHidden || + shape.children !== undefined || + selectedIds.includes(shape.id) || + selectedIds.includes(shape.parentId) + ) + ) + .map((shape) => ({ + id: shape.id, + util: getShapeUtils(shape), + bounds: getShapeUtils(shape).getBounds(shape), + selectId: TLDR.getTopParentId(data, shape.id, currentPageId), + })) + + return { + selectedIds, + shapesToTest, + } +} + +export type BrushSnapshot = ReturnType diff --git a/packages/tldraw/src/state/session/sessions/brush/index.ts b/packages/tldraw/src/state/session/sessions/brush/index.ts new file mode 100644 index 000000000..d8e5b1834 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/brush/index.ts @@ -0,0 +1 @@ +export * from './brush.session' diff --git a/packages/tldraw/src/state/session/sessions/draw/draw.session.spec.ts b/packages/tldraw/src/state/session/sessions/draw/draw.session.spec.ts new file mode 100644 index 000000000..8c9bcc786 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/draw/draw.session.spec.ts @@ -0,0 +1,47 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { ColorStyle, DashStyle, SizeStyle, TLDrawShapeType, TLDrawStatus } from '~types' + +describe('Draw session', () => { + const tlstate = new TLDrawState() + + it('begins, updates and completes session', () => { + tlstate.loadDocument(mockDocument) + + expect(tlstate.getShape('draw1')).toBe(undefined) + + tlstate + .create({ + id: 'draw1', + parentId: 'page1', + name: 'Draw', + childIndex: 5, + type: TLDrawShapeType.Draw, + point: [32, 32], + points: [[0, 0]], + style: { + dash: DashStyle.Draw, + size: SizeStyle.Medium, + color: ColorStyle.Blue, + }, + }) + .select('draw1') + .startDrawSession('draw1', [0, 0]) + .updateDrawSession([10, 10], 0.5) + .completeSession() + + expect(tlstate.appState.status.current).toBe(TLDrawStatus.Idle) + }) + + it('does, undoes and redoes', () => { + expect(tlstate.getShape('draw1')).toBeTruthy() + + tlstate.undo() + + expect(tlstate.getShape('draw1')).toBe(undefined) + + tlstate.redo() + + expect(tlstate.getShape('draw1')).toBeTruthy() + }) +}) diff --git a/packages/tldraw/src/state/session/sessions/draw/draw.session.ts b/packages/tldraw/src/state/session/sessions/draw/draw.session.ts new file mode 100644 index 000000000..603f9295b --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/draw/draw.session.ts @@ -0,0 +1,198 @@ +import { Utils, Vec } from '@tldraw/core' +import { Data, DrawShape, Session, TLDrawStatus } from '~types' +import { TLDR } from '~state/tldr' + +// TODO +// [ ] - Solve flat lines at corners on perfectly straight lines + +export class DrawSession implements Session { + id = 'draw' + status = TLDrawStatus.Creating + origin: number[] + previous: number[] + last: number[] + points: number[][] + snapshot: DrawSnapshot + isLocked?: boolean + lockedDirection?: 'horizontal' | 'vertical' + + constructor(data: Data, id: string, point: number[]) { + this.origin = point + this.previous = point + this.last = point + + this.snapshot = getDrawSnapshot(data, id) + + // Add a first point but don't update the shape yet. We'll update + // when the draw session ends; if the user hasn't added additional + // points, this single point will be interpreted as a "dot" shape. + this.points = [] + } + + start = () => void null + + update = (data: Data, point: number[], pressure: number, isLocked = false) => { + const { snapshot } = this + + // Roundabout way of preventing the "dot" from showing while drawing + if (this.points.length === 0) { + this.points.push([0, 0, pressure]) + } + + // Drawing while holding shift will "lock" the pen to either the + // x or y axis, depending on which direction has the greater + // delta. Pressing shift will also add more points to "return" + // the pen to the axis. + if (isLocked) { + if (!this.isLocked && this.points.length > 1) { + const bounds = Utils.getBoundsFromPoints(this.points) + if (bounds.width > 8 || bounds.height > 8) { + this.isLocked = true + const returning = [...this.previous] + + const isVertical = bounds.height > 8 + + if (isVertical) { + this.lockedDirection = 'vertical' + returning[0] = this.origin[0] + } else { + this.lockedDirection = 'horizontal' + returning[1] = this.origin[1] + } + + this.previous = returning + this.points.push(Vec.sub(returning, this.origin)) + } + } + } else if (this.isLocked) { + this.isLocked = false + } + + if (this.isLocked) { + if (this.lockedDirection === 'vertical') { + point[0] = this.origin[0] + } else { + point[1] = this.origin[1] + } + } + + // The previous input (not adjusted) point + this.previous = point + + // The new adjusted point + const newPoint = Vec.round(Vec.sub(this.previous, this.origin)).concat(pressure) + + // Don't add duplicate points. Be sure to + // test against the previous *adjusted* point. + if (Vec.isEqual(this.last, newPoint)) return + + // The new adjusted point is now the previous adjusted point. + this.last = newPoint + + // Add the new adjusted point to the points array + this.points.push(newPoint) + + return { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: { + [snapshot.id]: { + points: [...this.points], // Set to a new array here + }, + }, + }, + }, + pageStates: { + [data.appState.currentPageId]: { + selectedIds: [snapshot.id], + }, + }, + }, + } + } + + cancel = (data: Data) => { + const { snapshot } = this + const pageId = data.appState.currentPageId + + return { + document: { + pages: { + [pageId]: { + shapes: { + [snapshot.id]: undefined, + }, + }, + }, + pageStates: { + [pageId]: { + selectedIds: [], + }, + }, + }, + } + } + + complete = (data: Data) => { + const { snapshot } = this + const pageId = data.appState.currentPageId + + this.points.push(this.last) + + return { + id: 'create_draw', + before: { + document: { + pages: { + [pageId]: { + shapes: { + [snapshot.id]: undefined, + }, + }, + }, + pageStates: { + [pageId]: { + selectedIds: [], + }, + }, + }, + }, + after: { + document: { + pages: { + [pageId]: { + shapes: { + [snapshot.id]: TLDR.onSessionComplete( + data, + { ...TLDR.getShape(data, snapshot.id, pageId), points: [...this.points] }, + pageId + ), + }, + }, + }, + pageStates: { + [data.appState.currentPageId]: { + selectedIds: [], + }, + }, + }, + }, + } + } +} + +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +export function getDrawSnapshot(data: Data, shapeId: string) { + const page = { ...TLDR.getPage(data, data.appState.currentPageId) } + + const { points, point } = Utils.deepClone(page.shapes[shapeId]) as DrawShape + + return { + id: shapeId, + point, + points, + } +} + +export type DrawSnapshot = ReturnType diff --git a/packages/tldraw/src/state/session/sessions/draw/index.ts b/packages/tldraw/src/state/session/sessions/draw/index.ts new file mode 100644 index 000000000..aff2816cf --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/draw/index.ts @@ -0,0 +1 @@ +export * from './draw.session' diff --git a/packages/tldraw/src/state/session/sessions/handle/handle.session.spec.ts b/packages/tldraw/src/state/session/sessions/handle/handle.session.spec.ts new file mode 100644 index 000000000..7c606cdca --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/handle/handle.session.spec.ts @@ -0,0 +1,43 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { TLDR } from '~state/tldr' +import { TLDrawShape, TLDrawStatus } from '~types' + +describe('Handle session', () => { + const tlstate = new TLDrawState() + + it('begins, updates and completes session', () => { + tlstate + .loadDocument(mockDocument) + .create( + TLDR.getShapeUtils({ type: 'arrow' } as TLDrawShape).create({ + id: 'arrow1', + parentId: 'page1', + }) + ) + .select('arrow1') + .startHandleSession([-10, -10], 'end') + .updateHandleSession([10, 10]) + .completeSession() + + expect(tlstate.appState.status.current).toBe(TLDrawStatus.Idle) + + tlstate.undo().redo() + }) + + it('cancels session', () => { + tlstate + .loadDocument(mockDocument) + .create({ + ...TLDR.getShapeUtils({ type: 'arrow' } as TLDrawShape).defaultProps, + id: 'arrow1', + parentId: 'page1', + }) + .select('arrow1') + .startHandleSession([-10, -10], 'end') + .updateHandleSession([10, 10]) + .cancelSession() + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + }) +}) diff --git a/packages/tldraw/src/state/session/sessions/handle/handle.session.ts b/packages/tldraw/src/state/session/sessions/handle/handle.session.ts new file mode 100644 index 000000000..11a0c0942 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/handle/handle.session.ts @@ -0,0 +1,120 @@ +import { Vec } from '@tldraw/core' +import { ShapesWithProp, TLDrawStatus } from '~types' +import type { Session } from '~types' +import type { Data } from '~types' +import { TLDR } from '~state/tldr' + +export class HandleSession implements Session { + id = 'transform_single' + status = TLDrawStatus.TranslatingHandle + commandId: string + delta = [0, 0] + origin: number[] + shiftKey = false + initialShape: ShapesWithProp<'handles'> + handleId: string + + constructor(data: Data, handleId: string, point: number[], commandId = 'move_handle') { + const { currentPageId } = data.appState + const shapeId = TLDR.getSelectedIds(data, currentPageId)[0] + this.origin = point + this.handleId = handleId + this.initialShape = TLDR.getShape(data, shapeId, currentPageId) + this.commandId = commandId + } + + start = () => void null + + update = (data: Data, point: number[], shiftKey: boolean, altKey: boolean, metaKey: boolean) => { + const { initialShape } = this + const { currentPageId } = data.appState + + const shape = TLDR.getShape>(data, initialShape.id, currentPageId) + + const handles = shape.handles + + const handleId = this.handleId as keyof typeof handles + + const delta = Vec.sub(point, handles[handleId].point) + + const handle = { + ...handles[handleId], + point: Vec.sub(Vec.add(handles[handleId].point, delta), shape.point), + } + + // First update the handle's next point + const change = TLDR.getShapeUtils(shape).onHandleChange( + shape, + { + [handleId]: handle, + }, + { delta, shiftKey, altKey, metaKey } + ) + + if (!change) return data + + return { + document: { + pages: { + [currentPageId]: { + shapes: { + [shape.id]: change, + }, + }, + }, + }, + } + } + + cancel = (data: Data) => { + const { initialShape } = this + const { currentPageId } = data.appState + + return { + document: { + pages: { + [currentPageId]: { + shapes: { + [initialShape.id]: initialShape, + }, + }, + }, + }, + } + } + + complete(data: Data) { + const { initialShape } = this + const pageId = data.appState.currentPageId + + return { + id: this.commandId, + before: { + document: { + pages: { + [pageId]: { + shapes: { + [initialShape.id]: initialShape, + }, + }, + }, + }, + }, + after: { + document: { + pages: { + [pageId]: { + shapes: { + [initialShape.id]: TLDR.onSessionComplete( + data, + TLDR.getShape(data, this.initialShape.id, pageId), + pageId + ), + }, + }, + }, + }, + }, + } + } +} diff --git a/packages/tldraw/src/state/session/sessions/handle/index.ts b/packages/tldraw/src/state/session/sessions/handle/index.ts new file mode 100644 index 000000000..973107549 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/handle/index.ts @@ -0,0 +1 @@ +export * from './handle.session' diff --git a/packages/tldraw/src/state/session/sessions/index.ts b/packages/tldraw/src/state/session/sessions/index.ts new file mode 100644 index 000000000..3ba22bfd2 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/index.ts @@ -0,0 +1,9 @@ +export * from './brush' +export * from './translate' +export * from './transform-single' +export * from './transform' +export * from './draw' +export * from './rotate' +export * from './handle' +export * from './text' +export * from './arrow' diff --git a/packages/tldraw/src/state/session/sessions/rotate/index.ts b/packages/tldraw/src/state/session/sessions/rotate/index.ts new file mode 100644 index 000000000..acf631207 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/rotate/index.ts @@ -0,0 +1 @@ +export * from './rotate.session' diff --git a/packages/tldraw/src/state/session/sessions/rotate/rotate.session.spec.ts b/packages/tldraw/src/state/session/sessions/rotate/rotate.session.spec.ts new file mode 100644 index 000000000..fdc2c3219 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/rotate/rotate.session.spec.ts @@ -0,0 +1,59 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { TLDrawStatus } from '~types' + +describe('Rotate session', () => { + const tlstate = new TLDrawState() + + it('begins, updates and completes session', () => { + tlstate.loadDocument(mockDocument) + + expect(tlstate.getShape('rect1').rotation).toBe(undefined) + + tlstate + .select('rect1') + .startTransformSession([50, 0], 'rotate') + .updateTransformSession([100, 50]) + + expect(tlstate.getShape('rect1').rotation).toBe(Math.PI / 2) + + tlstate.updateTransformSession([50, 100]) + + expect(tlstate.getShape('rect1').rotation).toBe(Math.PI) + + tlstate.updateTransformSession([0, 50]) + + expect(tlstate.getShape('rect1').rotation).toBe((Math.PI * 3) / 2) + + tlstate.updateTransformSession([50, 0]) + + expect(tlstate.getShape('rect1').rotation).toBe(0) + + tlstate.updateTransformSession([0, 50]) + + expect(tlstate.getShape('rect1').rotation).toBe((Math.PI * 3) / 2) + + tlstate.completeSession() + + expect(tlstate.appState.status.current).toBe(TLDrawStatus.Idle) + + tlstate.undo() + + expect(tlstate.getShape('rect1').rotation).toBe(undefined) + + tlstate.redo() + + expect(tlstate.getShape('rect1').rotation).toBe((Math.PI * 3) / 2) + }) + + it('cancels session', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1') + .startTransformSession([50, 0], 'rotate') + .updateTransformSession([100, 50]) + .cancel() + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + }) +}) diff --git a/packages/tldraw/src/state/session/sessions/rotate/rotate.session.ts b/packages/tldraw/src/state/session/sessions/rotate/rotate.session.ts new file mode 100644 index 000000000..0998a7c37 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/rotate/rotate.session.ts @@ -0,0 +1,187 @@ +import { Utils, Vec } from '@tldraw/core' +import { Session, TLDrawShape, TLDrawStatus } from '~types' +import type { Data } from '~types' +import { TLDR } from '~state/tldr' + +const PI2 = Math.PI * 2 + +export class RotateSession implements Session { + id = 'rotate' + status = TLDrawStatus.Transforming + delta = [0, 0] + origin: number[] + snapshot: RotateSnapshot + prev = 0 + + constructor(data: Data, point: number[]) { + this.origin = point + this.snapshot = getRotateSnapshot(data) + } + + start = () => void null + + update = (data: Data, point: number[], isLocked = false) => { + const { commonBoundsCenter, initialShapes } = this.snapshot + const pageId = data.appState.currentPageId + const page = TLDR.getPage(data, pageId) + const pageState = TLDR.getPageState(data, pageId) + + const shapes: Record = {} + + for (const { id, shape } of initialShapes) { + shapes[id] = shape + } + + const a1 = Vec.angle(commonBoundsCenter, this.origin) + const a2 = Vec.angle(commonBoundsCenter, point) + + let rot = a2 - a1 + + this.prev = rot + + if (isLocked) { + rot = Utils.clampToRotationToSegments(rot, 24) + } + + pageState.boundsRotation = (PI2 + (this.snapshot.boundsRotation + rot)) % PI2 + + initialShapes.forEach(({ id, center, offset, shape: { rotation = 0 } }) => { + const shape = page.shapes[id] + + const nextRotation = isLocked + ? Utils.clampToRotationToSegments(rotation + rot, 24) + : rotation + rot + + const nextPoint = Vec.sub(Vec.rotWith(center, commonBoundsCenter, rot), offset) + + shapes[id] = TLDR.mutate( + data, + shape, + { + point: nextPoint, + rotation: (PI2 + nextRotation) % PI2, + }, + pageId + ) + }) + + return { + document: { + pages: { + [pageId]: { + shapes, + }, + }, + }, + } + } + + cancel = (data: Data) => { + const { initialShapes } = this.snapshot + const pageId = data.appState.currentPageId + + const shapes: Record = {} + + for (const { id, shape } of initialShapes) { + shapes[id] = shape + } + + return { + document: { + pages: { + [pageId]: { + shapes, + }, + }, + }, + } + } + + complete(data: Data) { + const { hasUnlockedShapes, initialShapes } = this.snapshot + const pageId = data.appState.currentPageId + + if (!hasUnlockedShapes) return data + + const beforeShapes = {} as Record> + const afterShapes = {} as Record> + + initialShapes.forEach(({ id, shape: { point, rotation } }) => { + beforeShapes[id] = { point, rotation } + const afterShape = TLDR.getShape(data, id, pageId) + afterShapes[id] = { point: afterShape.point, rotation: afterShape.rotation } + }) + + return { + id: 'rotate', + before: { + document: { + pages: { + [pageId]: { + shapes: beforeShapes, + }, + }, + }, + }, + after: { + document: { + pages: { + [pageId]: { + shapes: afterShapes, + }, + }, + }, + }, + } + } +} + +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +export function getRotateSnapshot(data: Data) { + const currentPageId = data.appState.currentPageId + const pageState = TLDR.getPageState(data, currentPageId) + const initialShapes = TLDR.getSelectedBranchSnapshot(data, currentPageId) + + if (initialShapes.length === 0) { + throw Error('No selected shapes!') + } + + const hasUnlockedShapes = initialShapes.length > 0 + + const shapesBounds = Object.fromEntries( + initialShapes.map((shape) => [shape.id, TLDR.getBounds(shape)]) + ) + + const rotatedBounds = Object.fromEntries( + initialShapes.map((shape) => [shape.id, TLDR.getRotatedBounds(shape)]) + ) + + const bounds = Utils.getCommonBounds(Object.values(shapesBounds)) + + const commonBoundsCenter = Utils.getBoundsCenter(bounds) + + return { + hasUnlockedShapes, + boundsRotation: pageState.boundsRotation || 0, + commonBoundsCenter, + initialShapes: initialShapes + .filter((shape) => shape.children === undefined) + .map((shape) => { + const bounds = TLDR.getBounds(shape) + const center = Utils.getBoundsCenter(bounds) + const offset = Vec.sub(center, shape.point) + + const rotationOffset = Vec.sub(center, Utils.getBoundsCenter(rotatedBounds[shape.id])) + + return { + id: shape.id, + shape: Utils.deepClone(shape), + offset, + rotationOffset, + center, + } + }), + } +} + +export type RotateSnapshot = ReturnType diff --git a/packages/tldraw/src/state/session/sessions/text/index.ts b/packages/tldraw/src/state/session/sessions/text/index.ts new file mode 100644 index 000000000..3fe829872 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/text/index.ts @@ -0,0 +1 @@ +export * from './text.session' diff --git a/packages/tldraw/src/state/session/sessions/text/text.session.spec.ts b/packages/tldraw/src/state/session/sessions/text/text.session.spec.ts new file mode 100644 index 000000000..70d0f7e79 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/text/text.session.spec.ts @@ -0,0 +1,44 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { TLDR } from '~state/tldr' +import { TextShape, TLDrawShape, TLDrawShapeType } from '~types' + +describe('Text session', () => { + const tlstate = new TLDrawState() + + it('begins, updates and completes session', () => { + tlstate + .loadDocument(mockDocument) + .create( + TLDR.getShapeUtils({ type: TLDrawShapeType.Text } as TLDrawShape).create({ + id: 'text1', + parentId: 'page1', + }) + ) + .select('text1') + .startTextSession('text1') + .updateTextSession('Hello world') + .completeSession() + .undo() + .redo() + + expect(tlstate.getShape('text1').text).toStrictEqual('Hello world') + }) + + it('cancels session', () => { + tlstate + .loadDocument(mockDocument) + .create( + TLDR.getShapeUtils({ type: TLDrawShapeType.Text } as TLDrawShape).create({ + id: 'text1', + parentId: 'page1', + }) + ) + .select('text1') + .startTextSession('text1') + .updateTextSession('Hello world') + .cancelSession() + + expect(tlstate.getShape('text1').text).toStrictEqual('Hello world') + }) +}) diff --git a/packages/tldraw/src/state/session/sessions/text/text.session.ts b/packages/tldraw/src/state/session/sessions/text/text.session.ts new file mode 100644 index 000000000..3c24eed69 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/text/text.session.ts @@ -0,0 +1,176 @@ +import { TextShape, TLDrawStatus } from '~types' +import type { Session } from '~types' +import type { Data } from '~types' +import { TLDR } from '~state/tldr' + +export class TextSession implements Session { + id = 'text' + status = TLDrawStatus.EditingText + initialShape: TextShape + + constructor(data: Data, id?: string) { + const pageId = data.appState.currentPageId + this.initialShape = TLDR.getShape(data, id || TLDR.getSelectedIds(data, pageId)[0], pageId) + } + + start = (data: Data) => { + const pageId = data.appState.currentPageId + return { + document: { + pageStates: { + [pageId]: { + editingId: this.initialShape.id, + }, + }, + }, + } + } + + update = (data: Data, text: string) => { + const { initialShape } = this + const pageId = data.appState.currentPageId + + let nextShape: TextShape = { + ...TLDR.getShape(data, initialShape.id, pageId), + text, + } + + nextShape = { + ...nextShape, + ...TLDR.getShapeUtils(nextShape).onStyleChange(nextShape), + } as TextShape + + return { + document: { + pages: { + [pageId]: { + shapes: { + [initialShape.id]: nextShape, + }, + }, + }, + }, + } + } + + cancel = (data: Data) => { + const { initialShape } = this + const pageId = data.appState.currentPageId + + return { + document: { + pages: { + [pageId]: { + shapes: { + [initialShape.id]: TLDR.onSessionComplete( + data, + TLDR.getShape(data, initialShape.id, pageId), + pageId + ), + }, + }, + }, + pageState: { + [pageId]: { + editingId: undefined, + }, + }, + }, + } + } + + complete(data: Data) { + const { initialShape } = this + const pageId = data.appState.currentPageId + + const shape = TLDR.getShape(data, initialShape.id, pageId) + + // TODO: Delete text shape if its content is empty + // TODO: ...and prevent `isCreating` from selecting the deleted shape + + // if (initialShape.text.trim() === '' && shape.text.trim() === '') { + // // delete shape + // console.log('deleting shape') + // return { + // id: 'text', + // before: { + // document: { + // pages: { + // [pageId]: { + // shapes: { + // [initialShape.id]: undefined, + // }, + // }, + // }, + // pageState: { + // [pageId]: { + // editingId: undefined, + // selectedIds: [initialShape.id], + // }, + // }, + // }, + // }, + // after: { + // document: { + // pages: { + // [pageId]: { + // shapes: { + // [initialShape.id]: undefined, + // }, + // }, + // }, + // pageState: { + // [pageId]: { + // editingId: undefined, + // selectedIds: [], + // }, + // }, + // }, + // }, + // } + // } + + if (shape.text === initialShape.text) return undefined + + return { + id: 'text', + before: { + document: { + pages: { + [pageId]: { + shapes: { + [initialShape.id]: initialShape, + }, + }, + }, + pageState: { + [pageId]: { + editingId: undefined, + }, + }, + }, + }, + after: { + document: { + pages: { + [pageId]: { + shapes: { + [initialShape.id]: TLDR.onSessionComplete( + data, + TLDR.getShape(data, initialShape.id, pageId), + pageId + ), + }, + }, + }, + pageState: { + [pageId]: { + editingId: undefined, + selectedIds: [initialShape.id], + }, + }, + }, + }, + } + } +} diff --git a/packages/tldraw/src/state/session/sessions/transform-single/index.ts b/packages/tldraw/src/state/session/sessions/transform-single/index.ts new file mode 100644 index 000000000..b1868b800 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/transform-single/index.ts @@ -0,0 +1 @@ +export * from './transform-single.session' diff --git a/packages/tldraw/src/state/session/sessions/transform-single/transform-single.session.spec.ts b/packages/tldraw/src/state/session/sessions/transform-single/transform-single.session.spec.ts new file mode 100644 index 000000000..546fba429 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/transform-single/transform-single.session.spec.ts @@ -0,0 +1,32 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { TLBoundsCorner } from '@tldraw/core' +import { TLDrawStatus } from '~types' + +describe('Transform single session', () => { + const tlstate = new TLDrawState() + + it('begins, updates and completes session', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1') + .startTransformSession([-10, -10], TLBoundsCorner.TopLeft) + .updateTransformSession([10, 10]) + .completeSession() + + expect(tlstate.appState.status.current).toBe(TLDrawStatus.Idle) + + tlstate.undo().redo() + }) + + it('cancels session', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1') + .startTransformSession([5, 5], TLBoundsCorner.TopLeft) + .updateTransformSession([10, 10]) + .cancelSession() + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + }) +}) diff --git a/packages/tldraw/src/state/session/sessions/transform-single/transform-single.session.ts b/packages/tldraw/src/state/session/sessions/transform-single/transform-single.session.ts new file mode 100644 index 000000000..e61ea2531 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/transform-single/transform-single.session.ts @@ -0,0 +1,151 @@ +import { TLBoundsCorner, TLBoundsEdge, Utils, Vec } from '@tldraw/core' +import { TLDrawShape, TLDrawStatus } from '~types' +import type { Session } from '~types' +import type { Data } from '~types' +import { TLDR } from '~state/tldr' + +export class TransformSingleSession implements Session { + id = 'transform_single' + status = TLDrawStatus.Transforming + commandId: string + transformType: TLBoundsEdge | TLBoundsCorner + origin: number[] + scaleX = 1 + scaleY = 1 + snapshot: TransformSingleSnapshot + + constructor( + data: Data, + point: number[], + transformType: TLBoundsEdge | TLBoundsCorner = TLBoundsCorner.BottomRight, + commandId = 'transform_single' + ) { + this.origin = point + this.transformType = transformType + this.snapshot = getTransformSingleSnapshot(data, transformType) + this.commandId = commandId + } + + start = () => void null + + update = (data: Data, point: number[], isAspectRatioLocked = false) => { + const { transformType } = this + + const { initialShapeBounds, initialShape, id } = this.snapshot + + const shapes = {} as Record> + + const shape = TLDR.getShape(data, id, data.appState.currentPageId) + + const utils = TLDR.getShapeUtils(shape) + + const newBounds = Utils.getTransformedBoundingBox( + initialShapeBounds, + transformType, + Vec.sub(point, this.origin), + shape.rotation, + isAspectRatioLocked || shape.isAspectRatioLocked || utils.isAspectRatioLocked + ) + + shapes[shape.id] = TLDR.getShapeUtils(shape).transformSingle(shape, newBounds, { + initialShape, + type: this.transformType, + scaleX: newBounds.scaleX, + scaleY: newBounds.scaleY, + transformOrigin: [0.5, 0.5], + }) + + return { + document: { + pages: { + [data.appState.currentPageId]: { + shapes, + }, + }, + }, + } + } + + cancel = (data: Data) => { + const { initialShape } = this.snapshot + + const shapes = {} as Record> + + shapes[initialShape.id] = initialShape + + return { + document: { + pages: { + [data.appState.currentPageId]: { + shapes, + }, + }, + }, + } + } + + complete(data: Data) { + if (!this.snapshot.hasUnlockedShape) return data + + const { initialShape } = this.snapshot + + const beforeShapes = {} as Record> + const afterShapes = {} as Record> + + beforeShapes[initialShape.id] = initialShape + afterShapes[initialShape.id] = TLDR.onSessionComplete( + data, + TLDR.getShape(data, initialShape.id, data.appState.currentPageId), + data.appState.currentPageId + ) + + return { + id: this.commandId, + before: { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: beforeShapes, + }, + }, + }, + }, + after: { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: afterShapes, + }, + }, + }, + }, + } + } +} + +export function getTransformSingleSnapshot( + data: Data, + transformType: TLBoundsEdge | TLBoundsCorner +) { + const shape = TLDR.getShape( + data, + TLDR.getSelectedIds(data, data.appState.currentPageId)[0], + data.appState.currentPageId + ) + + if (!shape) { + throw Error('You must have one shape selected.') + } + + const bounds = TLDR.getBounds(shape) + + return { + id: shape.id, + hasUnlockedShape: !shape.isLocked, + type: transformType, + initialShape: Utils.deepClone(shape), + initialShapeBounds: bounds, + } +} + +export type TransformSingleSnapshot = ReturnType diff --git a/packages/tldraw/src/state/session/sessions/transform/index.ts b/packages/tldraw/src/state/session/sessions/transform/index.ts new file mode 100644 index 000000000..0bed2fe8e --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/transform/index.ts @@ -0,0 +1 @@ +export * from './transform.session' diff --git a/packages/tldraw/src/state/session/sessions/transform/transform.session.spec.ts b/packages/tldraw/src/state/session/sessions/transform/transform.session.spec.ts new file mode 100644 index 000000000..0b573fb3f --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/transform/transform.session.spec.ts @@ -0,0 +1,220 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { TLBoundsCorner, Utils } from '@tldraw/core' +import { TLDR } from '~state/tldr' +import { TLDrawStatus } from '~types' + +function getShapeBounds(tlstate: TLDrawState, ...ids: string[]) { + return Utils.getCommonBounds( + (ids.length ? ids : tlstate.selectedIds).map((id) => TLDR.getBounds(tlstate.getShape(id))) + ) +} + +describe('Transform session', () => { + const tlstate = new TLDrawState() + + it('begins, updates and completes session', () => { + tlstate.loadDocument(mockDocument) + + expect(getShapeBounds(tlstate, 'rect1')).toMatchObject({ + minX: 0, + minY: 0, + maxX: 100, + maxY: 100, + width: 100, + height: 100, + }) + + tlstate + .select('rect1', 'rect2') + .startTransformSession([0, 0], TLBoundsCorner.TopLeft) + .updateTransformSession([10, 10]) + .completeSession() + + expect(tlstate.appState.status.current).toBe(TLDrawStatus.Idle) + + expect(getShapeBounds(tlstate, 'rect1')).toMatchObject({ + minX: 10, + minY: 10, + maxX: 105, + maxY: 105, + width: 95, + height: 95, + }) + + tlstate.undo() + + expect(getShapeBounds(tlstate, 'rect1')).toMatchObject({ + minX: 0, + minY: 0, + maxX: 100, + maxY: 100, + width: 100, + height: 100, + }) + + tlstate.redo() + }) + + it('cancels session', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1', 'rect2') + .startTransformSession([5, 5], TLBoundsCorner.TopLeft) + .updateTransformSession([10, 10]) + .cancelSession() + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + }) + + describe('when transforming from the top-left corner', () => { + it('transforms a single shape', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1') + .startTransformSession([0, 0], TLBoundsCorner.TopLeft) + .updateTransformSession([10, 10]) + .completeSession() + + expect(getShapeBounds(tlstate)).toMatchObject({ + minX: 10, + minY: 10, + maxX: 100, + maxY: 100, + width: 90, + height: 90, + }) + }) + + it('transforms a single shape while holding shift', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1') + .startTransformSession([0, 0], TLBoundsCorner.TopLeft) + .updateTransformSession([20, 10], true) + .completeSession() + + expect(getShapeBounds(tlstate, 'rect1')).toMatchObject({ + minX: 10, + minY: 10, + maxX: 100, + maxY: 100, + width: 90, + height: 90, + }) + }) + + it('transforms multiple shapes', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1', 'rect2') + .startTransformSession([0, 0], TLBoundsCorner.TopLeft) + .updateTransformSession([10, 10]) + .completeSession() + + expect(getShapeBounds(tlstate, 'rect1')).toMatchObject({ + minX: 10, + minY: 10, + maxX: 105, + maxY: 105, + width: 95, + height: 95, + }) + + expect(getShapeBounds(tlstate, 'rect2')).toMatchObject({ + minX: 105, + minY: 105, + maxX: 200, + maxY: 200, + width: 95, + height: 95, + }) + }) + + it('transforms multiple shapes while holding shift', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1', 'rect2') + .startTransformSession([0, 0], TLBoundsCorner.TopLeft) + .updateTransformSession([20, 10], true) + .completeSession() + + expect(getShapeBounds(tlstate, 'rect1')).toMatchObject({ + minX: 10, + minY: 10, + maxX: 105, + maxY: 105, + width: 95, + height: 95, + }) + + expect(getShapeBounds(tlstate, 'rect2')).toMatchObject({ + minX: 105, + minY: 105, + maxX: 200, + maxY: 200, + width: 95, + height: 95, + }) + }) + }) + + describe('when transforming from the top-right corner', () => { + // Todo + }) + + describe('when transforming from the bottom-right corner', () => { + // Todo + }) + + describe('when transforming from the bottom-left corner', () => { + // Todo + }) + + describe('when transforming from the top edge', () => { + // Todo + }) + + describe('when transforming from the right edge', () => { + // Todo + }) + + describe('when transforming from the bottom edge', () => { + // Todo + }) + + describe('when transforming from the left edge', () => { + // Todo + }) + + describe('when transforming a group', () => { + it('transforms the groups children', () => { + const tlstate = new TLDrawState() + tlstate + .loadDocument(mockDocument) + .group(['rect1', 'rect2'], 'groupA') + .select('groupA') + .startTransformSession([0, 0], TLBoundsCorner.TopLeft) + .updateTransformSession([10, 10]) + .completeSession() + + expect(getShapeBounds(tlstate, 'rect1')).toMatchObject({ + minX: 10, + minY: 10, + maxX: 105, + maxY: 105, + width: 95, + height: 95, + }) + + expect(getShapeBounds(tlstate, 'rect2')).toMatchObject({ + minX: 105, + minY: 105, + maxX: 200, + maxY: 200, + width: 95, + height: 95, + }) + }) + }) +}) diff --git a/packages/tldraw/src/state/session/sessions/transform/transform.session.ts b/packages/tldraw/src/state/session/sessions/transform/transform.session.ts new file mode 100644 index 000000000..d68fc2216 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/transform/transform.session.ts @@ -0,0 +1,185 @@ +import { TLBoundsCorner, TLBoundsEdge, Utils, Vec } from '@tldraw/core' +import { Session, TLDrawShape, TLDrawStatus } from '~types' +import type { Data } from '~types' +import { TLDR } from '~state/tldr' + +export class TransformSession implements Session { + id = 'transform' + status = TLDrawStatus.Transforming + scaleX = 1 + scaleY = 1 + transformType: TLBoundsEdge | TLBoundsCorner + origin: number[] + snapshot: TransformSnapshot + + constructor( + data: Data, + point: number[], + transformType: TLBoundsEdge | TLBoundsCorner = TLBoundsCorner.BottomRight + ) { + this.origin = point + this.transformType = transformType + this.snapshot = getTransformSnapshot(data, transformType) + } + + start = () => void null + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + update = (data: Data, point: number[], isAspectRatioLocked = false, _altKey = false) => { + const { + transformType, + snapshot: { shapeBounds, initialBounds, isAllAspectRatioLocked }, + } = this + + const shapes = {} as Record + + const pageState = TLDR.getPageState(data, data.appState.currentPageId) + + const newBoundingBox = Utils.getTransformedBoundingBox( + initialBounds, + transformType, + Vec.sub(point, this.origin), + pageState.boundsRotation, + isAspectRatioLocked || isAllAspectRatioLocked + ) + + // Now work backward to calculate a new bounding box for each of the shapes. + + this.scaleX = newBoundingBox.scaleX + this.scaleY = newBoundingBox.scaleY + + shapeBounds.forEach(({ id, initialShape, initialShapeBounds, transformOrigin }) => { + const newShapeBounds = Utils.getRelativeTransformedBoundingBox( + newBoundingBox, + initialBounds, + initialShapeBounds, + this.scaleX < 0, + this.scaleY < 0 + ) + + shapes[id] = TLDR.transform( + data, + TLDR.getShape(data, id, data.appState.currentPageId), + newShapeBounds, + { + type: this.transformType, + initialShape, + scaleX: this.scaleX, + scaleY: this.scaleY, + transformOrigin, + }, + data.appState.currentPageId + ) + }) + + return { + document: { + pages: { + [data.appState.currentPageId]: { + shapes, + }, + }, + }, + } + } + + cancel = (data: Data) => { + const { shapeBounds } = this.snapshot + + const shapes = {} as Record + + shapeBounds.forEach((shape) => (shapes[shape.id] = shape.initialShape)) + + return { + document: { + pages: { + [data.appState.currentPageId]: { + shapes, + }, + }, + }, + } + } + + complete(data: Data) { + const { hasUnlockedShapes, shapeBounds } = this.snapshot + + if (!hasUnlockedShapes) return data + + const beforeShapes = {} as Record + const afterShapes = {} as Record + + shapeBounds.forEach((shape) => { + beforeShapes[shape.id] = shape.initialShape + afterShapes[shape.id] = TLDR.getShape(data, shape.id, data.appState.currentPageId) + }) + + return { + id: 'transform', + before: { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: beforeShapes, + }, + }, + }, + }, + after: { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: afterShapes, + }, + }, + }, + }, + } + } +} + +export function getTransformSnapshot(data: Data, transformType: TLBoundsEdge | TLBoundsCorner) { + const initialShapes = TLDR.getSelectedBranchSnapshot(data, data.appState.currentPageId) + + const hasUnlockedShapes = initialShapes.length > 0 + + const isAllAspectRatioLocked = initialShapes.every( + (shape) => shape.isAspectRatioLocked || TLDR.getShapeUtils(shape).isAspectRatioLocked + ) + + const shapesBounds = Object.fromEntries( + initialShapes.map((shape) => [shape.id, TLDR.getBounds(shape)]) + ) + + const boundsArr = Object.values(shapesBounds) + + const commonBounds = Utils.getCommonBounds(boundsArr) + + const initialInnerBounds = Utils.getBoundsFromPoints(boundsArr.map(Utils.getBoundsCenter)) + + // Return a mapping of shapes to bounds together with the relative + // positions of the shape's bounds within the common bounds shape. + return { + type: transformType, + hasUnlockedShapes, + isAllAspectRatioLocked, + initialShapes, + initialBounds: commonBounds, + shapeBounds: initialShapes.map((shape) => { + const initialShapeBounds = shapesBounds[shape.id] + const ic = Utils.getBoundsCenter(initialShapeBounds) + + const ix = (ic[0] - initialInnerBounds.minX) / initialInnerBounds.width + const iy = (ic[1] - initialInnerBounds.minY) / initialInnerBounds.height + + return { + id: shape.id, + initialShape: shape, + initialShapeBounds, + transformOrigin: [ix, iy], + } + }), + } +} + +export type TransformSnapshot = ReturnType diff --git a/packages/tldraw/src/state/session/sessions/translate/index.ts b/packages/tldraw/src/state/session/sessions/translate/index.ts new file mode 100644 index 000000000..65826ded9 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/translate/index.ts @@ -0,0 +1 @@ +export * from './translate.session' diff --git a/packages/tldraw/src/state/session/sessions/translate/translate.session.spec.ts b/packages/tldraw/src/state/session/sessions/translate/translate.session.spec.ts new file mode 100644 index 000000000..f3c4d614f --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/translate/translate.session.spec.ts @@ -0,0 +1,231 @@ +import { TLDrawState } from '~state' +import { mockDocument } from '~test' +import { TLDrawShapeType, TLDrawStatus } from '~types' + +describe('Translate session', () => { + const tlstate = new TLDrawState() + + it('begins, updates and completes session', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1') + .startTranslateSession([5, 5]) + .updateTranslateSession([10, 10]) + + expect(tlstate.getShape('rect1').point).toStrictEqual([5, 5]) + + tlstate.completeSession() + + expect(tlstate.appState.status.current).toBe(TLDrawStatus.Idle) + + expect(tlstate.getShape('rect1').point).toStrictEqual([5, 5]) + + tlstate.undo() + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + + tlstate.redo() + + expect(tlstate.getShape('rect1').point).toStrictEqual([5, 5]) + }) + + it('cancels session', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1', 'rect2') + .startTranslateSession([5, 5]) + .updateTranslateSession([10, 10]) + .cancelSession() + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + }) + + it('moves a single shape', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1') + .startTranslateSession([10, 10]) + .updateTranslateSession([20, 20]) + .completeSession() + + expect(tlstate.getShape('rect1').point).toStrictEqual([10, 10]) + }) + + it('moves a single shape along a locked axis', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1') + .startTranslateSession([10, 10]) + .updateTranslateSession([20, 20], true) + .completeSession() + + expect(tlstate.getShape('rect1').point).toStrictEqual([10, 0]) + }) + + it('moves two shapes', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1', 'rect2') + .startTranslateSession([10, 10]) + .updateTranslateSession([20, 20]) + .completeSession() + + expect(tlstate.getShape('rect1').point).toStrictEqual([10, 10]) + expect(tlstate.getShape('rect2').point).toStrictEqual([110, 110]) + }) + + it('undos and redos clones', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1', 'rect2') + .startTranslateSession([10, 10]) + .updateTranslateSession([20, 20], false, true) + .completeSession() + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + expect(tlstate.getShape('rect2').point).toStrictEqual([100, 100]) + + expect(Object.keys(tlstate.getPage().shapes).length).toBe(5) + + tlstate.undo() + + expect(Object.keys(tlstate.getPage().shapes).length).toBe(3) + + tlstate.redo() + + expect(Object.keys(tlstate.getPage().shapes).length).toBe(5) + }) + + it('clones shapes', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1', 'rect2') + .startTranslateSession([10, 10]) + .updateTranslateSession([20, 20], false, true) + .completeSession() + + expect(tlstate.getShape('rect1').point).toStrictEqual([0, 0]) + expect(tlstate.getShape('rect2').point).toStrictEqual([100, 100]) + + expect(Object.keys(tlstate.getPage().shapes).length).toBe(5) + }) + + it('destroys clones when last update is not cloning', () => { + tlstate.resetDocument().loadDocument(mockDocument) + + expect(Object.keys(tlstate.getPage().shapes).length).toBe(3) + + tlstate + .select('rect1', 'rect2') + .startTranslateSession([10, 10]) + .updateTranslateSession([20, 20], false, true) + + expect(Object.keys(tlstate.getPage().shapes).length).toBe(5) + + tlstate.updateTranslateSession([30, 30], false, false) + + expect(Object.keys(tlstate.getPage().shapes).length).toBe(3) + + tlstate.completeSession() + + // Original position + delta + expect(tlstate.getShape('rect1').point).toStrictEqual([30, 30]) + expect(tlstate.getShape('rect2').point).toStrictEqual([130, 130]) + + expect(Object.keys(tlstate.page.shapes)).toStrictEqual(['rect1', 'rect2', 'rect3']) + }) + + it('destroys bindings from the translating shape', () => { + tlstate + .loadDocument(mockDocument) + .selectAll() + .delete() + .createShapes( + { + id: 'target1', + type: TLDrawShapeType.Rectangle, + parentId: 'page1', + point: [0, 0], + size: [100, 100], + }, + { + id: 'arrow1', + type: TLDrawShapeType.Arrow, + parentId: 'page1', + point: [200, 200], + } + ) + .select('arrow1') + .startHandleSession([200, 200], 'start') + .updateHandleSession([50, 50]) + .completeSession() + + expect(tlstate.bindings.length).toBe(1) + + tlstate + .select('arrow1') + .startTranslateSession([10, 10]) + .updateTranslateSession([30, 30]) + .completeSession() + + // expect(tlstate.bindings.length).toBe(0) + // expect(tlstate.getShape('arrow1').handles.start.bindingId).toBe(undefined) + + // tlstate.undo() + + // expect(tlstate.bindings.length).toBe(1) + // expect(tlstate.getShape('arrow1').handles.start.bindingId).toBeTruthy() + + // tlstate.redo() + + // expect(tlstate.bindings.length).toBe(0) + // expect(tlstate.getShape('arrow1').handles.start.bindingId).toBe(undefined) + }) + + // it.todo('clones a shape with a parent shape') + + describe('when translating a shape with children', () => { + it('translates the shapes children', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1', 'rect2') + .group() + .startTranslateSession([10, 10]) + .updateTranslateSession([20, 20], false, false) + .completeSession() + }) + + it('clones the shapes and children', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1', 'rect2') + .group() + .startTranslateSession([10, 10]) + .updateTranslateSession([20, 20], false, true) + .completeSession() + }) + + it('deletes clones when not cloning anymore', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1', 'rect2') + .group() + .startTranslateSession([10, 10]) + .updateTranslateSession([20, 20], false, true) + .updateTranslateSession([20, 20], false, false) + .updateTranslateSession([20, 20], false, true) + .completeSession() + }) + + it('clones the shapes and children when selecting a group and a different shape', () => { + tlstate + .loadDocument(mockDocument) + .select('rect1', 'rect2') + .group(['rect1', 'rect2'], 'groupA') + .select('groupA', 'rect3') + .startTranslateSession([10, 10]) + .updateTranslateSession([20, 20], false, true) + .completeSession() + }) + }) +}) diff --git a/packages/tldraw/src/state/session/sessions/translate/translate.session.ts b/packages/tldraw/src/state/session/sessions/translate/translate.session.ts new file mode 100644 index 000000000..31cf91989 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/translate/translate.session.ts @@ -0,0 +1,443 @@ +/* eslint-disable @typescript-eslint/no-non-null-assertion */ +import { TLPageState, Utils, Vec } from '@tldraw/core' +import { + TLDrawShape, + TLDrawBinding, + Session, + Data, + TLDrawCommand, + TLDrawStatus, + ArrowShape, +} from '~types' +import { TLDR } from '~state/tldr' +import type { Patch } from 'rko' + +export class TranslateSession implements Session { + id = 'translate' + status = TLDrawStatus.Translating + delta = [0, 0] + prev = [0, 0] + origin: number[] + snapshot: TranslateSnapshot + isCloning = false + + constructor(data: Data, point: number[]) { + this.origin = point + this.snapshot = getTranslateSnapshot(data) + } + + start = (data: Data) => { + const { bindingsToDelete } = this.snapshot + + if (bindingsToDelete.length === 0) return data + + const nextBindings: Patch> = {} + + bindingsToDelete.forEach((binding) => (nextBindings[binding.id] = undefined)) + + return { + document: { + pages: { + [data.appState.currentPageId]: { + bindings: nextBindings, + }, + }, + }, + } + } + + update = (data: Data, point: number[], isAligned = false, isCloning = false) => { + const { selectedIds, initialParentChildren, clones, initialShapes, bindingsToDelete } = + this.snapshot + + const { currentPageId } = data.appState + const nextBindings: Patch> = {} + const nextShapes: Patch> = {} + const nextPageState: Patch = {} + + const delta = Vec.sub(point, this.origin) + + if (isAligned) { + if (Math.abs(delta[0]) < Math.abs(delta[1])) { + delta[0] = 0 + } else { + delta[1] = 0 + } + } + + const trueDelta = Vec.sub(delta, this.prev) + + this.delta = delta + this.prev = delta + + // If cloning... + if (isCloning) { + // Not Cloning -> Cloning + if (!this.isCloning) { + this.isCloning = true + + // Put back any bindings we deleted + bindingsToDelete.forEach((binding) => (nextBindings[binding.id] = binding)) + + // Move original shapes back to start + initialShapes.forEach((shape) => (nextShapes[shape.id] = { point: shape.point })) + + // Add the clones to the page + clones.forEach((clone) => { + nextShapes[clone.id] = { ...clone, point: Vec.round(Vec.add(clone.point, delta)) } + + // Add clones to non-selected parents + if ( + clone.parentId !== data.appState.currentPageId && + !selectedIds.includes(clone.parentId) + ) { + const children = + nextShapes[clone.parentId]?.children || initialParentChildren[clone.parentId] + + if (!children.includes(clone.id)) { + nextShapes[clone.parentId] = { + ...nextShapes[clone.parentId], + children: [...children, clone.id], + } + } + } + }) + + // Add the cloned bindings + for (const binding of this.snapshot.clonedBindings) { + nextBindings[binding.id] = binding + } + + // Set the selected ids to the clones + nextPageState.selectedIds = clones.map((clone) => clone.id) + } + + // Either way, move the clones + clones.forEach((shape) => { + const current = (nextShapes[shape.id] || + TLDR.getShape(data, shape.id, data.appState.currentPageId)) as TLDrawShape + + if (!current.point) throw Error('No point on that clone!') + + nextShapes[shape.id] = { + ...nextShapes[shape.id], + point: Vec.round(Vec.add(current.point, trueDelta)), + } + }) + } else { + // If not cloning... + + // Cloning -> Not Cloning + if (this.isCloning) { + this.isCloning = false + + // Delete the bindings + + bindingsToDelete.forEach((binding) => (nextBindings[binding.id] = undefined)) + + // Delete the clones + clones.forEach((clone) => { + nextShapes[clone.id] = undefined + if (clone.parentId !== currentPageId) { + nextShapes[clone.parentId] = { + ...nextShapes[clone.parentId], + children: initialParentChildren[clone.parentId], + } + } + }) + + // Move the original shapes back to the cursor position + initialShapes.forEach((shape) => { + nextShapes[shape.id] = { + point: Vec.round(Vec.add(shape.point, delta)), + } + }) + + // Delete the cloned bindings + for (const binding of this.snapshot.clonedBindings) { + nextBindings[binding.id] = undefined + } + + // Set selected ids + nextPageState.selectedIds = initialShapes.map((shape) => shape.id) + } + + // Move the shapes by the delta + initialShapes.forEach((shape) => { + const current = (nextShapes[shape.id] || + TLDR.getShape(data, shape.id, data.appState.currentPageId)) as TLDrawShape + + if (!current.point) throw Error('No point on that clone!') + + nextShapes[shape.id] = { + ...nextShapes[shape.id], + point: Vec.round(Vec.add(current.point, trueDelta)), + } + }) + } + + return { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: nextShapes, + bindings: nextBindings, + }, + }, + pageStates: { + [data.appState.currentPageId]: nextPageState, + }, + }, + } + } + + cancel = (data: Data) => { + const { initialShapes, clones, clonedBindings, bindingsToDelete } = this.snapshot + + const nextBindings: Record | undefined> = {} + const nextShapes: Record | undefined> = {} + const nextPageState: Partial = {} + + // Put back any deleted bindings + bindingsToDelete.forEach((binding) => (nextBindings[binding.id] = binding)) + + // Put initial shapes back to where they started + initialShapes.forEach(({ id, point }) => (nextShapes[id] = { ...nextShapes[id], point })) + + // Delete clones + clones.forEach((clone) => (nextShapes[clone.id] = undefined)) + + // Delete cloned bindings + clonedBindings.forEach((binding) => (nextBindings[binding.id] = undefined)) + + nextPageState.selectedIds = this.snapshot.selectedIds + + return { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: nextShapes, + bindings: nextBindings, + }, + }, + pageStates: { + [data.appState.currentPageId]: nextPageState, + }, + }, + } + } + + complete(data: Data): TLDrawCommand { + const pageId = data.appState.currentPageId + + const { initialShapes, bindingsToDelete, clones, clonedBindings } = this.snapshot + + const beforeBindings: Patch> = {} + const beforeShapes: Patch> = {} + + const afterBindings: Patch> = {} + const afterShapes: Patch> = {} + + clones.forEach((clone) => { + beforeShapes[clone.id] = undefined + afterShapes[clone.id] = this.isCloning ? TLDR.getShape(data, clone.id, pageId) : undefined + }) + + initialShapes.forEach((shape) => { + beforeShapes[shape.id] = { point: shape.point } + afterShapes[shape.id] = { point: TLDR.getShape(data, shape.id, pageId).point } + }) + + clonedBindings.forEach((binding) => { + beforeBindings[binding.id] = undefined + afterBindings[binding.id] = TLDR.getBinding(data, binding.id, pageId) + }) + + bindingsToDelete.forEach((binding) => { + beforeBindings[binding.id] = binding + + for (const id of [binding.toId, binding.fromId]) { + // Let's also look at the bound shape... + const shape = TLDR.getShape(data, id, pageId) + + // If the bound shape has a handle that references the deleted binding, delete that reference + if (!shape.handles) continue + + Object.values(shape.handles) + .filter((handle) => handle.bindingId === binding.id) + .forEach((handle) => { + beforeShapes[id] = { ...beforeShapes[id], handles: {} } + + afterShapes[id] = { ...afterShapes[id], handles: {} } + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + beforeShapes[id]!.handles![handle.id as keyof ArrowShape['handles']] = { + bindingId: binding.id, + } + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + afterShapes[id]!.handles![handle.id as keyof ArrowShape['handles']] = { + bindingId: undefined, + } + }) + } + }) + + return { + id: 'translate', + before: { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: beforeShapes, + bindings: beforeBindings, + }, + }, + pageStates: { + [data.appState.currentPageId]: { + selectedIds: [...this.snapshot.selectedIds], + }, + }, + }, + }, + after: { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: afterShapes, + bindings: afterBindings, + }, + }, + pageStates: { + [data.appState.currentPageId]: { + selectedIds: [...TLDR.getSelectedIds(data, data.appState.currentPageId)], + }, + }, + }, + }, + } + } +} + +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +export function getTranslateSnapshot(data: Data) { + const { currentPageId } = data.appState + const selectedIds = TLDR.getSelectedIds(data, currentPageId) + const page = TLDR.getPage(data, currentPageId) + + const selectedShapes = selectedIds.flatMap((id) => TLDR.getShape(data, id, currentPageId)) + + const hasUnlockedShapes = selectedShapes.length > 0 + + const shapesToMove: TLDrawShape[] = selectedShapes + .filter((shape) => !selectedIds.includes(shape.parentId)) + .flatMap((shape) => { + return shape.children + ? [shape, ...shape.children!.map((childId) => TLDR.getShape(data, childId, currentPageId))] + : [shape] + }) + + const initialParentChildren: Record = {} + + Array.from(new Set(shapesToMove.map((s) => s.parentId)).values()) + .filter((id) => id !== page.id) + .forEach((id) => { + const shape = TLDR.getShape(data, id, currentPageId) + initialParentChildren[id] = shape.children! + }) + + const cloneMap: Record = {} + const clonedBindingsMap: Record = {} + const clonedBindings: TLDrawBinding[] = [] + + // Create clones of selected shapes + const clones: TLDrawShape[] = [] + + shapesToMove.forEach((shape) => { + const newId = Utils.uniqueId() + + initialParentChildren[newId] = initialParentChildren[shape.id] + + cloneMap[shape.id] = newId + + clones.push({ + ...Utils.deepClone(shape), + id: newId, + parentId: shape.parentId, + childIndex: TLDR.getChildIndexAbove(data, shape.id, currentPageId), + }) + }) + + clones.forEach((clone) => { + if (clone.children !== undefined) { + clone.children = clone.children.map((childId) => cloneMap[childId]) + } + }) + + clones.forEach((clone) => { + if (selectedIds.includes(clone.parentId)) { + clone.parentId = cloneMap[clone.parentId] + } + }) + + // Potentially confusing name here: these are the ids of the + // original shapes that were cloned, not their clones' ids. + const clonedShapeIds = Object.keys(cloneMap) + + const bindingsToDelete: TLDrawBinding[] = [] + + // Create cloned bindings for shapes where both to and from shapes are selected + // (if the user clones, then we will create a new binding for the clones) + Object.values(page.bindings).forEach((binding) => { + if (clonedShapeIds.includes(binding.fromId)) { + if (clonedShapeIds.includes(binding.toId)) { + const cloneId = Utils.uniqueId() + const cloneBinding = { + ...Utils.deepClone(binding), + id: cloneId, + fromId: cloneMap[binding.fromId] || binding.fromId, + toId: cloneMap[binding.toId] || binding.toId, + } + + clonedBindingsMap[binding.id] = cloneId + clonedBindings.push(cloneBinding) + } else { + bindingsToDelete.push(binding) + } + } + }) + + // Assign new binding ids to clones (or delete them!) + clones.forEach((clone) => { + if (clone.handles) { + if (clone.handles) { + for (const id in clone.handles) { + const handle = clone.handles[id as keyof ArrowShape['handles']] + handle.bindingId = handle.bindingId ? clonedBindingsMap[handle.bindingId] : undefined + } + } + } + }) + + clones.forEach((clone) => { + if (page.shapes[clone.id]) { + throw Error("uh oh, we didn't clone correctly") + } + }) + + return { + selectedIds, + bindingsToDelete, + hasUnlockedShapes, + initialParentChildren, + initialShapes: shapesToMove.map(({ id, point, parentId }) => ({ + id, + point, + parentId, + })), + clones, + clonedBindings, + } +} + +export type TranslateSnapshot = ReturnType diff --git a/packages/tldraw/src/state/tldr.ts b/packages/tldraw/src/state/tldr.ts new file mode 100644 index 000000000..232858af3 --- /dev/null +++ b/packages/tldraw/src/state/tldr.ts @@ -0,0 +1,895 @@ +import { TLBounds, TLTransformInfo, Vec, Utils, TLPageState } from '@tldraw/core' +import { getShapeUtils } from '~shape' +import type { + Data, + ShapeStyles, + ShapesWithProp, + TLDrawShape, + TLDrawShapeUtil, + TLDrawBinding, + TLDrawPage, + TLDrawCommand, + TLDrawPatch, +} from '~types' + +export class TLDR { + static getShapeUtils(shape: T | T['type']): TLDrawShapeUtil { + return getShapeUtils(typeof shape === 'string' ? ({ type: shape } as T) : shape) + } + + static getSelectedShapes(data: Data, pageId: string) { + const page = this.getPage(data, pageId) + const selectedIds = this.getSelectedIds(data, pageId) + return selectedIds.map((id) => page.shapes[id]) + } + + static screenToWorld(data: Data, point: number[]) { + const camera = this.getPageState(data, data.appState.currentPageId).camera + return Vec.sub(Vec.div(point, camera.zoom), camera.point) + } + + static getViewport(data: Data): TLBounds { + const [minX, minY] = this.screenToWorld(data, [0, 0]) + const [maxX, maxY] = this.screenToWorld(data, [window.innerWidth, window.innerHeight]) + + return { + minX, + minY, + maxX, + maxY, + height: maxX - minX, + width: maxY - minY, + } + } + + static getCameraZoom(zoom: number) { + return Utils.clamp(zoom, 0.1, 5) + } + + static getPage(data: Data, pageId: string): TLDrawPage { + return data.document.pages[pageId] + } + + static getPageState(data: Data, pageId: string): TLPageState { + return data.document.pageStates[pageId] + } + + static getSelectedIds(data: Data, pageId: string): string[] { + return this.getPageState(data, pageId).selectedIds + } + + static getShapes(data: Data, pageId: string): TLDrawShape[] { + return Object.values(this.getPage(data, pageId).shapes) + } + + static getCamera(data: Data, pageId: string): TLPageState['camera'] { + return this.getPageState(data, pageId).camera + } + + static getShape( + data: Data, + shapeId: string, + pageId: string + ): T { + return this.getPage(data, pageId).shapes[shapeId] as T + } + + static getBounds(shape: T) { + return getShapeUtils(shape).getBounds(shape) + } + + static getRotatedBounds(shape: T) { + return getShapeUtils(shape).getRotatedBounds(shape) + } + + static getSelectedBounds(data: Data): TLBounds { + return Utils.getCommonBounds( + this.getSelectedShapes(data, data.appState.currentPageId).map((shape) => + getShapeUtils(shape).getBounds(shape) + ) + ) + } + + static getParentId(data: Data, id: string, pageId: string) { + return this.getShape(data, id, pageId).parentId + } + + static getPointedId(data: Data, id: string, pageId: string): string { + const page = this.getPage(data, pageId) + const pageState = this.getPageState(data, data.appState.currentPageId) + const shape = this.getShape(data, id, pageId) + if (!shape) return id + + return shape.parentId === pageState.currentParentId || shape.parentId === page.id + ? id + : this.getPointedId(data, shape.parentId, pageId) + } + + static getDrilledPointedId(data: Data, id: string, pageId: string): string { + const shape = this.getShape(data, id, pageId) + const { currentPageId } = data.appState + const { currentParentId, pointedId } = this.getPageState(data, data.appState.currentPageId) + + return shape.parentId === currentPageId || + shape.parentId === pointedId || + shape.parentId === currentParentId + ? id + : this.getDrilledPointedId(data, shape.parentId, pageId) + } + + static getTopParentId(data: Data, id: string, pageId: string): string { + const page = this.getPage(data, pageId) + const pageState = this.getPageState(data, pageId) + const shape = this.getShape(data, id, pageId) + + if (shape.parentId === shape.id) { + throw Error(`Shape has the same id as its parent! ${shape.id}`) + } + + return shape.parentId === page.id || shape.parentId === pageState.currentParentId + ? id + : this.getTopParentId(data, shape.parentId, pageId) + } + + // Get an array of a shape id and its descendant shapes' ids + static getDocumentBranch(data: Data, id: string, pageId: string): string[] { + const shape = this.getShape(data, id, pageId) + + if (shape.children === undefined) return [id] + + return [ + id, + ...shape.children.flatMap((childId) => this.getDocumentBranch(data, childId, pageId)), + ] + } + + // Get a deep array of unproxied shapes and their descendants + static getSelectedBranchSnapshot( + data: Data, + pageId: string, + fn: (shape: TLDrawShape) => K + ): ({ id: string } & K)[] + static getSelectedBranchSnapshot(data: Data, pageId: string): TLDrawShape[] + static getSelectedBranchSnapshot( + data: Data, + pageId: string, + fn?: (shape: TLDrawShape) => K + ): (TLDrawShape | K)[] { + const page = this.getPage(data, pageId) + + const copies = this.getSelectedIds(data, pageId) + .flatMap((id) => this.getDocumentBranch(data, id, pageId).map((id) => page.shapes[id])) + .filter((shape) => !shape.isLocked) + .map(Utils.deepClone) + + if (fn !== undefined) { + return copies.map((shape) => ({ id: shape.id, ...fn(shape) })) + } + + return copies + } + + // Get a shallow array of unproxied shapes + static getSelectedShapeSnapshot(data: Data, pageId: string): TLDrawShape[] + static getSelectedShapeSnapshot( + data: Data, + pageId: string, + fn?: (shape: TLDrawShape) => K + ): ({ id: string } & K)[] + static getSelectedShapeSnapshot( + data: Data, + pageId: string, + fn?: (shape: TLDrawShape) => K + ): (TLDrawShape | K)[] { + const copies = this.getSelectedShapes(data, pageId) + .filter((shape) => !shape.isLocked) + .map(Utils.deepClone) + + if (fn !== undefined) { + return copies.map((shape) => ({ id: shape.id, ...fn(shape) })) + } + + return copies + } + + // For a given array of shape ids, an array of all other shapes that may be affected by a mutation to it. + // Use this to decide which shapes to clone as before / after for a command. + static getAllEffectedShapeIds(data: Data, ids: string[], pageId: string): string[] { + const page = this.getPage(data, pageId) + + const visited = new Set(ids) + + ids.forEach((id) => { + const shape = page.shapes[id] + + // Add descendant shapes + function collectDescendants(shape: TLDrawShape): void { + if (shape.children === undefined) return + shape.children + .filter((childId) => !visited.has(childId)) + .forEach((childId) => { + visited.add(childId) + collectDescendants(page.shapes[childId]) + }) + } + + collectDescendants(shape) + + // Add asecendant shapes + function collectAscendants(shape: TLDrawShape): void { + const parentId = shape.parentId + if (parentId === page.id) return + if (visited.has(parentId)) return + visited.add(parentId) + collectAscendants(page.shapes[parentId]) + } + + collectAscendants(shape) + + // Add bindings that are to or from any of the visited shapes (this does not have to be recursive) + visited.forEach((id) => { + Object.values(page.bindings) + .filter((binding) => binding.fromId === id || binding.toId === id) + .forEach((binding) => visited.add(binding.fromId === id ? binding.toId : binding.fromId)) + }) + }) + + // Return the unique array of visited shapes + return Array.from(visited.values()) + } + + static recursivelyUpdateChildren( + data: Data, + id: string, + beforeShapes: Record> = {}, + afterShapes: Record> = {}, + pageId: string + ): Data { + const page = this.getPage(data, pageId) + const shape = page.shapes[id] as T + + if (shape.children !== undefined) { + const deltas = this.getShapeUtils(shape).updateChildren( + shape, + shape.children.map((childId) => page.shapes[childId]) + ) + + if (deltas) { + return deltas.reduce((cData, delta) => { + if (!delta.id) throw Error('Delta must include an id!') + const cPage = this.getPage(cData, pageId) + const deltaShape = this.getShape(cData, delta.id, pageId) + + if (!beforeShapes[delta.id]) { + beforeShapes[delta.id] = deltaShape + } + cPage.shapes[delta.id] = this.getShapeUtils(deltaShape).mutate(deltaShape, delta) + afterShapes[delta.id] = cPage.shapes[delta.id] + + if (deltaShape.children !== undefined) { + this.recursivelyUpdateChildren(cData, delta.id, beforeShapes, afterShapes, pageId) + } + + return cData + }, data) + } + } + + return data + } + + static recursivelyUpdateParents( + data: Data, + id: string, + beforeShapes: Record> = {}, + afterShapes: Record> = {}, + pageId: string + ): Data { + const page = { ...this.getPage(data, pageId) } + const shape = this.getShape(data, id, pageId) + + if (page.id === 'doc') { + throw Error('wtf') + } + + if (shape.parentId !== page.id) { + const parent = this.getShape(data, shape.parentId, pageId) + + if (!parent.children) throw Error('No children in parent!') + + const delta = this.getShapeUtils(parent).onChildrenChange( + parent, + parent.children.map((childId) => this.getShape(data, childId, pageId)) + ) + + if (delta) { + if (!beforeShapes[parent.id]) { + beforeShapes[parent.id] = parent + } + page.shapes[parent.id] = this.getShapeUtils(parent).mutate(parent, delta) + afterShapes[parent.id] = page.shapes[parent.id] + } + + if (parent.parentId !== page.id) { + return this.recursivelyUpdateParents( + data, + parent.parentId, + beforeShapes, + afterShapes, + pageId + ) + } + } + + if (data.appState.currentPageId === 'doc') { + console.error('WTF?') + } + + return { + ...data, + document: { + ...data.document, + pages: { + ...data.document.pages, + [page.id]: page, + }, + }, + } + } + + static updateBindings( + data: Data, + id: string, + beforeShapes: Record> = {}, + afterShapes: Record> = {}, + pageId: string + ): Data { + const page = { ...this.getPage(data, pageId) } + return Object.values(page.bindings) + .filter((binding) => binding.fromId === id || binding.toId === id) + .reduce((cData, binding) => { + if (!beforeShapes[binding.fromId]) { + beforeShapes[binding.fromId] = Utils.deepClone( + this.getShape(cData, binding.fromId, pageId) + ) + } + + if (!beforeShapes[binding.toId]) { + beforeShapes[binding.toId] = Utils.deepClone(this.getShape(cData, binding.toId, pageId)) + } + + this.onBindingChange( + cData, + this.getShape(cData, binding.fromId, pageId), + binding, + this.getShape(cData, binding.toId, pageId), + pageId + ) + + afterShapes[binding.fromId] = Utils.deepClone(this.getShape(cData, binding.fromId, pageId)) + afterShapes[binding.toId] = Utils.deepClone(this.getShape(cData, binding.toId, pageId)) + + return cData + }, data) + } + + static getChildIndexAbove(data: Data, id: string, pageId: string): number { + const page = this.getPage(data, pageId) + + const shape = page.shapes[id] + + let siblings: TLDrawShape[] + + if (shape.parentId === page.id) { + siblings = Object.values(page.shapes) + .filter((shape) => shape.parentId === page.id) + .sort((a, b) => a.childIndex - b.childIndex) + } else { + const parent = page.shapes[shape.parentId] + if (!parent.children) throw Error('No children in parent!') + siblings = parent.children + .map((childId) => page.shapes[childId]) + .sort((a, b) => a.childIndex - b.childIndex) + } + + const index = siblings.indexOf(shape) + + const nextSibling = siblings[index + 1] + + if (!nextSibling) return shape.childIndex + 1 + + return (shape.childIndex + nextSibling.childIndex) / 2 + } + + /* -------------------------------------------------- */ + /* Mutations */ + /* -------------------------------------------------- */ + + static mutateShapes( + data: Data, + ids: string[], + fn: (shape: T, i: number) => Partial, + pageId: string + ): { + before: Record> + after: Record> + data: Data + } { + const beforeShapes: Record> = {} + const afterShapes: Record> = {} + + ids.forEach((id, i) => { + const shape = this.getShape(data, id, pageId) + const change = fn(shape, i) + beforeShapes[id] = Object.fromEntries( + Object.keys(change).map((key) => [key, shape[key as keyof T]]) + ) as Partial + afterShapes[id] = change + }) + + const dataWithMutations = Utils.deepMerge(data, { + document: { + pages: { + [data.appState.currentPageId]: { + shapes: afterShapes, + }, + }, + }, + }) + + const dataWithChildrenChanges = ids.reduce((cData, id) => { + return this.recursivelyUpdateChildren(cData, id, beforeShapes, afterShapes, pageId) + }, dataWithMutations) + + const dataWithParentChanges = ids.reduce((cData, id) => { + return this.recursivelyUpdateParents(cData, id, beforeShapes, afterShapes, pageId) + }, dataWithChildrenChanges) + + const dataWithBindingChanges = ids.reduce((cData, id) => { + return this.updateBindings(cData, id, beforeShapes, afterShapes, pageId) + }, dataWithParentChanges) + + return { + before: beforeShapes, + after: afterShapes, + data: dataWithBindingChanges, + } + } + + static createShapes(data: Data, shapes: TLDrawShape[], pageId: string): TLDrawCommand { + const before: TLDrawPatch = { + document: { + pages: { + [pageId]: { + shapes: { + ...Object.fromEntries( + shapes.flatMap((shape) => { + const results: [string, Partial | undefined][] = [ + [shape.id, undefined], + ] + + // If the shape is a child of another shape, also save that shape + if (shape.parentId !== pageId) { + const parent = this.getShape(data, shape.parentId, pageId) + if (!parent.children) throw Error('No children in parent!') + results.push([parent.id, { children: parent.children }]) + } + + return results + }) + ), + }, + }, + }, + }, + } + + const after: TLDrawPatch = { + document: { + pages: { + [pageId]: { + shapes: { + shapes: { + ...Object.fromEntries( + shapes.flatMap((shape) => { + const results: [string, Partial | undefined][] = [ + [shape.id, shape], + ] + + // If the shape is a child of a different shape, update its parent + if (shape.parentId !== pageId) { + const parent = this.getShape(data, shape.parentId, pageId) + if (!parent.children) throw Error('No children in parent!') + results.push([parent.id, { children: [...parent.children, shape.id] }]) + } + + return results + }) + ), + }, + }, + }, + }, + }, + } + + return { + before, + after, + } + } + + static deleteShapes( + data: Data, + shapes: TLDrawShape[] | string[], + pageId?: string + ): TLDrawCommand { + pageId = pageId ? pageId : data.appState.currentPageId + + const page = this.getPage(data, pageId) + + const shapeIds = + typeof shapes[0] === 'string' + ? (shapes as string[]) + : (shapes as TLDrawShape[]).map((shape) => shape.id) + + const before: TLDrawPatch = { + document: { + pages: { + [pageId]: { + shapes: { + // These are the shapes that we're going to delete + ...Object.fromEntries( + shapeIds.flatMap((id) => { + const shape = page.shapes[id] + const results: [string, Partial | undefined][] = [[shape.id, shape]] + + // If the shape is a child of another shape, also add that shape + if (shape.parentId !== pageId) { + const parent = page.shapes[shape.parentId] + if (!parent.children) throw Error('No children in parent!') + results.push([parent.id, { children: parent.children }]) + } + + return results + }) + ), + }, + bindings: { + // These are the bindings that we're going to delete + ...Object.fromEntries( + Object.values(page.bindings) + .filter((binding) => { + return shapeIds.includes(binding.fromId) || shapeIds.includes(binding.toId) + }) + .map((binding) => { + return [binding.id, binding] + }) + ), + }, + }, + }, + }, + } + + const after: TLDrawPatch = { + document: { + pages: { + [pageId]: { + shapes: { + ...Object.fromEntries( + shapeIds.flatMap((id) => { + const shape = page.shapes[id] + const results: [string, Partial | undefined][] = [ + [shape.id, undefined], + ] + + // If the shape is a child of a different shape, update its parent + if (shape.parentId !== page.id) { + const parent = page.shapes[shape.parentId] + + if (!parent.children) throw Error('No children in parent!') + + results.push([ + parent.id, + { children: parent.children.filter((id) => id !== shape.id) }, + ]) + } + + return results + }) + ), + }, + }, + }, + }, + } + + return { + before, + after, + } + } + + static onSessionComplete(data: Data, shape: T, pageId: string) { + const delta = getShapeUtils(shape).onSessionComplete(shape) + if (!delta) return shape + return this.mutate(data, shape, delta, pageId) + } + + static onChildrenChange(data: Data, shape: T, pageId: string) { + if (!shape.children) return + + const delta = getShapeUtils(shape).onChildrenChange( + shape, + shape.children.map((id) => this.getShape(data, id, pageId)) + ) + if (!delta) return shape + return this.mutate(data, shape, delta, pageId) + } + + static onBindingChange( + data: Data, + shape: T, + binding: TLDrawBinding, + otherShape: TLDrawShape, + pageId: string + ) { + const delta = getShapeUtils(shape).onBindingChange( + shape, + binding, + otherShape, + getShapeUtils(otherShape).getBounds(otherShape), + getShapeUtils(otherShape).getCenter(otherShape) + ) + if (!delta) return shape + return this.mutate(data, shape, delta, pageId) + } + + static transform( + data: Data, + shape: T, + bounds: TLBounds, + info: TLTransformInfo, + pageId: string + ) { + return this.mutate(data, shape, getShapeUtils(shape).transform(shape, bounds, info), pageId) + } + + static transformSingle( + data: Data, + shape: T, + bounds: TLBounds, + info: TLTransformInfo, + pageId: string + ) { + return this.mutate( + data, + shape, + getShapeUtils(shape).transformSingle(shape, bounds, info), + pageId + ) + } + + static mutate(data: Data, shape: T, props: Partial, pageId: string) { + let next = getShapeUtils(shape).mutate(shape, props) + + if (props.children) { + next = this.onChildrenChange(data, next, pageId) || next + } + + return next + } + + /* -------------------------------------------------- */ + /* Parents */ + /* -------------------------------------------------- */ + + static updateParents(data: Data, pageId: string, changedShapeIds: string[]): void { + const page = this.getPage(data, pageId) + + if (changedShapeIds.length === 0) return + + const { shapes } = this.getPage(data, pageId) + + const parentToUpdateIds = Array.from( + new Set(changedShapeIds.map((id) => shapes[id].parentId).values()) + ).filter((id) => id !== page.id) + + for (const parentId of parentToUpdateIds) { + const parent = shapes[parentId] + + if (!parent.children) { + throw Error('A shape is parented to a shape without a children array.') + } + + this.onChildrenChange(data, parent, pageId) + } + + this.updateParents(data, pageId, parentToUpdateIds) + } + + static getSelectedStyle(data: Data, pageId: string): ShapeStyles | false { + const { currentStyle } = data.appState + + const page = data.document.pages[pageId] + const pageState = data.document.pageStates[pageId] + + if (pageState.selectedIds.length === 0) { + return currentStyle + } + + const shapeStyles = pageState.selectedIds.map((id) => page.shapes[id].style) + + const commonStyle = {} as ShapeStyles + + const overrides = new Set([]) + + for (const shapeStyle of shapeStyles) { + const styles = Object.keys(currentStyle) as (keyof ShapeStyles)[] + styles.forEach((key) => { + if (overrides.has(key)) return + if (commonStyle[key] === undefined) { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + commonStyle[key] = shapeStyle[key] + } else { + if (commonStyle[key] === shapeStyle[key]) return + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + commonStyle[key] = currentStyle[key] + overrides.add(key) + } + }) + } + + return commonStyle + } + + /* -------------------------------------------------- */ + /* Bindings */ + /* -------------------------------------------------- */ + + static getBinding(data: Data, id: string, pageId: string): TLDrawBinding { + return this.getPage(data, pageId).bindings[id] + } + + static getBindings(data: Data, pageId: string): TLDrawBinding[] { + const page = this.getPage(data, pageId) + return Object.values(page.bindings) + } + + static getBindableShapeIds(data: Data) { + return this.getShapes(data, data.appState.currentPageId) + .filter((shape) => TLDR.getShapeUtils(shape).canBind) + .sort((a, b) => b.childIndex - a.childIndex) + .map((shape) => shape.id) + } + + static getBindingsWithShapeIds(data: Data, ids: string[], pageId: string): TLDrawBinding[] { + return Array.from( + new Set( + this.getBindings(data, pageId).filter((binding) => { + return ids.includes(binding.toId) || ids.includes(binding.fromId) + }) + ).values() + ) + } + + static getRelatedBindings(data: Data, ids: string[], pageId: string): TLDrawBinding[] { + const changedShapeIds = new Set(ids) + + const page = this.getPage(data, pageId) + + // Find all bindings that we need to update + const bindingsArr = Object.values(page.bindings) + + // Start with bindings that are directly bound to our changed shapes + const bindingsToUpdate = new Set( + bindingsArr.filter( + (binding) => changedShapeIds.has(binding.toId) || changedShapeIds.has(binding.fromId) + ) + ) + + // Next, look for other bindings that effect the same shapes + let prevSize = bindingsToUpdate.size + let delta = -1 + + while (delta !== 0) { + bindingsToUpdate.forEach((binding) => { + const fromId = binding.fromId + + for (const otherBinding of bindingsArr) { + if (otherBinding.fromId === fromId) { + bindingsToUpdate.add(otherBinding) + } + + if (otherBinding.toId === fromId) { + bindingsToUpdate.add(otherBinding) + } + } + }) + + // Continue until we stop finding new bindings to update + delta = bindingsToUpdate.size - prevSize + + prevSize = bindingsToUpdate.size + } + + return Array.from(bindingsToUpdate.values()) + } + + static copyStringToClipboard = (string: string) => { + try { + navigator.clipboard.writeText(string) + } catch (e) { + const textarea = document.createElement('textarea') + textarea.setAttribute('position', 'fixed') + textarea.setAttribute('top', '0') + textarea.setAttribute('readonly', 'true') + textarea.setAttribute('contenteditable', 'true') + textarea.style.position = 'fixed' + textarea.value = string + document.body.appendChild(textarea) + textarea.focus() + textarea.select() + + try { + const range = document.createRange() + range.selectNodeContents(textarea) + const sel = window.getSelection() + if (sel) { + sel.removeAllRanges() + sel.addRange(range) + textarea.setSelectionRange(0, textarea.value.length) + } + } catch (err) { + null // Could not copy to clipboard + } finally { + document.body.removeChild(textarea) + } + } + } + + /* -------------------------------------------------- */ + /* Groups */ + /* -------------------------------------------------- */ + + static flattenShape = (data: Data, shape: TLDrawShape): TLDrawShape[] => { + return [ + shape, + ...(shape.children ?? []) + .map((childId) => TLDR.getShape(data, childId, data.appState.currentPageId)) + .sort((a, b) => a.childIndex - b.childIndex) + .flatMap((shape) => TLDR.flattenShape(data, shape)), + ] + } + + static flattenPage = (data: Data, pageId: string): TLDrawShape[] => { + return Object.values(data.document.pages[pageId].shapes) + .sort((a, b) => a.childIndex - b.childIndex) + .reduce((acc, shape) => [...acc, ...TLDR.flattenShape(data, shape)], []) + } + + static getTopChildIndex = (data: Data, pageId: string): number => { + const shapes = TLDR.getShapes(data, pageId) + return shapes.length === 0 + ? 1 + : shapes + .filter((shape) => shape.parentId === pageId) + .sort((a, b) => b.childIndex - a.childIndex)[0].childIndex + 1 + } + + /* -------------------------------------------------- */ + /* Assertions */ + /* -------------------------------------------------- */ + + static assertShapeHasProperty

( + shape: TLDrawShape, + prop: P + ): asserts shape is ShapesWithProp

{ + if (shape[prop] === undefined) { + throw new Error() + } + } +} diff --git a/packages/tldraw/src/state/tlstate.spec.ts b/packages/tldraw/src/state/tlstate.spec.ts new file mode 100644 index 000000000..ce5bd34cf --- /dev/null +++ b/packages/tldraw/src/state/tlstate.spec.ts @@ -0,0 +1,362 @@ +import { TLDrawState } from './tlstate' +import { mockDocument, TLStateUtils } from '~test' +import { ColorStyle, TLDrawShapeType } from '~types' + +describe('TLDrawState', () => { + const tlstate = new TLDrawState() + + const tlu = new TLStateUtils(tlstate) + + describe('Copy and Paste', () => { + it('copies a shape', () => { + tlstate.loadDocument(mockDocument).deselectAll().copy(['rect1']) + }) + + it('pastes a shape', () => { + tlstate.loadDocument(mockDocument) + + const prevCount = Object.keys(tlstate.page.shapes).length + + tlstate.deselectAll().copy(['rect1']).paste() + + expect(Object.keys(tlstate.page.shapes).length).toBe(prevCount + 1) + + tlstate.undo() + + expect(Object.keys(tlstate.page.shapes).length).toBe(prevCount) + + tlstate.redo() + + expect(Object.keys(tlstate.page.shapes).length).toBe(prevCount + 1) + }) + + it('pastes a shape to a new page', () => { + tlstate.loadDocument(mockDocument) + + tlstate.deselectAll().copy(['rect1']).createPage().paste() + + expect(Object.keys(tlstate.page.shapes).length).toBe(1) + + tlstate.undo() + + expect(Object.keys(tlstate.page.shapes).length).toBe(0) + + tlstate.redo() + + expect(Object.keys(tlstate.page.shapes).length).toBe(1) + }) + }) + + describe('Selection', () => { + it('selects a shape', () => { + tlstate.loadDocument(mockDocument).deselectAll() + tlu.clickShape('rect1') + expect(tlstate.selectedIds).toStrictEqual(['rect1']) + expect(tlstate.appState.status.current).toBe('idle') + }) + + it('selects and deselects a shape', () => { + tlstate.loadDocument(mockDocument).deselectAll() + tlu.clickShape('rect1') + tlu.clickCanvas() + expect(tlstate.selectedIds).toStrictEqual([]) + expect(tlstate.appState.status.current).toBe('idle') + }) + + it('selects multiple shapes', () => { + tlstate.loadDocument(mockDocument).deselectAll() + tlu.clickShape('rect1') + tlu.clickShape('rect2', { shiftKey: true }) + expect(tlstate.selectedIds).toStrictEqual(['rect1', 'rect2']) + expect(tlstate.appState.status.current).toBe('idle') + }) + + it('shift-selects to deselect shapes', () => { + tlstate.loadDocument(mockDocument).deselectAll() + tlu.clickShape('rect1') + tlu.clickShape('rect2', { shiftKey: true }) + tlu.clickShape('rect2', { shiftKey: true }) + expect(tlstate.selectedIds).toStrictEqual(['rect1']) + expect(tlstate.appState.status.current).toBe('idle') + }) + + it('clears selection when clicking bounds', () => { + tlstate.loadDocument(mockDocument).deselectAll() + tlstate.startBrushSession([-10, -10]) + tlstate.updateBrushSession([110, 110]) + tlstate.completeSession() + expect(tlstate.selectedIds.length).toBe(3) + }) + + it('selects selected shape when single-clicked', () => { + tlstate.loadDocument(mockDocument).selectAll() + tlu.clickShape('rect2') + expect(tlstate.selectedIds).toStrictEqual(['rect2']) + }) + + // it('selects shape when double-clicked', () => { + // tlstate.loadDocument(mockDocument).selectAll() + // tlu.doubleClickShape('rect2') + // expect(tlstate.selectedIds).toStrictEqual(['rect2']) + // }) + + it('does not select on meta-click', () => { + tlstate.loadDocument(mockDocument).deselectAll() + tlu.clickShape('rect1', { ctrlKey: true }) + expect(tlstate.selectedIds).toStrictEqual([]) + expect(tlstate.appState.status.current).toBe('idle') + }) + + it.todo('deletes shapes if cancelled during creating') + + it.todo('deletes shapes on undo after creating') + + it.todo('re-creates shapes on redo after creating') + + it.todo('selects all') + + // Single click on a selected shape to select just that shape + + it('single-selects shape in selection on click', () => { + tlstate.deselectAll() + tlu.clickShape('rect1') + tlu.clickShape('rect2', { shiftKey: true }) + tlu.clickShape('rect2') + expect(tlstate.selectedIds).toStrictEqual(['rect2']) + expect(tlstate.appState.status.current).toBe('idle') + }) + + it('single-selects shape in selection on pointerup only', () => { + tlstate.deselectAll() + tlu.clickShape('rect1') + tlu.clickShape('rect2', { shiftKey: true }) + tlu.pointShape('rect2') + expect(tlstate.selectedIds).toStrictEqual(['rect1', 'rect2']) + tlu.stopPointing('rect2') + expect(tlstate.selectedIds).toStrictEqual(['rect2']) + expect(tlstate.appState.status.current).toBe('idle') + }) + + // it('selects shapes if shift key is lifted before pointerup', () => { + // tlstate.deselectAll() + // tlu.clickShape('rect1') + // tlu.pointShape('rect2', { shiftKey: true }) + // expect(tlstate.appState.status.current).toBe('pointingBounds') + // tlu.stopPointing('rect2') + // expect(tlstate.selectedIds).toStrictEqual(['rect2']) + // expect(tlstate.appState.status.current).toBe('idle') + // }) + }) + + describe('Select history', () => { + it('selects, undoes and redoes', () => { + tlstate.reset().loadDocument(mockDocument) + + expect(tlstate.selectHistory.pointer).toBe(0) + expect(tlstate.selectHistory.stack).toStrictEqual([[]]) + expect(tlstate.selectedIds).toStrictEqual([]) + + tlu.pointShape('rect1') + + expect(tlstate.selectHistory.pointer).toBe(1) + expect(tlstate.selectHistory.stack).toStrictEqual([[], ['rect1']]) + expect(tlstate.selectedIds).toStrictEqual(['rect1']) + + tlu.stopPointing('rect1') + + expect(tlstate.selectHistory.pointer).toBe(1) + expect(tlstate.selectHistory.stack).toStrictEqual([[], ['rect1']]) + expect(tlstate.selectedIds).toStrictEqual(['rect1']) + + tlu.clickShape('rect2', { shiftKey: true }) + + expect(tlstate.selectHistory.pointer).toBe(2) + expect(tlstate.selectHistory.stack).toStrictEqual([[], ['rect1'], ['rect1', 'rect2']]) + expect(tlstate.selectedIds).toStrictEqual(['rect1', 'rect2']) + + tlstate.undoSelect() + + expect(tlstate.selectHistory.pointer).toBe(1) + expect(tlstate.selectHistory.stack).toStrictEqual([[], ['rect1'], ['rect1', 'rect2']]) + expect(tlstate.selectedIds).toStrictEqual(['rect1']) + + tlstate.undoSelect() + + expect(tlstate.selectHistory.pointer).toBe(0) + expect(tlstate.selectHistory.stack).toStrictEqual([[], ['rect1'], ['rect1', 'rect2']]) + expect(tlstate.selectedIds).toStrictEqual([]) + + tlstate.redoSelect() + + expect(tlstate.selectHistory.pointer).toBe(1) + expect(tlstate.selectHistory.stack).toStrictEqual([[], ['rect1'], ['rect1', 'rect2']]) + expect(tlstate.selectedIds).toStrictEqual(['rect1']) + + tlstate.select('rect2') + + expect(tlstate.selectHistory.pointer).toBe(2) + expect(tlstate.selectHistory.stack).toStrictEqual([[], ['rect1'], ['rect2']]) + expect(tlstate.selectedIds).toStrictEqual(['rect2']) + + tlstate.delete() + + expect(tlstate.selectHistory.pointer).toBe(0) + expect(tlstate.selectHistory.stack).toStrictEqual([[]]) + expect(tlstate.selectedIds).toStrictEqual([]) + + tlstate.undoSelect() + + expect(tlstate.selectHistory.pointer).toBe(0) + expect(tlstate.selectHistory.stack).toStrictEqual([[]]) + expect(tlstate.selectedIds).toStrictEqual([]) + }) + }) + + describe('Copies to JSON', () => { + tlstate.selectAll() + expect(tlstate.copyJson()).toMatchSnapshot('copied json') + }) + + describe('Copies to SVG', () => { + tlstate.selectAll() + expect(tlstate.copySvg()).toMatchSnapshot('copied svg') + }) + + describe('Mutates bound shapes', () => { + const tlstate = new TLDrawState() + .createShapes( + { + id: 'rect', + point: [0, 0], + size: [100, 100], + childIndex: 1, + type: TLDrawShapeType.Rectangle, + }, + { + id: 'arrow', + point: [200, 200], + childIndex: 2, + type: TLDrawShapeType.Arrow, + } + ) + .select('arrow') + .startHandleSession([200, 200], 'start', 'arrow') + .updateHandleSession([10, 10]) + .completeSession() + .selectAll() + .style({ color: ColorStyle.Red }) + + expect(tlstate.getShape('arrow').style.color).toBe(ColorStyle.Red) + expect(tlstate.getShape('rect').style.color).toBe(ColorStyle.Red) + + tlstate.undo() + + expect(tlstate.getShape('arrow').style.color).toBe(ColorStyle.Black) + expect(tlstate.getShape('rect').style.color).toBe(ColorStyle.Black) + + tlstate.redo() + + expect(tlstate.getShape('arrow').style.color).toBe(ColorStyle.Red) + expect(tlstate.getShape('rect').style.color).toBe(ColorStyle.Red) + }) + + describe('when selecting shapes in a group', () => { + it('selects the group when a grouped shape is clicked', () => { + const tlstate = new TLDrawState() + .loadDocument(mockDocument) + .group(['rect1', 'rect2'], 'groupA') + + const tlu = new TLStateUtils(tlstate) + tlu.clickShape('rect1') + expect(tlstate.selectedGroupId).toBeUndefined() + expect(tlstate.selectedIds).toStrictEqual(['groupA']) + }) + + it('selects the grouped shape when double clicked', () => { + const tlstate = new TLDrawState() + .loadDocument(mockDocument) + .group(['rect1', 'rect2'], 'groupA') + + const tlu = new TLStateUtils(tlstate) + tlu.doubleClickShape('rect1') + expect(tlstate.selectedGroupId).toStrictEqual('groupA') + expect(tlstate.selectedIds).toStrictEqual(['rect1']) + }) + + it('clears the selectedGroupId when selecting a different shape', () => { + const tlstate = new TLDrawState() + .loadDocument(mockDocument) + .group(['rect1', 'rect2'], 'groupA') + + const tlu = new TLStateUtils(tlstate) + tlu.doubleClickShape('rect1') + tlu.clickShape('rect3') + expect(tlstate.selectedGroupId).toBeUndefined() + expect(tlstate.selectedIds).toStrictEqual(['rect3']) + }) + + it('selects a grouped shape when meta-shift-clicked', () => { + const tlstate = new TLDrawState() + .loadDocument(mockDocument) + .group(['rect1', 'rect2'], 'groupA') + .deselectAll() + + const tlu = new TLStateUtils(tlstate) + + tlu.clickShape('rect1', { ctrlKey: true, shiftKey: true }) + expect(tlstate.selectedIds).toStrictEqual(['rect1']) + + tlu.clickShape('rect1', { ctrlKey: true, shiftKey: true }) + expect(tlstate.selectedIds).toStrictEqual([]) + }) + + it('selects a hovered shape from the selected group when meta-shift-clicked', () => { + const tlstate = new TLDrawState() + .loadDocument(mockDocument) + .group(['rect1', 'rect2'], 'groupA') + + const tlu = new TLStateUtils(tlstate) + + tlu.clickShape('rect1', { ctrlKey: true, shiftKey: true }) + expect(tlstate.selectedIds).toStrictEqual(['rect1']) + + tlu.clickShape('rect1', { ctrlKey: true, shiftKey: true }) + expect(tlstate.selectedIds).toStrictEqual([]) + }) + }) + + describe('when creating shapes', () => { + it('Creates shapes with the correct child index', () => { + const tlstate = new TLDrawState() + .createShapes( + { + id: 'rect1', + type: TLDrawShapeType.Rectangle, + childIndex: 1, + }, + { + id: 'rect2', + type: TLDrawShapeType.Rectangle, + childIndex: 2, + }, + { + id: 'rect3', + type: TLDrawShapeType.Rectangle, + childIndex: 3, + } + ) + .selectTool(TLDrawShapeType.Rectangle) + .createActiveToolShape([0, 0], 'rect4') + + expect(tlstate.getShape('rect4').childIndex).toBe(4) + + tlstate + .group(['rect2', 'rect3', 'rect4'], 'groupA') + .selectTool(TLDrawShapeType.Rectangle) + .createActiveToolShape([0, 0], 'rect5') + + expect(tlstate.getShape('groupA').childIndex).toBe(2) + expect(tlstate.getShape('rect5').childIndex).toBe(3) + }) + }) +}) diff --git a/packages/tldraw/src/state/tlstate.ts b/packages/tldraw/src/state/tlstate.ts new file mode 100644 index 000000000..71fa16c5a --- /dev/null +++ b/packages/tldraw/src/state/tlstate.ts @@ -0,0 +1,2644 @@ +import { StateManager } from 'rko' +import { + TLBoundsCorner, + TLBoundsEdge, + TLBoundsEventHandler, + TLBoundsHandleEventHandler, + TLCanvasEventHandler, + TLKeyboardInfo, + TLPageState, + TLPinchEventHandler, + TLPointerEventHandler, + TLWheelEventHandler, + Utils, + Vec, + brushUpdater, + TLPointerInfo, + inputs, +} from '@tldraw/core' +import { + FlipType, + TextShape, + TLDrawDocument, + MoveType, + AlignType, + StretchType, + DistributeType, + ShapeStyles, + TLDrawShape, + TLDrawShapeType, + TLDrawToolType, + Data, + Session, + TLDrawStatus, + ParametersExceptFirst, + SelectHistory, + TLDrawPage, + TLDrawBinding, + GroupShape, +} from '~types' +import { TLDR } from './tldr' +import { defaultStyle } from '~shape' +import * as Sessions from './session' +import * as Commands from './command' + +const defaultDocument: TLDrawDocument = { + id: 'doc', + pages: { + page: { + id: 'page', + name: 'Page 1', + childIndex: 1, + shapes: {}, + bindings: {}, + }, + }, + pageStates: { + page: { + id: 'page', + selectedIds: [], + camera: { + point: [0, 0], + zoom: 1, + }, + }, + }, +} + +const initialData: Data = { + settings: { + isPenMode: false, + isDarkMode: false, + isZoomSnap: true, + isDebugMode: process.env.NODE_ENV === 'development', + isReadonlyMode: false, + nudgeDistanceLarge: 10, + nudgeDistanceSmall: 1, + }, + appState: { + activeToolType: undefined, + activeTool: 'select', + hoveredId: undefined, + currentPageId: 'page', + pages: [{ id: 'page', name: 'page', childIndex: 1 }], + currentStyle: defaultStyle, + selectedStyle: defaultStyle, + isToolLocked: false, + isStyleOpen: false, + isEmptyCanvas: false, + status: { + current: TLDrawStatus.Idle, + previous: TLDrawStatus.Idle, + }, + }, + document: defaultDocument, +} + +export class TLDrawState extends StateManager { + private _onChange?: (tlstate: TLDrawState, data: Data, reason: string) => void + private _onMount?: (tlstate: TLDrawState) => void + + selectHistory: SelectHistory = { + stack: [[]], + pointer: 0, + } + + clipboard?: TLDrawShape[] + + session?: Session + + pointedId?: string + + pointedHandle?: string + + pointedBoundsHandle?: TLBoundsCorner | TLBoundsEdge | 'rotate' + + isCreating = false + + selectedGroupId?: string + + constructor( + id = Utils.uniqueId(), + onChange?: (tlstate: TLDrawState, data: Data, reason: string) => void, + onMount?: (tlstate: TLDrawState) => void + ) { + super(initialData, id, 2, (prev, next, prevVersion) => { + const state = { ...prev } + if (prevVersion === 1) + state.settings = { + ...state.settings, + isZoomSnap: next.settings.isZoomSnap, + } + return state + }) + + this._onChange = onChange + this._onMount = onMount + + this.session = undefined + this.pointedId = undefined + } + /* -------------------- Internal -------------------- */ + + onReady = () => { + this._onMount?.(this) + } + + /** + * Cleanup the state after each state change. + * @param state The new state + * @param prev The previous state + * @protected + * @returns The final state + */ + protected cleanup = (state: Data, prev: Data): Data => { + const data = { ...state } + + // Remove deleted shapes and bindings (in Commands, these will be set to undefined) + if (data.document !== prev.document) { + Object.entries(data.document.pages).forEach(([pageId, page]) => { + if (page === undefined) { + // If page is undefined, delete the page and pagestate + delete data.document.pages[pageId] + delete data.document.pageStates[pageId] + return + } + + const prevPage = prev.document.pages[pageId] + + if (!prevPage || page.shapes !== prevPage.shapes || page.bindings !== prevPage.bindings) { + page.shapes = { ...page.shapes } + page.bindings = { ...page.bindings } + + const groupsToUpdate = new Set() + + // If shape is undefined, delete the shape + Object.keys(page.shapes).forEach((id) => { + const shape = page.shapes[id] + let parentId: string + + if (!shape) { + parentId = prevPage.shapes[id]?.parentId + delete page.shapes[id] + } else { + parentId = shape.parentId + } + + // If the shape is the child of a group, then update the group + // (unless the group is being deleted too) + if (parentId && parentId !== pageId) { + const group = page.shapes[parentId] + if (group !== undefined) { + groupsToUpdate.add(page.shapes[parentId] as GroupShape) + } + } + }) + + // If binding is undefined, delete the binding + Object.keys(page.bindings).forEach((id) => { + if (!page.bindings[id]) delete page.bindings[id] + }) + + // Find which shapes have changed + const changedShapeIds = Object.values(page.shapes) + .filter((shape) => prevPage?.shapes[shape.id] !== shape) + .map((shape) => shape.id) + + data.document.pages[pageId] = page + + // Get bindings related to the changed shapes + const bindingsToUpdate = TLDR.getRelatedBindings(data, changedShapeIds, pageId) + + // Update all of the bindings we've just collected + bindingsToUpdate.forEach((binding) => { + const toShape = page.shapes[binding.toId] + const fromShape = page.shapes[binding.fromId] + const toUtils = TLDR.getShapeUtils(toShape) + + // We only need to update the binding's "from" shape + const util = TLDR.getShapeUtils(fromShape) + + const fromDelta = util.onBindingChange( + fromShape, + binding, + toShape, + toUtils.getBounds(toShape), + toUtils.getCenter(toShape) + ) + + if (fromDelta) { + const nextShape = { + ...fromShape, + ...fromDelta, + } as TLDrawShape + + page.shapes[fromShape.id] = nextShape + } + }) + + groupsToUpdate.forEach((group) => { + if (!group) throw Error('no group!') + const children = group.children.filter((id) => page.shapes[id] !== undefined) + + const commonBounds = Utils.getCommonBounds( + children + .map((id) => page.shapes[id]) + .filter(Boolean) + .map((shape) => TLDR.getRotatedBounds(shape)) + ) + + page.shapes[group.id] = { + ...group, + point: [commonBounds.minX, commonBounds.minY], + size: [commonBounds.width, commonBounds.height], + children, + } + }) + } + + // Clean up page state, preventing hovers on deleted shapes + + const nextPageState: TLPageState = { + ...data.document.pageStates[pageId], + } + + if (nextPageState.hoveredId && !page.shapes[nextPageState.hoveredId]) { + delete nextPageState.hoveredId + } + + if (nextPageState.bindingId && !page.bindings[nextPageState.bindingId]) { + console.warn('Could not find the binding binding!', pageId) + delete nextPageState.bindingId + } + + if (nextPageState.editingId && !page.shapes[nextPageState.editingId]) { + console.warn('Could not find the editing shape!') + delete nextPageState.editingId + } + + data.document.pageStates[pageId] = nextPageState + }) + } + + const currentPageId = data.appState.currentPageId + + // Apply selected style change, if any + + const newSelectedStyle = TLDR.getSelectedStyle(data, currentPageId) + + if (newSelectedStyle) { + data.appState = { + ...data.appState, + selectedStyle: newSelectedStyle, + } + } + + // Check that the correct page id is active (delete me?) + + if (data.document.pageStates[currentPageId].id !== currentPageId) { + throw Error('Current page id is not the current page state!') + } + + return data + } + + /** + * Clear the selection history after each new command, undo or redo. + * @param state + * @param id + */ + protected onStateDidChange = (state: Data, id: string): void => { + if (!id.startsWith('patch')) { + this.clearSelectHistory() + } + + this._onChange?.(this, state, id) + } + + /** + * Set the current status. + * @param status The new status to set. + * @private + * @returns + */ + private setStatus(status: TLDrawStatus) { + return this.patchState({ + appState: { status: { current: status, previous: this.appState.status.current } }, + }) + } + + /* -------------------------------------------------- */ + /* Settings & UI */ + /* -------------------------------------------------- */ + + /** + * Toggle pen mode. + * @returns this + */ + togglePenMode = (): this => { + if (this.session) return this + return this.patchState( + { + settings: { + isPenMode: !this.state.settings.isPenMode, + }, + }, + `settings:toggled_pen_mode` + ) + } + + /** + * Toggle dark mode. + * @returns this + */ + toggleDarkMode = (): this => { + if (this.session) return this + this.patchState( + { settings: { isDarkMode: !this.state.settings.isDarkMode } }, + `settings:toggled_dark_mode` + ) + this.persist() + return this + } + + /** + * Toggle zoom snap. + * @returns this + */ + toggleZoomSnap = () => { + if (this.session) return this + this.patchState( + { settings: { isZoomSnap: !this.state.settings.isZoomSnap } }, + `settings:toggled_zoom_snap` + ) + this.persist() + return this + } + + /** + * Toggle debug mode. + * @returns this + */ + toggleDebugMode = () => { + if (this.session) return this + this.patchState( + { settings: { isDebugMode: !this.state.settings.isDebugMode } }, + `settings:toggled_debug` + ) + this.persist() + return this + } + + /** + * Toggle the style panel. + * @returns this + */ + toggleStylePanel = (): this => { + if (this.session) return this + this.patchState( + { appState: { isStyleOpen: !this.appState.isStyleOpen } }, + 'ui:toggled_style_panel' + ) + this.persist() + return this + } + + /** + * Select a tool. + * @param tool The tool to select. + * @returns this + */ + selectTool = (tool: TLDrawShapeType | 'select'): this => { + if (this.session) return this + return this.patchState( + { + appState: { + activeTool: tool, + activeToolType: + tool === 'select' + ? 'select' + : TLDR.getShapeUtils({ type: tool } as TLDrawShape).toolType, + }, + }, + `selected_tool:${tool}` + ) + } + + /** + * Toggle the tool lock option. + * @returns this + */ + toggleToolLock = (): this => { + if (this.session) return this + return this.patchState( + { + appState: { + isToolLocked: !this.appState.isToolLocked, + }, + }, + `toggled_tool_lock` + ) + } + + /* -------------------------------------------------- */ + /* Document */ + /* -------------------------------------------------- */ + + /** + * Reset the document to a blank state. + * @returns this + */ + resetDocument = (): this => { + if (this.session) return this + this.session = undefined + this.selectedGroupId = undefined + this.resetHistory() + .clearSelectHistory() + .loadDocument(defaultDocument) + .patchState( + { + appState: { + status: { + current: TLDrawStatus.Idle, + previous: TLDrawStatus.Idle, + }, + }, + document: { + pageStates: { + [this.currentPageId]: { + bindingId: undefined, + editingId: undefined, + hoveredId: undefined, + pointedId: undefined, + }, + }, + }, + }, + 'reset_document' + ) + .persist() + return this + } + + /** + * Load a new document. + * @param document The document to load + * @param onChange (optional) A callback to call when the document changes + * @returns this + */ + loadDocument = (document: TLDrawDocument): this => { + this.deselectAll() + this.resetHistory() + this.clearSelectHistory() + this.session = undefined + this.selectedGroupId = undefined + + return this.replaceState({ + ...this.state, + appState: { + ...this.appState, + currentPageId: Object.keys(document.pages)[0], + }, + document: { + ...document, + pages: Object.fromEntries( + Object.entries(document.pages) + .sort((a, b) => (a[1].childIndex || 0) - (b[1].childIndex || 0)) + .map(([id, page], i) => { + return [ + id, + { + ...page, + name: page.name ? page.name : `Page ${i++}`, + }, + ] + }) + ), + pageStates: Object.fromEntries( + Object.entries(document.pageStates).map(([id, pageState]) => { + return [ + id, + { + ...pageState, + bindingId: undefined, + editingId: undefined, + hoveredId: undefined, + pointedId: undefined, + }, + ] + }) + ), + }, + }) + } + + newProject = () => { + // TODO + } + + saveProject = () => { + // TODO + } + + loadProject = () => { + // TODO + } + + signOut = () => { + // TODO + } + /* -------------------- Getters --------------------- */ + + /** + * Get the current app state. + * @returns this + */ + getAppState = (): Data['appState'] => { + return this.appState + } + + /** + * Get a page. + * @param pageId (optional) The page's id. + * @returns this + */ + getPage = (pageId = this.currentPageId): TLDrawPage => { + return TLDR.getPage(this.state, pageId || this.currentPageId) + } + + /** + * Get the shapes (as an array) from a given page. + * @param pageId (optional) The page's id. + * @returns this + */ + getShapes = (pageId = this.currentPageId): TLDrawShape[] => { + return TLDR.getShapes(this.state, pageId || this.currentPageId) + } + + /** + * Get the bindings from a given page. + * @param pageId (optional) The page's id. + * @returns this + */ + getBindings = (pageId = this.currentPageId): TLDrawBinding[] => { + return TLDR.getBindings(this.state, pageId || this.currentPageId) + } + + /** + * Get a shape from a given page. + * @param id The shape's id. + * @param pageId (optional) The page's id. + * @returns this + */ + getShape = (id: string, pageId = this.currentPageId): T => { + return TLDR.getShape(this.state, id, pageId) + } + + /** + * Get a binding from a given page. + * @param id The binding's id. + * @param pageId (optional) The page's id. + * @returns this + */ + getBinding = (id: string, pageId = this.currentPageId): TLDrawBinding => { + return TLDR.getBinding(this.state, id, pageId) + } + + /** + * Get the page state for a given page. + * @param pageId (optional) The page's id. + * @returns this + */ + getPageState = (pageId = this.currentPageId): TLPageState => { + return TLDR.getPageState(this.state, pageId || this.currentPageId) + } + + /** + * Turn a screen point into a point on the page. + * @param point The screen point + * @param pageId (optional) The page to use + * @returns this + */ + getPagePoint = (point: number[], pageId = this.currentPageId): number[] => { + const { camera } = this.getPageState(pageId) + return Vec.sub(Vec.div(point, camera.zoom), camera.point) + } + + /** + * The current document. + */ + get document(): TLDrawDocument { + return this.state.document + } + + /** + * The current app state. + */ + get appState(): Data['appState'] { + return this.state.appState + } + + /** + * The current page id. + */ + get currentPageId(): string { + return this.state.appState.currentPageId + } + + /** + * The current page. + */ + get page(): TLDrawPage { + return this.state.document.pages[this.currentPageId] + } + + /** + * The current page's shapes (as an array). + */ + get shapes(): TLDrawShape[] { + return Object.values(this.page.shapes) + } + + /** + * The current page's bindings. + */ + get bindings(): TLDrawBinding[] { + return Object.values(this.page.bindings) + } + + /** + * The current page's state. + */ + get pageState(): TLPageState { + return this.state.document.pageStates[this.currentPageId] + } + + /** + * The page's current selected ids. + */ + get selectedIds(): string[] { + return this.pageState.selectedIds + } + + /* -------------------------------------------------- */ + /* Pages */ + /* -------------------------------------------------- */ + + /** + * Create a new page page. + * @param pageId (optional) The new page's id. + * @returns this + */ + createPage = (id?: string): this => { + return this.setState(Commands.createPage(this.state, id)) + } + + /** + * Change the current page. + * @param pageId The new current page's id. + * @returns this + */ + changePage = (pageId: string): this => { + return this.setState(Commands.changePage(this.state, pageId)) + } + + /** + * Rename a page. + * @param pageId The id of the page to rename. + * @param name The page's new name + * @returns this + */ + renamePage = (pageId: string, name: string): this => { + return this.setState(Commands.renamePage(this.state, pageId, name)) + } + + /** + * Duplicate a page. + * @param pageId The id of the page to duplicate. + * @returns this + */ + duplicatePage = (pageId: string): this => { + return this.setState(Commands.duplicatePage(this.state, pageId)) + } + + /** + * Delete a page. + * @param pageId The id of the page to delete. + * @returns this + */ + deletePage = (pageId?: string): this => { + if (Object.values(this.document.pages).length <= 1) return this + return this.setState(Commands.deletePage(this.state, pageId ? pageId : this.currentPageId)) + } + + /* -------------------------------------------------- */ + /* Clipboard */ + /* -------------------------------------------------- */ + + /** + * Copy one or more shapes to the clipboard. + * @param ids The ids of the shapes to copy. + * @returns this + */ + copy = (ids = this.selectedIds): this => { + this.clipboard = ids + .flatMap((id) => TLDR.getDocumentBranch(this.state, id, this.currentPageId)) + .map((id) => { + const shape = this.getShape(id, this.currentPageId) + + return { + ...shape, + id: Utils.uniqueId(), + childIndex: TLDR.getChildIndexAbove(this.state, id, this.currentPageId), + } + }) + + return this + } + + /** + * Paste shapes (or text) from clipboard to a certain point. + * @param point + * @param string + * @returns this + */ + paste = (point?: number[], string?: string): this => { + if (string) { + // Parse shapes from string + try { + const jsonShapes: TLDrawShape[] = JSON.parse(string) + + jsonShapes.forEach((shape) => { + if (shape.parentId !== this.currentPageId) { + shape.parentId = this.currentPageId + } + }) + + this.create(...jsonShapes) + } catch (e) { + // Create text shape + const childIndex = + this.getShapes().sort((a, b) => b.childIndex - a.childIndex)[0].childIndex + 1 + + const shape = TLDR.getShapeUtils(TLDrawShapeType.Text).create({ + id: Utils.uniqueId(), + parentId: this.appState.currentPageId, + childIndex, + point: this.getPagePoint([window.innerWidth / 2, window.innerHeight / 2]), + style: { ...this.appState.currentStyle }, + }) + + const boundsCenter = Utils.centerBounds( + TLDR.getShapeUtils(shape).getBounds(shape), + this.getPagePoint([window.innerWidth / 2, window.innerHeight / 2]) + ) + + this.create( + TLDR.getShapeUtils(TLDrawShapeType.Text).create({ + id: Utils.uniqueId(), + parentId: this.appState.currentPageId, + childIndex, + point: [boundsCenter.minX, boundsCenter.minY], + }) + ) + } + + return this + } + + if (!this.clipboard) return this + + const idsMap = Object.fromEntries(this.clipboard.map((shape) => [shape.id, Utils.uniqueId()])) + + const shapesToPaste = this.clipboard.map((shape) => ({ + ...shape, + id: idsMap[shape.id], + parentId: idsMap[shape.parentId] || this.currentPageId, + })) + + const commonBounds = Utils.getCommonBounds(shapesToPaste.map(TLDR.getBounds)) + + const centeredBounds = Utils.centerBounds( + commonBounds, + this.getPagePoint(point || [window.innerWidth / 2, window.innerHeight / 2]) + ) + + let delta = Vec.sub(Utils.getBoundsCenter(centeredBounds), Utils.getBoundsCenter(commonBounds)) + + if (Vec.isEqual(delta, [0, 0])) { + delta = [16, 16] + } + + this.create( + ...shapesToPaste.map((shape) => ({ + ...shape, + point: Vec.round(Vec.add(shape.point, delta)), + })) + ) + + return this + } + + /** + * Copy one or more shapes as SVG. + * @param ids The ids of the shapes to copy. + * @param pageId The page from which to copy the shapes. + * @returns A string containing the JSON. + */ + copySvg = (ids = this.selectedIds, pageId = this.currentPageId) => { + if (ids.length === 0) return + + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg') + + ids.forEach((id) => { + const elm = document.getElementById(id) + if (elm) { + const clone = elm?.cloneNode(true) + svg.appendChild(clone) + } + }) + + const shapes = ids.map((id) => this.getShape(id, pageId)) + const bounds = Utils.getCommonBounds(shapes.map(TLDR.getBounds)) + const padding = 16 + + // Resize the element to the bounding box + svg.setAttribute( + 'viewBox', + [ + bounds.minX - padding, + bounds.minY - padding, + bounds.width + padding * 2, + bounds.height + padding * 2, + ].join(' ') + ) + + svg.setAttribute('width', String(bounds.width)) + + svg.setAttribute('height', String(bounds.height)) + + const s = new XMLSerializer() + + const svgString = s + .serializeToString(svg) + .replaceAll(' ', '') + .replaceAll(/((\s|")[0-9]*\.[0-9]{2})([0-9]*)(\b|"|\))/g, '$1') + + TLDR.copyStringToClipboard(svgString) + + return svgString + } + + /** + * Copy one or more shapes as JSON + * @param ids The ids of the shapes to copy. + * @param pageId The page from which to copy the shapes. + * @returns A string containing the JSON. + */ + copyJson = (ids = this.selectedIds, pageId = this.currentPageId) => { + const shapes = ids.map((id) => this.getShape(id, pageId)) + const json = JSON.stringify(shapes, null, 2) + TLDR.copyStringToClipboard(json) + return json + } + + /* -------------------------------------------------- */ + /* Camera */ + /* -------------------------------------------------- */ + + /** + * Set the camera to a specific point and zoom. + * @param point The camera point (top left of the viewport). + * @param zoom The zoom level. + * @param reason Why did the camera change? + * @returns this + */ + setCamera = (point: number[], zoom: number, reason: string): this => { + return this.patchState( + { + document: { + pageStates: { + [this.currentPageId]: { camera: { point, zoom } }, + }, + }, + }, + reason + ) + } + + /** + * Reset the camera to the default position + * @returns this + */ + resetCamera = (): this => { + return this.setCamera( + Vec.round([window.innerWidth / 2, window.innerHeight / 2]), + 1, + `reset_camera` + ) + } + + /** + * Pan the camera + * @param delta + * @returns this + */ + pan = (delta: number[]): this => { + const { camera } = this.pageState + return this.setCamera(Vec.round(Vec.sub(camera.point, delta)), camera.zoom, `panned`) + } + + /** + * Pinch to a new zoom level, possibly together with a pan. + * @param point The current point under the cursor. + * @param delta The movement delta. + * @param zoomDelta The zoom detal + * @returns this + */ + pinchZoom = (point: number[], delta: number[], zoomDelta: number): this => { + const { camera } = this.pageState + const nextPoint = Vec.add(camera.point, Vec.div(delta, camera.zoom)) + const nextZoom = TLDR.getCameraZoom(camera.zoom - zoomDelta * camera.zoom) + const p0 = Vec.sub(Vec.div(point, camera.zoom), nextPoint) + const p1 = Vec.sub(Vec.div(point, nextZoom), nextPoint) + return this.setCamera(Vec.round(Vec.add(nextPoint, Vec.sub(p1, p0))), nextZoom, `pinch_zoomed`) + } + + /** + * Zoom to a new zoom level, keeping the point under the cursor in the same position + * @param next The new zoom level. + * @returns this + */ + zoomTo = (next: number, center = [window.innerWidth / 2, window.innerHeight / 2]): this => { + const { zoom, point } = this.pageState.camera + const p0 = Vec.sub(Vec.div(center, zoom), point) + const p1 = Vec.sub(Vec.div(center, next), point) + return this.setCamera(Vec.round(Vec.add(point, Vec.sub(p1, p0))), next, `zoomed_camera`) + } + + /** + * Zoom out by 25% + * @returns this + */ + zoomIn = (): this => { + const i = Math.round((this.pageState.camera.zoom * 100) / 25) + const nextZoom = TLDR.getCameraZoom((i + 1) * 0.25) + return this.zoomTo(nextZoom) + } + + /** + * Zoom in by 25%. + * @returns this + */ + zoomOut = (): this => { + const i = Math.round((this.pageState.camera.zoom * 100) / 25) + const nextZoom = TLDR.getCameraZoom((i - 1) * 0.25) + return this.zoomTo(nextZoom) + } + + /** + * Zoom to fit the page's shapes. + * @returns this + */ + zoomToFit = (): this => { + const shapes = this.getShapes() + + if (shapes.length === 0) return this + + const bounds = Utils.getCommonBounds(Object.values(shapes).map(TLDR.getBounds)) + + const zoom = TLDR.getCameraZoom( + window.innerWidth < window.innerHeight + ? (window.innerWidth - 128) / bounds.width + : (window.innerHeight - 128) / bounds.height + ) + + const mx = (window.innerWidth - bounds.width * zoom) / 2 / zoom + const my = (window.innerHeight - bounds.height * zoom) / 2 / zoom + + return this.setCamera( + Vec.round(Vec.add([-bounds.minX, -bounds.minY], [mx, my])), + this.pageState.camera.zoom, + `zoomed_to_fit` + ) + } + + /** + * Zoom to the selected shapes. + * @returns this + */ + zoomToSelection = (): this => { + if (this.selectedIds.length === 0) return this + + const bounds = TLDR.getSelectedBounds(this.state) + + const zoom = TLDR.getCameraZoom( + window.innerWidth < window.innerHeight + ? (window.innerWidth - 128) / bounds.width + : (window.innerHeight - 128) / bounds.height + ) + + const mx = (window.innerWidth - bounds.width * zoom) / 2 / zoom + const my = (window.innerHeight - bounds.height * zoom) / 2 / zoom + + return this.setCamera( + Vec.round(Vec.add([-bounds.minX, -bounds.minY], [mx, my])), + zoom, + `zoomed_to_selection` + ) + } + + /** + * Zoom back to content when the canvas is empty. + * @returns this + */ + zoomToContent = (): this => { + const shapes = this.getShapes() + const pageState = this.pageState + + if (shapes.length === 0) return this + + const bounds = Utils.getCommonBounds(Object.values(shapes).map(TLDR.getBounds)) + + const { zoom } = pageState.camera + const mx = (window.innerWidth - bounds.width * zoom) / 2 / zoom + const my = (window.innerHeight - bounds.height * zoom) / 2 / zoom + + return this.setCamera( + Vec.round(Vec.add([-bounds.minX, -bounds.minY], [mx, my])), + this.pageState.camera.zoom, + `zoomed_to_content` + ) + } + + /** + * Zoom the camera to 100%. + * @returns this + */ + zoomToActual = (): this => { + return this.zoomTo(1) + } + + /** + * Zoom the camera by a certain delta. + * @returns this + */ + zoom = Utils.throttle((delta: number): this => { + const { zoom } = this.pageState.camera + const nextZoom = TLDR.getCameraZoom(zoom - delta * zoom) + return this.zoomTo(nextZoom) + }, 16) + + /* -------------------------------------------------- */ + /* Selection */ + /* -------------------------------------------------- */ + + /** + * Clear the selection history (undo/redo stack for selection). + */ + private clearSelectHistory = (): this => { + this.selectHistory.pointer = 0 + this.selectHistory.stack = [this.selectedIds] + return this + } + + /** + * Adds a selection to the selection history (undo/redo stack for selection). + */ + private addToSelectHistory = (ids: string[]): this => { + if (this.selectHistory.pointer < this.selectHistory.stack.length) { + this.selectHistory.stack = this.selectHistory.stack.slice(0, this.selectHistory.pointer + 1) + } + this.selectHistory.pointer++ + this.selectHistory.stack.push(ids) + return this + } + + /** + * Set the current selection. + * @param ids The ids to select + * @param push Whether to add the ids to the current selection instead. + * @returns this + */ + private setSelectedIds = (ids: string[], push = false): this => { + return this.patchState( + { + appState: { + activeTool: 'select', + activeToolType: 'select', + }, + document: { + pageStates: { + [this.currentPageId]: { + selectedIds: push ? [...this.pageState.selectedIds, ...ids] : [...ids], + }, + }, + }, + }, + `selected` + ) + } + + /** + * Undo the most recent selection. + * @returns this + */ + undoSelect = (): this => { + if (this.selectHistory.pointer > 0) { + this.selectHistory.pointer-- + this.setSelectedIds(this.selectHistory.stack[this.selectHistory.pointer]) + } + return this + } + + /** + * Redo the previous selection. + * @returns this + */ + redoSelect = (): this => { + if (this.selectHistory.pointer < this.selectHistory.stack.length - 1) { + this.selectHistory.pointer++ + this.setSelectedIds(this.selectHistory.stack[this.selectHistory.pointer]) + } + return this + } + + /** + * Select one or more shapes. + * @param ids The shape ids to select. + * @returns this + */ + select = (...ids: string[]): this => { + ids.forEach((id) => { + if (!this.page.shapes[id]) { + throw Error(`That shape does not exist on page ${this.currentPageId}`) + } + }) + this.setSelectedIds(ids) + this.addToSelectHistory(ids) + return this + } + + /** + * Select all shapes on the page. + * @returns this + */ + selectAll = (): this => { + if (this.session) return this + this.setSelectedIds(Object.keys(this.page.shapes)) + this.addToSelectHistory(this.selectedIds) + if (this.appState.activeTool !== 'select') { + this.selectTool('select') + } + return this + } + + /** + * Deselect any selected shapes. + * @returns this + */ + deselectAll = (): this => { + this.setSelectedIds([]) + this.addToSelectHistory(this.selectedIds) + return this + } + + /* -------------------------------------------------- */ + /* Sessions */ + /* -------------------------------------------------- */ + + /** + * Start a new session. + * @param session The new session + * @param args arguments of the session's start method. + * @returns this + */ + startSession = ( + session: T, + ...args: ParametersExceptFirst + ): this => { + this.session = session + + const result = session.start(this.state, ...args) + + if (result) { + return this.patchState( + { + ...result, + appState: { + ...result.appState, + status: { + current: session.status, + previous: this.appState.status.previous, + }, + }, + }, + `session:start_${session.id}` + ) + } + + return this.setStatus(session.status) + } + + /** + * Update the current session. + * @param args The arguments of the current session's update method. + * @returns this + */ + updateSession = (...args: ParametersExceptFirst): this => { + const { session } = this + if (!session) return this + const patch = session.update(this.state, ...args) + if (!patch) return this + return this.patchState(patch, `session:update:${session.id}`) + } + + /** + * Cancel the current session. + * @param args The arguments of the current session's cancel method. + * @returns this + */ + cancelSession = (...args: ParametersExceptFirst): this => { + const { session } = this + if (!session) return this + this.session = undefined + + if (this.isCreating) { + this.isCreating = false + return this.patchState( + { + appState: { + status: { + current: TLDrawStatus.Idle, + previous: this.appState.status.previous, + }, + }, + document: { + pages: { + [this.currentPageId]: { + shapes: { + ...Object.fromEntries(this.selectedIds.map((id) => [id, undefined])), + }, + }, + }, + pageStates: { + [this.currentPageId]: { + selectedIds: [], + editingId: undefined, + bindingId: undefined, + hoveredId: undefined, + }, + }, + }, + }, + `session:cancel_create:${session.id}` + ) + } + + return this.patchState( + { + ...session.cancel(this.state, ...args), + appState: { + status: { + current: TLDrawStatus.Idle, + previous: this.appState.status.current, + }, + }, + }, + `session:cancel:${session.id}` + ) + } + + /** + * Complete the current session. + * @param args The arguments of the current session's complete method. + * @returns this + */ + completeSession = (...args: ParametersExceptFirst): this => { + const { session } = this + + if (!session) return this + + const result = session.complete(this.state, ...args) + + this.session = undefined + + if (result === undefined) { + this.isCreating = false + return this.patchState( + { + appState: { + status: { + current: TLDrawStatus.Idle, + previous: this.appState.status.previous, + }, + }, + document: { + pageStates: { + [this.currentPageId]: { + editingId: undefined, + }, + }, + }, + }, + `session:complete:${session.id}` + ) + } else if ('after' in result) { + // Session ended with a command + + if (this.isCreating) { + // We're currently creating a shape. Override the command's + // before state so that when we undo the command, we remove + // the shape we just created. + result.before = { + document: { + pages: { + [this.currentPageId]: { + shapes: Object.fromEntries(this.selectedIds.map((id) => [id, undefined])), + }, + }, + pageStates: { + [this.currentPageId]: { + selectedIds: [], + editingId: undefined, + bindingId: undefined, + hoveredId: undefined, + }, + }, + }, + } + + // ...and set editingId back to undefined + result.after = { + ...result.after, + document: { + ...result.after.document, + pageStates: { + ...result.after.document?.pageStates, + [this.currentPageId]: { + ...(result.after.document?.pageStates || {})[this.currentPageId], + editingId: undefined, + }, + }, + }, + } + + if (this.appState.isToolLocked) { + const pageState = result.after?.document?.pageStates?.[this.currentPageId] || {} + pageState.selectedIds = [] + } + + this.isCreating = false + } + + // Either way, set the status back to idle + result.after.appState = { + ...result.after.appState, + status: { + current: TLDrawStatus.Idle, + previous: this.appState.status.previous, + }, + } + + this.setState(result, `session:complete:${session.id}`) + } else { + this.patchState( + { + ...result, + appState: { + ...result.appState, + status: { + current: TLDrawStatus.Idle, + previous: this.appState.status.previous, + }, + }, + document: { + pageStates: { + [this.currentPageId]: { + editingId: undefined, + }, + }, + }, + }, + `session:complete:${session.id}` + ) + } + + const { isToolLocked, activeTool } = this.appState + + if (!isToolLocked && activeTool !== 'draw') { + this.selectTool('select') + } + + return this + } + + /* -------------------- Sessions -------------------- */ + startBrushSession = (point: number[]): this => { + return this.startSession(new Sessions.BrushSession(this.state, point)) + } + + updateBrushSession = (point: number[], metaKey = false): this => { + return this.updateSession(point, metaKey) + } + + startTranslateSession = (point: number[]): this => { + return this.startSession(new Sessions.TranslateSession(this.state, point)) + } + + updateTranslateSession = (point: number[], shiftKey = false, altKey = false): this => { + return this.updateSession(point, shiftKey, altKey) + } + + startTransformSession = ( + point: number[], + handle: TLBoundsCorner | TLBoundsEdge | 'rotate', + commandId?: string + ): this => { + const { selectedIds } = this + + if (selectedIds.length === 0) return this + + this.pointedBoundsHandle = handle + + if (this.pointedBoundsHandle === 'rotate') { + return this.startSession(new Sessions.RotateSession(this.state, point)) + } + + const idsToTransform = selectedIds.flatMap((id) => + TLDR.getDocumentBranch(this.state, id, this.currentPageId) + ) + + if (idsToTransform.length === 1) { + return this.startSession( + new Sessions.TransformSingleSession(this.state, point, this.pointedBoundsHandle, commandId) + ) + } + + return this.startSession( + new Sessions.TransformSession(this.state, point, this.pointedBoundsHandle) + ) + } + + updateTransformSession = (point: number[], shiftKey = false, altKey = false): this => { + return this.updateSession( + point, + shiftKey, + altKey + ) + } + + startTextSession = (id: string): this => { + return this.startSession(new Sessions.TextSession(this.state, id)) + } + + updateTextSession = (text: string): this => { + return this.updateSession(text) + } + + startDrawSession = (id: string, point: number[]): this => { + return this.startSession(new Sessions.DrawSession(this.state, id, point)) + } + + updateDrawSession = (point: number[], pressure: number, shiftKey = false): this => { + return this.updateSession(point, pressure, shiftKey) + } + + startHandleSession = (point: number[], handleId: string, commandId?: string): this => { + const selectedShape = this.page.shapes[this.selectedIds[0]] + if (selectedShape.type === TLDrawShapeType.Arrow) { + return this.startSession( + new Sessions.ArrowSession(this.state, handleId as 'start' | 'end', point) + ) + } + + return this.startSession( + new Sessions.HandleSession(this.state, handleId, point, commandId) + ) + } + + updateHandleSession = ( + point: number[], + shiftKey = false, + altKey = false, + metaKey = false + ): this => { + return this.updateSession( + point, + shiftKey, + altKey, + metaKey + ) + } + + /* -------------------------------------------------- */ + /* Shape Functions */ + /* -------------------------------------------------- */ + + /** + * Manually create shapes on the page. + * @param shapes An array of shape partials, containing the initial props for the shapes. + * @command + * @returns this + */ + createShapes = ( + ...shapes: ({ id: string; type: TLDrawShapeType } & Partial)[] + ): this => { + if (shapes.length === 0) return this + return this.create( + ...shapes.map((shape) => { + return TLDR.getShapeUtils(shape as TLDrawShape).create({ + ...shape, + parentId: shape.parentId || this.currentPageId, + }) + }) + ) + } + + /** + * Manually update a set of shapes. + * @param shapes An array of shape partials, containing the changes to be made to each shape. + * @command + * @returns this + */ + updateShapes = (...shapes: ({ id: string } & Partial)[]): this => { + if (shapes.length === 0) return this + return this.setState(Commands.update(this.state, shapes), 'updated_shape') + } + + /** + * Create one or more shapes. + * @param shapes An array of shapes. + * @command + * @returns this + */ + create = (...shapes: TLDrawShape[]): this => { + if (shapes.length === 0) return this + return this.setState(Commands.create(this.state, shapes)) + } + + /** + * Delete one or more shapes. + * @param ids The ids of the shapes to delete. + * @command + * @returns this + */ + delete = (ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.deleteShapes(this.state, ids)) + } + + /** + * Delete all shapes on the page. + * @returns this + */ + clear = (): this => { + this.selectAll() + this.delete() + return this + } + + /** + * Change the style for one or more shapes. + * @param style A style partial to apply to the shapes. + * @param ids The ids of the shapes to change (defaults to selection). + * @returns this + */ + style = (style: Partial, ids = this.selectedIds): this => { + return this.setState(Commands.style(this.state, ids, style)) + } + + /** + * Align one or more shapes. + * @param direction Whether to align horizontally or vertically. + * @param ids The ids of the shapes to change (defaults to selection). + * @returns this + */ + align = (type: AlignType, ids = this.selectedIds): this => { + if (ids.length < 2) return this + return this.setState(Commands.align(this.state, ids, type)) + } + + /** + * Distribute one or more shapes. + * @param direction Whether to distribute horizontally or vertically.. + * @param ids The ids of the shapes to change (defaults to selection). + * @returns this + */ + distribute = (direction: DistributeType, ids = this.selectedIds): this => { + if (ids.length < 3) return this + return this.setState(Commands.distribute(this.state, ids, direction)) + } + + /** + * Stretch one or more shapes to their common bounds. + * @param direction Whether to stretch horizontally or vertically. + * @param ids The ids of the shapes to change (defaults to selection). + * @returns this + */ + stretch = (direction: StretchType, ids = this.selectedIds): this => { + if (ids.length < 2) return this + return this.setState(Commands.stretch(this.state, ids, direction)) + } + + /** + * Flip one or more shapes horizontally. + * @param ids The ids of the shapes to change (defaults to selection). + * @returns this + */ + flipHorizontal = (ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.flip(this.state, ids, FlipType.Horizontal)) + } + + /** + * Flip one or more shapes vertically. + * @param ids The ids of the shapes to change (defaults to selection). + * @returns this + */ + flipVertical = (ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.flip(this.state, ids, FlipType.Vertical)) + } + + /** + * Move one or more shapes to a new page. Will also break or move bindings. + * @param toPage The id of the page to move the shapes to. + * @param fromPage The id of the page to move the shapes from + *(defaults to current page). + * @param ids The ids of the shapes to move (defaults to selection). + * @returns this + */ + moveToPage = ( + toPageId: string, + fromPageId = this.currentPageId, + ids = this.selectedIds + ): this => { + if (ids.length === 0) return this + this.setState(Commands.moveToPage(this.state, ids, fromPageId, toPageId)) + return this + } + + /** + * Move one or more shapes to the back of the page. + * @param ids The ids of the shapes to change (defaults to selection). + * @returns this + */ + moveToBack = (ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.move(this.state, ids, MoveType.ToBack)) + } + + /** + * Move one or more shapes backward on of the page. + * @param ids The ids of the shapes to change (defaults to selection). + * @returns this + */ + moveBackward = (ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.move(this.state, ids, MoveType.Backward)) + } + + /** + * Move one or more shapes forward on the page. + * @param ids The ids of the shapes to change (defaults to selection). + * @returns this + */ + moveForward = (ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.move(this.state, ids, MoveType.Forward)) + } + + /** + * Move one or more shapes to the front of the page. + * @param ids The ids of the shapes to change (defaults to selection). + * @returns this + */ + moveToFront = (ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.move(this.state, ids, MoveType.ToFront)) + } + + /** + * Nudge one or more shapes in a direction. + * @param delta The direction to nudge the shapes. + * @param isMajor Whether this is a major (i.e. shift) nudge. + * @param ids The ids to change (defaults to selection). + * @returns this + */ + nudge = (delta: number[], isMajor = false, ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.translate(this.state, ids, Vec.mul(delta, isMajor ? 10 : 1))) + } + + /** + * Duplicate one or more shapes. + * @param ids The ids to duplicate (defaults to selection). + * @returns this + */ + duplicate = (ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.duplicate(this.state, ids)) + } + + /** + * Toggle the hidden property of one or more shapes. + * @param ids The ids to change (defaults to selection). + * @returns this + */ + toggleHidden = (ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.toggle(this.state, ids, 'isHidden')) + } + + /** + * Toggle the locked property of one or more shapes. + * @param ids The ids to change (defaults to selection). + * @returns this + */ + toggleLocked = (ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.toggle(this.state, ids, 'isLocked')) + } + + /** + * Toggle the fixed-aspect-ratio property of one or more shapes. + * @param ids The ids to change (defaults to selection). + * @returns this + */ + toggleAspectRatioLocked = (ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.toggle(this.state, ids, 'isAspectRatioLocked')) + } + + /** + * Toggle the decoration at a handle of one or more shapes. + * @param handleId The handle to toggle. + * @param ids The ids of the shapes to toggle the decoration on. + * @returns this + */ + toggleDecoration = (handleId: string, ids = this.selectedIds): this => { + if (ids.length === 0 || !(handleId === 'start' || handleId === 'end')) return this + return this.setState(Commands.toggleDecoration(this.state, ids, handleId)) + } + + /** + * Rotate one or more shapes by a delta. + * @param delta The delta in radians. + * @param ids The ids to rotate (defaults to selection). + * @returns this + */ + rotate = (delta = Math.PI * -0.5, ids = this.selectedIds): this => { + if (ids.length === 0) return this + return this.setState(Commands.rotate(this.state, ids, delta)) + } + + /** + * Group the selected shapes. + * @returns this + * @todo + */ + group = (ids = this.selectedIds, groupId = Utils.uniqueId()): this => { + if (ids.length < 2) return this + const command = Commands.group(this.state, ids, groupId) + if (!command) return this + return this.setState(command) + } + + /** + * Ungroup the selected groups. + * @returns this + * @todo + */ + ungroup = (): this => { + // TODO + return this + } + + /** + * Cancel the current session. + * @returns this + */ + cancel = (): this => { + switch (this.state.appState.status.current) { + case TLDrawStatus.Idle: { + this.deselectAll() + this.selectTool('select') + break + } + case TLDrawStatus.Brushing: { + this.cancelSession() + brushUpdater.clear() + break + } + case TLDrawStatus.Translating: + case TLDrawStatus.Transforming: + case TLDrawStatus.Rotating: + case TLDrawStatus.Creating: { + this.cancelSession() + break + } + } + + return this + } + + updateOnPointerMove = (info: TLPointerInfo): this => { + switch (this.appState.status.current) { + case TLDrawStatus.PointingBoundsHandle: { + if (!this.pointedBoundsHandle) throw Error('No pointed bounds handle') + if (Vec.dist(info.origin, info.point) > 4) { + return this.startTransformSession( + this.getPagePoint(info.origin), + this.pointedBoundsHandle + ) + } + break + } + case TLDrawStatus.PointingHandle: { + if (!this.pointedHandle) throw Error('No pointed handle') + if (Vec.dist(info.origin, info.point) > 4) { + return this.startHandleSession(this.getPagePoint(info.origin), this.pointedHandle) + } + break + } + case TLDrawStatus.PointingBounds: { + if (Vec.dist(info.origin, info.point) > 4) { + return this.startTranslateSession(this.getPagePoint(info.origin)) + } + break + } + case TLDrawStatus.Brushing: { + return this.updateBrushSession(this.getPagePoint(info.point), info.metaKey) + } + case TLDrawStatus.Translating: { + return this.updateTranslateSession( + this.getPagePoint(info.point), + info.shiftKey, + info.altKey + ) + } + case TLDrawStatus.Transforming: { + return this.updateTransformSession( + this.getPagePoint(info.point), + info.shiftKey, + info.altKey + ) + } + case TLDrawStatus.TranslatingHandle: { + return this.updateHandleSession( + this.getPagePoint(info.point), + info.shiftKey, + info.altKey, + info.metaKey + ) + } + case TLDrawStatus.Creating: { + switch (this.appState.activeToolType) { + case TLDrawToolType.Draw: { + return this.updateDrawSession( + this.getPagePoint(info.point), + info.pressure, + info.shiftKey + ) + } + case TLDrawToolType.Bounds: { + return this.updateTransformSession(this.getPagePoint(info.point), info.shiftKey) + } + case TLDrawToolType.Handle: { + return this.updateHandleSession( + this.getPagePoint(info.point), + info.shiftKey, + info.altKey, + info.metaKey + ) + } + case TLDrawToolType.Point: { + break + } + case TLDrawToolType.Points: { + break + } + } + break + } + } + + return this + } + + createActiveToolShape = (point: number[], id = Utils.uniqueId()): this => { + const pagePoint = Vec.round(this.getPagePoint(point)) + + if (this.appState.activeTool === 'select') return this + + if (!this.appState.activeToolType) throw Error + + const utils = TLDR.getShapeUtils({ type: this.appState.activeTool } as TLDrawShape) + + const shapes = this.getShapes() + + const childIndex = + shapes.length === 0 + ? 1 + : shapes + .filter((shape) => shape.parentId === this.currentPageId) + .sort((a, b) => b.childIndex - a.childIndex)[0].childIndex + 1 + + this.patchState( + { + appState: { + status: { + current: TLDrawStatus.Creating, + previous: this.appState.status.current, + }, + }, + document: { + pages: { + [this.currentPageId]: { + shapes: { + [id]: utils.create({ + id, + parentId: this.currentPageId, + childIndex, + point: pagePoint, + style: { ...this.appState.currentStyle }, + }), + }, + }, + }, + pageStates: { + [this.currentPageId]: { + selectedIds: [id], + editingId: id, + }, + }, + }, + }, + `started_creating:${this.appState.activeTool}` + ) + + this.isCreating = true + + const { activeTool, activeToolType } = this.appState + + switch (activeToolType) { + case TLDrawToolType.Draw: { + return this.startDrawSession(id, pagePoint) + } + case TLDrawToolType.Bounds: { + return this.startTransformSession( + pagePoint, + TLBoundsCorner.BottomRight, + `create_${activeTool}` + ) + } + case TLDrawToolType.Handle: { + return this.startHandleSession(pagePoint, 'end', `create_${activeTool}`) + } + case TLDrawToolType.Text: { + return this.startTextSession(id) + } + case TLDrawToolType.Point: { + break + } + case TLDrawToolType.Points: { + break + } + } + + return this + } + + /* -------------------------------------------------- */ + /* Event Handlers */ + /* -------------------------------------------------- */ + + /* ----------------- Keyboard Events ---------------- */ + + onKeyDown = (key: string, info: TLKeyboardInfo) => { + if (key === 'Escape') { + this.cancel() + return + } + + switch (this.appState.status.current) { + case TLDrawStatus.Idle: { + break + } + case TLDrawStatus.Brushing: { + if (key === 'Meta' || key === 'Control') { + this.updateBrushSession(this.getPagePoint(info.point), info.metaKey) + return + } + + break + } + case TLDrawStatus.Translating: { + if (key === 'Escape') { + this.cancelSession(this.getPagePoint(info.point)) + } + + if (key === 'Shift' || key === 'Alt') { + this.updateTranslateSession(this.getPagePoint(info.point), info.shiftKey, info.altKey) + } + break + } + case TLDrawStatus.Transforming: { + if (key === 'Escape') { + this.cancelSession(this.getPagePoint(info.point)) + } + + if (key === 'Shift' || key === 'Alt') { + this.updateTransformSession(this.getPagePoint(info.point), info.shiftKey, info.altKey) + } + break + } + case TLDrawStatus.TranslatingHandle: { + if (key === 'Escape') { + this.cancelSession(this.getPagePoint(info.point)) + } + + if (key === 'Meta' || key === 'Control') { + this.updateHandleSession( + this.getPagePoint(info.point), + info.shiftKey, + info.altKey, + info.metaKey + ) + } + break + } + } + } + + onKeyUp = (key: string, info: TLKeyboardInfo) => { + switch (this.appState.status.current) { + case TLDrawStatus.Brushing: { + if (key === 'Meta' || key === 'Control') { + this.updateBrushSession(this.getPagePoint(info.point), info.metaKey) + } + break + } + case TLDrawStatus.Transforming: { + if (key === 'Shift' || key === 'Alt') { + this.updateTransformSession(this.getPagePoint(info.point), info.shiftKey, info.altKey) + } + break + } + case TLDrawStatus.Translating: { + if (key === 'Shift' || key === 'Alt') { + this.updateTranslateSession(this.getPagePoint(info.point), info.shiftKey, info.altKey) + } + break + } + case TLDrawStatus.TranslatingHandle: { + if (key === 'Escape') { + this.cancelSession(this.getPagePoint(info.point)) + } + + if (key === 'Meta' || key === 'Control') { + this.updateHandleSession( + this.getPagePoint(info.point), + info.shiftKey, + info.altKey, + info.metaKey + ) + } + break + } + } + } + + /* ------------- Renderer Event Handlers ------------ */ + + onPinchStart: TLPinchEventHandler = () => { + this.setStatus(TLDrawStatus.Pinching) + } + + onPinchEnd: TLPinchEventHandler = () => { + if (this.state.settings.isZoomSnap) { + const i = Math.round((this.pageState.camera.zoom * 100) / 25) + const nextZoom = TLDR.getCameraZoom(i * 0.25) + this.zoomTo(nextZoom, inputs.pointer?.point) + } + this.setStatus(this.appState.status.previous) + } + + onPinch: TLPinchEventHandler = (info) => { + if (this.appState.status.current !== TLDrawStatus.Pinching) return + + this.pinchZoom(info.origin, info.delta, info.delta[2] / 350) + this.updateOnPointerMove(info) + } + + onPan: TLWheelEventHandler = (info) => { + if (this.appState.status.current === TLDrawStatus.Pinching) return + // TODO: Pan and pinchzoom are firing at the same time. Considering turning one of them off! + + const delta = Vec.div(info.delta, this.pageState.camera.zoom) + const prev = this.pageState.camera.point + const next = Vec.sub(prev, delta) + + if (Vec.isEqual(next, prev)) return + + this.pan(delta) + this.updateOnPointerMove(info) + } + + onZoom: TLWheelEventHandler = (info) => { + this.zoom(info.delta[2] / 100) + this.updateOnPointerMove(info) + } + + /* ----------------- Pointer Events ----------------- */ + + onPointerMove: TLPointerEventHandler = (info) => { + // Several events (e.g. pan) can trigger the same "pointer move" behavior + this.updateOnPointerMove(info) + } + + onPointerDown: TLPointerEventHandler = (info) => { + switch (this.appState.status.current) { + case TLDrawStatus.Idle: { + switch (this.appState.activeTool) { + case TLDrawShapeType.Draw: { + this.createActiveToolShape(info.point) + break + } + case TLDrawShapeType.Rectangle: { + this.createActiveToolShape(info.point) + break + } + case TLDrawShapeType.Ellipse: { + this.createActiveToolShape(info.point) + break + } + case TLDrawShapeType.Arrow: { + this.createActiveToolShape(info.point) + break + } + case TLDrawShapeType.Text: { + this.createActiveToolShape(info.point) + break + } + } + break + } + case TLDrawStatus.EditingText: { + this.completeSession() + break + } + } + } + + onPointerUp: TLPointerEventHandler = (info) => { + switch (this.appState.status.current) { + case TLDrawStatus.PointingBounds: { + if (info.target === 'bounds') { + // If we just clicked the selecting bounds's background, + // clear the selection + this.deselectAll() + } else if (this.selectedIds.includes(info.target)) { + // If we're holding shift... + if (info.shiftKey) { + // unless we just shift-selected the shape, remove it from + // the selected shapes + if (this.pointedId !== info.target) { + this.select(...this.selectedIds.filter((id) => id !== info.target)) + } + } else { + if (this.pointedId !== info.target && this.selectedIds.length > 1) { + this.select(info.target) + } + } + } else if (this.pointedId === info.target) { + if (info.shiftKey) { + this.select(...this.selectedIds, info.target) + } else { + this.select(info.target) + } + } + + this.setStatus(TLDrawStatus.Idle) + this.pointedId = undefined + break + } + case TLDrawStatus.PointingBoundsHandle: { + this.setStatus(TLDrawStatus.Idle) + this.pointedBoundsHandle = undefined + break + } + case TLDrawStatus.PointingHandle: { + this.setStatus(TLDrawStatus.Idle) + this.pointedHandle = undefined + break + } + case TLDrawStatus.TranslatingHandle: { + this.completeSession() + this.pointedHandle = undefined + break + } + case TLDrawStatus.Brushing: { + this.completeSession() + brushUpdater.clear() + break + } + case TLDrawStatus.Translating: { + this.completeSession() + this.pointedId = undefined + break + } + case TLDrawStatus.Transforming: { + this.completeSession() + this.pointedBoundsHandle = undefined + break + } + case TLDrawStatus.Creating: { + this.completeSession(this.getPagePoint(info.point)) + this.pointedHandle = undefined + } + } + } + + // Canvas (background) + onPointCanvas: TLCanvasEventHandler = (info) => { + if (this.appState.isStyleOpen) { + this.toggleStylePanel() + } + + switch (this.appState.status.current) { + case TLDrawStatus.Idle: { + switch (this.appState.activeTool) { + case 'select': { + // Unless the user is holding shift or meta, clear the current selection + if (!(info.shiftKey || info.metaKey)) { + this.deselectAll() + } + + // Start a brush session + this.startBrushSession(this.getPagePoint(info.point)) + break + } + } + break + } + } + } + + onDoubleClickCanvas: TLCanvasEventHandler = (info) => { + // Unused + switch (this.appState.status.current) { + case TLDrawStatus.Idle: { + switch (this.appState.activeTool) { + case TLDrawShapeType.Text: { + // Create a text shape + this.createActiveToolShape(info.point) + break + } + } + break + } + } + } + + onRightPointCanvas: TLCanvasEventHandler = () => { + // Unused + } + + onDragCanvas: TLCanvasEventHandler = () => { + // Unused + } + + onReleaseCanvas: TLCanvasEventHandler = () => { + // Unused + } + + // Shape + onPointShape: TLPointerEventHandler = (info) => { + const { activeTool, status } = this.appState + + // While holding command and shift, select or deselect + // the shape, ignoring any group that may contain it. Yikes! + if ( + activeTool === 'select' && + (status.current === TLDrawStatus.Idle || status.current === TLDrawStatus.PointingBounds) && + info.metaKey && + info.shiftKey && + this.pageState.hoveredId + ) { + const targetId = this.pageState.hoveredId + this.pointedId = targetId + + if (this.selectedIds.includes(targetId)) { + // Deselect if selected + this.select(...this.selectedIds.filter((id) => id !== targetId)) + } else { + const shape = this.getShape(this.pageState.hoveredId) + // Push select the shape, deselecting the shape's parent if selected + this.select(...this.selectedIds.filter((id) => id !== shape.parentId), targetId) + } + + return + } + + switch (status.current) { + case TLDrawStatus.Idle: { + switch (activeTool) { + case 'select': { + if (info.metaKey) { + if (!info.shiftKey) { + this.deselectAll() + } + // While holding just command key, start a brush session + this.startBrushSession(this.getPagePoint(info.point)) + return + } + + // If we've clicked on a shape that is inside of a group, + // then select the group rather than the shape. + let shapeIdToSelect: string + const { parentId } = this.getShape(info.target) + + // If the pointed shape is a child of the page, select the + // target shape and clear the selected group id. + if (parentId === this.currentPageId) { + shapeIdToSelect = info.target + this.selectedGroupId = undefined + } else { + // If the parent is some other group... + if (parentId === this.selectedGroupId) { + // If that group is the selected group, then select + // the target shape. + shapeIdToSelect = info.target + } else { + // Otherwise, select the group and clear the selected + // group id. + shapeIdToSelect = parentId + this.selectedGroupId = undefined + } + } + + if (!this.selectedIds.includes(shapeIdToSelect)) { + // Set the pointed ID to the shape that was clicked. + this.pointedId = shapeIdToSelect + + // If the shape is not selected: then if the user is pressing shift, + // add the shape to the current selection; otherwise, set the shape as + // the only selected shape. + this.select( + ...(info.shiftKey ? [...this.selectedIds, shapeIdToSelect] : [shapeIdToSelect]) + ) + } + + this.setStatus(TLDrawStatus.PointingBounds) + break + } + } + break + } + case TLDrawStatus.PointingBounds: { + const { parentId } = this.getShape(info.target) + this.pointedId = parentId === this.currentPageId ? info.target : parentId + + break + } + } + } + + onReleaseShape: TLPointerEventHandler = () => { + // Unused + } + + onDoubleClickShape: TLPointerEventHandler = (info) => { + switch (this.appState.status.current) { + case TLDrawStatus.Idle: + case TLDrawStatus.PointingBounds: { + switch (this.appState.activeTool) { + case 'select': { + const shape = this.getShape(info.target) + if (shape.parentId !== this.currentPageId) { + this.selectedGroupId = shape.parentId + } + if (this.selectedIds.includes(shape.id)) { + if (shape.type === TLDrawShapeType.Text) { + this.startTextSession(info.target) + } + } + this.select(info.target) + break + } + } + break + } + } + } + + onRightPointShape: TLPointerEventHandler = (info) => { + if (!this.selectedIds.includes(info.target)) { + this.select(info.target) + } + } + + onDragShape: TLPointerEventHandler = () => { + // Unused + } + + onHoverShape: TLPointerEventHandler = (info) => { + this.patchState( + { + document: { + pageStates: { + [this.currentPageId]: { + hoveredId: info.target, + }, + }, + }, + }, + `hovered_shape:${info.target}` + ) + } + + onUnhoverShape: TLPointerEventHandler = (info) => { + const { currentPageId } = this + setTimeout(() => { + if (currentPageId === this.currentPageId && this.pageState.hoveredId === info.target) { + this.patchState( + { + document: { + pageStates: { + [this.currentPageId]: { + hoveredId: undefined, + }, + }, + }, + }, + `unhovered_shape:${info.target}` + ) + } + }, 10) + } + + // Bounds (bounding box background) + onPointBounds: TLBoundsEventHandler = (info) => { + if (info.metaKey) { + if (!info.shiftKey) { + this.deselectAll() + } + // While holding just command key, start a brush session + this.startBrushSession(this.getPagePoint(info.point)) + return + } + + this.setStatus(TLDrawStatus.PointingBounds) + } + + onDoubleClickBounds: TLBoundsEventHandler = () => { + // Unused + } + + onRightPointBounds: TLBoundsEventHandler = () => { + // Unused + } + + onDragBounds: TLBoundsEventHandler = () => { + // Unused + } + + onHoverBounds: TLBoundsEventHandler = () => { + // Unused + } + + onUnhoverBounds: TLBoundsEventHandler = () => { + // Unused + } + + onReleaseBounds: TLBoundsEventHandler = (info) => { + switch (this.appState.status.current) { + case TLDrawStatus.Translating: { + this.completeSession(this.getPagePoint(info.point)) + break + } + case TLDrawStatus.Brushing: { + this.completeSession() + brushUpdater.clear() + break + } + } + } + + // Bounds handles (corners, edges) + onPointBoundsHandle: TLBoundsHandleEventHandler = (info) => { + this.pointedBoundsHandle = info.target + this.setStatus(TLDrawStatus.PointingBoundsHandle) + } + + onDoubleClickBoundsHandle: TLBoundsHandleEventHandler = () => { + // TODO + } + + onRightPointBoundsHandle: TLBoundsHandleEventHandler = () => { + // TODO + } + + onDragBoundsHandle: TLBoundsHandleEventHandler = () => { + // Unused + } + + onHoverBoundsHandle: TLBoundsHandleEventHandler = () => { + // TODO + } + + onUnhoverBoundsHandle: TLBoundsHandleEventHandler = () => { + // TODO + } + + onReleaseBoundsHandle: TLBoundsHandleEventHandler = () => { + // TODO + } + + // Handles (ie the handles of a selected arrow) + onPointHandle: TLPointerEventHandler = (info) => { + this.pointedHandle = info.target + this.setStatus(TLDrawStatus.PointingHandle) + } + + onDoubleClickHandle: TLPointerEventHandler = (info) => { + this.toggleDecoration(info.target) + } + + onRightPointHandle: TLPointerEventHandler = () => { + // TODO + } + + onDragHandle: TLPointerEventHandler = () => { + // TODO + } + + onHoverHandle: TLPointerEventHandler = () => { + // TODO + } + + onUnhoverHandle: TLPointerEventHandler = () => { + // TODO + } + + onReleaseHandle: TLPointerEventHandler = () => { + // Unused + } + + onTextChange = (id: string, text: string) => { + this.updateTextSession(text) + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTextBlur = (id: string) => { + this.completeSession() + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTextFocus = (id: string) => { + // Unused + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTextKeyDown = (id: string, key: string) => { + // Unused + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + onTextKeyUp = (id: string, key: string) => { + // Unused + } + + onChange = (ids: string[]) => { + const appState = this.getAppState() + if (appState.isEmptyCanvas && ids.length > 0) { + this.patchState( + { + appState: { + isEmptyCanvas: false, + }, + }, + 'empty_canvas:false' + ) + } else if (!appState.isEmptyCanvas && ids.length <= 0) { + this.patchState( + { + appState: { + isEmptyCanvas: true, + }, + }, + 'empty_canvas:true' + ) + } + } + + onError = () => { + // TODO + } + + onBlurEditingShape = () => { + this.completeSession() + } +} diff --git a/packages/tldraw/src/state/utils.spec.ts b/packages/tldraw/src/state/utils.spec.ts new file mode 100644 index 000000000..079e3e62e --- /dev/null +++ b/packages/tldraw/src/state/utils.spec.ts @@ -0,0 +1,19 @@ +import { Utils } from '@tldraw/core' + +describe('deep merge', () => { + it('merges an object', () => { + const a = { a: 1, b: 2 } + const b = { ...a, a: 2 } + const c = Utils.deepMerge(a, b) + expect(c.a).toBe(2) + expect(c.b).toBe(a.b) + }) + + it('merges a complex object', () => { + const a = { a: 1, b: { name: 'steve', age: 93 } } + const b = { a: 2 } + const c = Utils.deepMerge(a, b) + expect(c.a).toBe(2) + expect(c.b === a.b).toBeTruthy() + }) +}) diff --git a/packages/tldraw/src/styles/index.ts b/packages/tldraw/src/styles/index.ts new file mode 100644 index 000000000..2eb879795 --- /dev/null +++ b/packages/tldraw/src/styles/index.ts @@ -0,0 +1,5 @@ +import styled from './stitches.config' + +export * from './stitches.config' + +export default styled diff --git a/packages/tldraw/src/styles/stitches.config.ts b/packages/tldraw/src/styles/stitches.config.ts new file mode 100644 index 000000000..c6d8f9257 --- /dev/null +++ b/packages/tldraw/src/styles/stitches.config.ts @@ -0,0 +1,139 @@ +import { createStitches, defaultThemeMap } from '@stitches/react' + +const { styled, css, createTheme, getCssText } = createStitches({ + themeMap: { + ...defaultThemeMap, + }, + theme: { + colors: { + codeHl: 'rgba(144, 144, 144, .15)', + brushFill: 'rgba(0,0,0,.05)', + brushStroke: 'rgba(0,0,0,.25)', + hint: 'rgba(216, 226, 249, 1.000)', + selected: 'rgba(66, 133, 244, 1.000)', + bounds: 'rgba(65, 132, 244, 1.000)', + boundsBg: 'rgba(65, 132, 244, 0.05)', + highlight: 'rgba(65, 132, 244, 0.15)', + overlay: 'rgba(0, 0, 0, 0.15)', + overlayContrast: 'rgba(255, 255, 255, 0.15)', + border: '#aaaaaa', + canvas: '#f8f9fa', + panel: '#fefefe', + inactive: '#cccccf', + hover: '#efefef', + text: '#333333', + tooltipBg: '#1d1d1d', + tooltipText: '#ffffff', + muted: '#777777', + input: '#f3f3f3', + inputBorder: '#dddddd', + warn: 'rgba(255, 100, 100, 1)', + lineError: 'rgba(255, 0, 0, .1)', + }, + shadows: { + 2: '0px 1px 1px rgba(0, 0, 0, 0.14)', + 3: '0px 2px 3px rgba(0, 0, 0, 0.14)', + 4: '0px 4px 5px -1px rgba(0, 0, 0, 0.14)', + 8: '0px 12px 17px rgba(0, 0, 0, 0.14)', + 12: '0px 12px 17px rgba(0, 0, 0, 0.14)', + 24: '0px 24px 38px rgba(0, 0, 0, 0.14)', + key: '1px 1px rgba(0,0,0,1)', + }, + space: { + 0: '2px', + 1: '3px', + 2: '4px', + 3: '8px', + 4: '12px', + 5: '16px', + }, + fontSizes: { + 0: '10px', + 1: '12px', + 2: '13px', + 3: '16px', + 4: '18px', + }, + fonts: { + ui: '"Recursive", system-ui, sans-serif', + body: '"Recursive", system-ui, sans-serif', + mono: '"Recursive Mono", monospace', + }, + fontWeights: {}, + lineHeights: {}, + letterSpacings: {}, + sizes: {}, + borderWidths: { + 0: '$1', + }, + borderStyles: {}, + radii: { + 0: '2px', + 1: '4px', + 2: '8px', + }, + zIndices: {}, + transitions: {}, + }, + media: { + sm: '(min-width: 640px)', + md: '(min-width: 768px)', + }, + utils: { + zDash: () => (value: number) => { + return { + strokeDasharray: `calc(${value}px / var(--camera-zoom)) calc(${value}px / var(--camera-zoom))`, + } + }, + zStrokeWidth: () => (value: number | number[]) => { + if (Array.isArray(value)) { + return { + strokeWidth: `calc(${value[0]}px / var(--camera-zoom))`, + } + } + + return { + strokeWidth: `calc(${value}px / var(--camera-zoom))`, + } + }, + }, +}) + +const dark = createTheme({ + colors: { + brushFill: 'rgba(180, 180, 180, .05)', + brushStroke: 'rgba(180, 180, 180, .25)', + hint: 'rgba(216, 226, 249, 1.000)', + selected: 'rgba(38, 150, 255, 1.000)', + bounds: 'rgba(38, 150, 255, 1.000)', + boundsBg: 'rgba(38, 150, 255, 0.05)', + highlight: 'rgba(38, 150, 255, 0.15)', + overlay: 'rgba(0, 0, 0, 0.15)', + overlayContrast: 'rgba(255, 255, 255, 0.15)', + border: '#202529', + canvas: '#343d45', + panel: '#49555f', + inactive: '#aaaaad', + hover: '#343d45', + text: '#f8f9fa', + muted: '#e0e2e6', + input: '#f3f3f3', + inputBorder: '#ddd', + tooltipBg: '#1d1d1d', + tooltipText: '#ffffff', + codeHl: 'rgba(144, 144, 144, .15)', + lineError: 'rgba(255, 0, 0, .1)', + }, + shadows: { + 2: '0px 1px 1px rgba(0, 0, 0, 0.24)', + 3: '0px 2px 3px rgba(0, 0, 0, 0.24)', + 4: '0px 4px 5px -1px rgba(0, 0, 0, 0.24)', + 8: '0px 12px 17px rgba(0, 0, 0, 0.24)', + 12: '0px 12px 17px rgba(0, 0, 0, 0.24)', + 24: '0px 24px 38px rgba(0, 0, 0, 0.24)', + }, +}) + +export default styled + +export { css, getCssText, dark } diff --git a/packages/tldraw/src/test/index.ts b/packages/tldraw/src/test/index.ts new file mode 100644 index 000000000..1a19cb05b --- /dev/null +++ b/packages/tldraw/src/test/index.ts @@ -0,0 +1,3 @@ +export * from './mock-document' +export * from './renderWithContext' +export * from './state-utils' diff --git a/packages/tldraw/src/test/mock-document.tsx b/packages/tldraw/src/test/mock-document.tsx new file mode 100644 index 000000000..84c03f974 --- /dev/null +++ b/packages/tldraw/src/test/mock-document.tsx @@ -0,0 +1,66 @@ +import { TLDrawDocument, ColorStyle, DashStyle, SizeStyle, TLDrawShapeType } from '~types' + +export const mockDocument: TLDrawDocument = { + id: 'doc', + pages: { + page1: { + id: 'page1', + shapes: { + rect1: { + id: 'rect1', + parentId: 'page1', + name: 'Rectangle', + childIndex: 1, + type: TLDrawShapeType.Rectangle, + point: [0, 0], + size: [100, 100], + style: { + dash: DashStyle.Draw, + size: SizeStyle.Medium, + color: ColorStyle.Blue, + }, + }, + rect2: { + id: 'rect2', + parentId: 'page1', + name: 'Rectangle', + childIndex: 2, + type: TLDrawShapeType.Rectangle, + point: [100, 100], + size: [100, 100], + style: { + dash: DashStyle.Draw, + size: SizeStyle.Medium, + color: ColorStyle.Blue, + }, + }, + rect3: { + id: 'rect3', + parentId: 'page1', + name: 'Rectangle', + childIndex: 3, + type: TLDrawShapeType.Rectangle, + point: [20, 20], + size: [100, 100], + style: { + dash: DashStyle.Draw, + size: SizeStyle.Medium, + color: ColorStyle.Blue, + }, + }, + }, + bindings: {}, + }, + }, + pageStates: { + page1: { + id: 'page1', + selectedIds: [], + currentParentId: 'page1', + camera: { + point: [0, 0], + zoom: 1, + }, + }, + }, +} diff --git a/packages/tldraw/src/test/renderWithContext.tsx b/packages/tldraw/src/test/renderWithContext.tsx new file mode 100644 index 000000000..49f722972 --- /dev/null +++ b/packages/tldraw/src/test/renderWithContext.tsx @@ -0,0 +1,30 @@ +import * as React from 'react' +import { IdProvider } from '@radix-ui/react-id' +import { TLDrawState } from '~state' +import { useKeyboardShortcuts, TLDrawContext } from '~hooks' +import { mockDocument } from './mock-document' +import { render } from '@testing-library/react' + +export const Wrapper: React.FC = ({ children }) => { + const [tlstate] = React.useState(() => new TLDrawState()) + const [context] = React.useState(() => { + return { tlstate, useSelector: tlstate.useStore } + }) + + useKeyboardShortcuts() + + React.useEffect(() => { + if (!document) return + tlstate.loadDocument(mockDocument) + }, [document, tlstate]) + + return ( + + {children} + + ) +} + +export const renderWithContext = (children: JSX.Element) => { + return render({children}) +} diff --git a/packages/tldraw/src/test/state-utils.tsx b/packages/tldraw/src/test/state-utils.tsx new file mode 100644 index 000000000..4221af965 --- /dev/null +++ b/packages/tldraw/src/test/state-utils.tsx @@ -0,0 +1,116 @@ +import { inputs, TLBoundsEdge, TLBoundsCorner } from '@tldraw/core' +import type { TLDrawState } from '~state' + +interface PointerOptions { + id?: number + x?: number + y?: number + shiftKey?: boolean + altKey?: boolean + ctrlKey?: boolean +} + +export class TLStateUtils { + tlstate: TLDrawState + + constructor(tlstate: TLDrawState) { + this.tlstate = tlstate + } + + hoverShape = (id: string, options: PointerOptions = {}) => { + const { tlstate } = this + tlstate.onHoverShape(inputs.pointerDown(this.getPoint(options), id), {} as React.PointerEvent) + } + + pointCanvas = (options: PointerOptions = {}) => { + this.tlstate.onPointCanvas( + inputs.pointerDown(this.getPoint(options), 'canvas'), + {} as React.PointerEvent + ) + return this + } + + pointShape = (id: string, options: PointerOptions = {}) => { + this.tlstate.onPointShape( + inputs.pointerDown(this.getPoint(options), id), + {} as React.PointerEvent + ) + return this + } + + doubleClickShape = (id: string, options: PointerOptions = {}) => { + this.tlstate.onDoubleClickShape( + inputs.pointerDown(this.getPoint(options), id), + {} as React.PointerEvent + ) + return this + } + + pointBounds = (options: PointerOptions = {}) => { + this.tlstate.onPointBounds( + inputs.pointerDown(this.getPoint(options), 'bounds'), + {} as React.PointerEvent + ) + return this + } + + pointBoundsHandle = ( + id: TLBoundsCorner | TLBoundsEdge | 'rotate', + options: PointerOptions = {} + ) => { + this.tlstate.onPointBounds( + inputs.pointerDown(this.getPoint(options), 'bounds'), + {} as React.PointerEvent + ) + return this + } + + stopPointing = (target = 'canvas', options: PointerOptions = {}) => { + this.tlstate.onPointerUp( + inputs.pointerUp(this.getPoint(options), target), + {} as React.PointerEvent + ) + return this + } + + clickCanvas = (options: PointerOptions = {}) => { + this.pointCanvas(options) + this.stopPointing() + return this + } + + clickShape = (id: string, options: PointerOptions = {}) => { + this.hoverShape(id) + this.pointShape(id, options) + this.stopPointing(id, options) + return this + } + + clickBounds = (options: PointerOptions = {}) => { + this.pointBounds(options) + this.stopPointing('bounds', options) + return this + } + + clickBoundsHandle = ( + id: TLBoundsCorner | TLBoundsEdge | 'rotate', + options: PointerOptions = {} + ) => { + this.pointBoundsHandle(id, options) + this.stopPointing(id) + return this + } + + getPoint(options: PointerOptions = {} as PointerOptions): PointerEvent { + const { id = 1, x = 0, y = 0, shiftKey = false, altKey = false, ctrlKey = false } = options + + return { + shiftKey, + altKey, + ctrlKey, + pointerId: id, + clientX: x, + clientY: y, + } as PointerEvent + } +} diff --git a/packages/tldraw/src/types.ts b/packages/tldraw/src/types.ts new file mode 100644 index 000000000..ad416827d --- /dev/null +++ b/packages/tldraw/src/types.ts @@ -0,0 +1,294 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/ban-types */ +import type { TLBinding, TLRenderInfo } from '@tldraw/core' +import { TLShape, TLShapeUtil, TLHandle } from '@tldraw/core' +import type { TLPage, TLPageState } from '@tldraw/core' +import type { StoreApi } from 'zustand' +import type { Command, Patch } from 'rko' + +export type TLStore = StoreApi + +export type TLChange = Data + +export type TLDrawPage = TLPage + +export interface TLDrawDocument { + id: string + pages: Record + pageStates: Record +} + +export interface TLDrawSettings { + isDarkMode: boolean + isDebugMode: boolean + isPenMode: boolean + isReadonlyMode: boolean + isZoomSnap: boolean + nudgeDistanceSmall: number + nudgeDistanceLarge: number +} + +export interface TLDrawMeta { + isDarkMode: boolean +} + +export type TLDrawRenderInfo = TLRenderInfo + +export interface Data { + document: TLDrawDocument + settings: TLDrawSettings + appState: { + selectedStyle: ShapeStyles + currentStyle: ShapeStyles + currentPageId: string + pages: Pick, 'id' | 'name' | 'childIndex'>[] + hoveredId?: string + activeTool: TLDrawShapeType | 'select' + activeToolType?: TLDrawToolType | 'select' + isToolLocked: boolean + isStyleOpen: boolean + isEmptyCanvas: boolean + status: { current: TLDrawStatus; previous: TLDrawStatus } + } +} + +export type TLDrawPatch = Patch + +export type TLDrawCommand = Command + +export type PagePartial = { + shapes: Patch + bindings: Patch +} + +export interface SelectHistory { + pointer: number + stack: string[][] +} + +export interface Session { + id: string + status: TLDrawStatus + start: (data: Readonly, ...args: any[]) => TLDrawPatch | undefined + update: (data: Readonly, ...args: any[]) => TLDrawPatch | undefined + complete: (data: Readonly, ...args: any[]) => TLDrawPatch | TLDrawCommand | undefined + cancel: (data: Readonly, ...args: any[]) => TLDrawPatch | undefined +} + +export enum TLDrawStatus { + Idle = 'idle', + PointingHandle = 'pointingHandle', + PointingBounds = 'pointingBounds', + PointingBoundsHandle = 'pointingBoundsHandle', + TranslatingHandle = 'translatingHandle', + Translating = 'translating', + Transforming = 'transforming', + Rotating = 'rotating', + Pinching = 'pinching', + Brushing = 'brushing', + Creating = 'creating', + EditingText = 'editing-text', +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type ParametersExceptFirst = F extends (arg0: any, ...rest: infer R) => any ? R : never + +export enum MoveType { + Backward = 'backward', + Forward = 'forward', + ToFront = 'toFront', + ToBack = 'toBack', +} + +export enum AlignType { + Top = 'top', + CenterVertical = 'centerVertical', + Bottom = 'bottom', + Left = 'left', + CenterHorizontal = 'centerHorizontal', + Right = 'right', +} + +export enum StretchType { + Horizontal = 'horizontal', + Vertical = 'vertical', +} + +export enum DistributeType { + Horizontal = 'horizontal', + Vertical = 'vertical', +} + +export enum FlipType { + Horizontal = 'horizontal', + Vertical = 'vertical', +} + +export enum TLDrawToolType { + Draw = 'draw', + Bounds = 'bounds', + Point = 'point', + Handle = 'handle', + Points = 'points', + Text = 'text', +} + +export enum TLDrawShapeType { + Ellipse = 'ellipse', + Rectangle = 'rectangle', + Draw = 'draw', + Arrow = 'arrow', + Text = 'text', + Group = 'group', +} + +export enum Decoration { + Arrow = 'Arrow', +} + +export interface TLDrawBaseShape extends TLShape { + style: ShapeStyles + type: TLDrawShapeType +} + +export interface DrawShape extends TLDrawBaseShape { + type: TLDrawShapeType.Draw + points: number[][] +} + +export interface ArrowShape extends TLDrawBaseShape { + type: TLDrawShapeType.Arrow + bend: number + handles: { + start: TLHandle + bend: TLHandle + end: TLHandle + } + decorations?: { + start?: Decoration + end?: Decoration + middle?: Decoration + } +} +export interface EllipseShape extends TLDrawBaseShape { + type: TLDrawShapeType.Ellipse + radius: number[] +} + +export interface RectangleShape extends TLDrawBaseShape { + type: TLDrawShapeType.Rectangle + size: number[] +} + +export interface TextShape extends TLDrawBaseShape { + type: TLDrawShapeType.Text + text: string +} + +export interface GroupShape extends TLDrawBaseShape { + type: TLDrawShapeType.Group + size: number[] + children: string[] +} + +export type TLDrawShape = + | RectangleShape + | EllipseShape + | DrawShape + | ArrowShape + | TextShape + | GroupShape + +export abstract class TLDrawShapeUtil extends TLShapeUtil { + abstract toolType: TLDrawToolType +} + +export type TLDrawShapeUtils = Record> + +export interface ArrowBinding extends TLBinding { + type: 'arrow' + handleId: keyof ArrowShape['handles'] + distance: number + point: number[] +} + +export type TLDrawBinding = ArrowBinding + +export enum ColorStyle { + White = 'White', + LightGray = 'LightGray', + Gray = 'Gray', + Black = 'Black', + Green = 'Green', + Cyan = 'Cyan', + Blue = 'Blue', + Indigo = 'Indigo', + Violet = 'Violet', + Red = 'Red', + Orange = 'Orange', + Yellow = 'Yellow', +} + +export enum SizeStyle { + Small = 'Small', + Medium = 'Medium', + Large = 'Large', +} + +export enum DashStyle { + Draw = 'Draw', + Solid = 'Solid', + Dashed = 'Dashed', + Dotted = 'Dotted', +} + +export enum FontSize { + Small = 'Small', + Medium = 'Medium', + Large = 'Large', + ExtraLarge = 'ExtraLarge', +} + +export type ShapeStyles = { + color: ColorStyle + size: SizeStyle + dash: DashStyle + isFilled?: boolean + scale?: number +} + +export type PropsOfType = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [K in keyof TLDrawShape]: TLDrawShape[K] extends any + ? TLDrawShape[K] extends U + ? K + : never + : never +}[keyof TLDrawShape] + +export type Theme = 'dark' | 'light' + +export type Difference = A extends B ? never : C + +export type Intersection = A extends B ? C : never + +export type FilteredKeys = { + [P in keyof T]: T[P] extends U ? P : never +}[keyof T] + +export type RequiredKeys = { + [K in keyof T]-?: Difference, Pick, K> +}[keyof T] + +export type MembersWithRequiredKey = { + [P in keyof T]: Intersection, T[P]> +}[keyof T] + +export type MappedByType = { + [P in T['type']]: T extends any ? (P extends T['type'] ? T : never) : never +} + +export type ShapesWithProp = MembersWithRequiredKey< + MappedByType, + U +> diff --git a/packages/tldraw/tsconfig.build.json b/packages/tldraw/tsconfig.build.json new file mode 100644 index 000000000..92e47bf2b --- /dev/null +++ b/packages/tldraw/tsconfig.build.json @@ -0,0 +1,15 @@ +{ + "extends": "./tsconfig.json", + "exclude": [ + "node_modules", + "**/*.test.tsx", + "**/*.test.ts", + "**/*.spec.tsx", + "**/*.spec.ts", + "src/test", + "dist" + ], + "compilerOptions": { + "outDir": "./dist/types" + } +} diff --git a/packages/tldraw/tsconfig.json b/packages/tldraw/tsconfig.json new file mode 100644 index 000000000..49fd2d297 --- /dev/null +++ b/packages/tldraw/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src"], + "exclude": ["node_modules", "dist"], + "compilerOptions": { + "emitDeclarationOnly": true, + "rootDir": "src", + "outDir": "./dist/types", + "baseUrl": "src", + "paths": { + "~*": ["./*"] + } + } +} diff --git a/packages/www/.eslintrc.json b/packages/www/.eslintrc.json new file mode 100644 index 000000000..bffb357a7 --- /dev/null +++ b/packages/www/.eslintrc.json @@ -0,0 +1,3 @@ +{ + "extends": "next/core-web-vitals" +} diff --git a/packages/www/.gitignore b/packages/www/.gitignore new file mode 100644 index 000000000..1437c53f7 --- /dev/null +++ b/packages/www/.gitignore @@ -0,0 +1,34 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# local env files +.env.local +.env.development.local +.env.test.local +.env.production.local + +# vercel +.vercel diff --git a/packages/www/README.md b/packages/www/README.md new file mode 100644 index 000000000..b12f3e33e --- /dev/null +++ b/packages/www/README.md @@ -0,0 +1,34 @@ +This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). + +## Getting Started + +First, run the development server: + +```bash +npm run dev +# or +yarn dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. + +You can start editing the page by modifying `pages/index.js`. The page auto-updates as you edit the file. + +[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`. + +The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages. + +## Learn More + +To learn more about Next.js, take a look at the following resources: + +- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. +- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. + +You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! + +## Deploy on Vercel + +The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. + +Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. diff --git a/packages/www/components/editor.tsx b/packages/www/components/editor.tsx new file mode 100644 index 000000000..73c840bda --- /dev/null +++ b/packages/www/components/editor.tsx @@ -0,0 +1,9 @@ +import { TLDraw } from '@tldraw/tldraw' + +interface EditorProps { + id?: string +} + +export default function Editor({ id = 'home' }: EditorProps) { + return +} diff --git a/next-env.d.ts b/packages/www/next-env.d.ts similarity index 51% rename from next-env.d.ts rename to packages/www/next-env.d.ts index c6643fda1..9bc3dd46b 100644 --- a/next-env.d.ts +++ b/packages/www/next-env.d.ts @@ -1,3 +1,6 @@ /// /// /// + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/basic-features/typescript for more information. diff --git a/packages/www/next.config.js b/packages/www/next.config.js new file mode 100644 index 000000000..af4b6a360 --- /dev/null +++ b/packages/www/next.config.js @@ -0,0 +1,14 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +const withTM = require('next-transpile-modules')(['@tldraw/tldraw']) + +const { NODE_ENV } = process.env + +const isProduction = NODE_ENV === 'production' + +module.exports = withTM({ + reactStrictMode: true, + pwa: { + disable: !isProduction, + dest: 'public', + }, +}) diff --git a/packages/www/package.json b/packages/www/package.json new file mode 100644 index 000000000..795939d3c --- /dev/null +++ b/packages/www/package.json @@ -0,0 +1,37 @@ +{ + "name": "www", + "version": "0.0.59", + "private": true, + "description": "A tiny little drawing app (site).", + "repository": { + "type": "git", + "url": "git+https://github.com/tldraw/tldraw.git" + }, + "license": "MIT", + "author": "@steveruizok", + "scripts": { + "dev": "next dev", + "build": "next build", + "serve": "next serve", + "lint": "next lint" + }, + "dependencies": { + "@stitches/react": "^1.0.0", + "@tldraw/tldraw": "^0.0.59", + "next": "11.1.2", + "next-auth": "3.29.0", + "next-pwa": "^5.2.23", + "next-themes": "^0.0.15", + "next-transpile-modules": "^8.0.0", + "react": "17.0.2", + "react-dom": "17.0.2" + }, + "devDependencies": { + "@types/react": "^17.0.19", + "@types/react-dom": "^17.0.9", + "eslint": "7.32.0", + "eslint-config-next": "11.1.2", + "typescript": "^4.4.2" + }, + "gitHead": "838fabdbff1a66d4d7ee8aa5c5d117bc55acbff2" +} diff --git a/packages/www/pages/_app.tsx b/packages/www/pages/_app.tsx new file mode 100644 index 000000000..1e1cec924 --- /dev/null +++ b/packages/www/pages/_app.tsx @@ -0,0 +1,7 @@ +import '../styles/globals.css' + +function MyApp({ Component, pageProps }) { + return +} + +export default MyApp diff --git a/pages/_document.tsx b/packages/www/pages/_document.tsx similarity index 81% rename from pages/_document.tsx rename to packages/www/pages/_document.tsx index 0ec043039..34f37c5b7 100644 --- a/pages/_document.tsx +++ b/packages/www/pages/_document.tsx @@ -1,12 +1,6 @@ -import NextDocument, { - Html, - Head, - Main, - NextScript, - DocumentContext, -} from 'next/document' -import { getCssString } from 'styles' -import { GA_TRACKING_ID } from 'utils/gtag' +import NextDocument, { Html, Head, Main, NextScript, DocumentContext } from 'next/document' +import { getCssText } from '../styles' +import { GA_TRACKING_ID } from '../utils/gtag' class MyDocument extends NextDocument { static async getInitialProps(ctx: DocumentContext): Promise<{ @@ -22,10 +16,7 @@ class MyDocument extends NextDocument { styles: ( <> {initialProps.styles} -